From e4aa32fecc35206bb73ebe1190d8a3faba28ea9c Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 5 Aug 2025 16:57:58 +0000 Subject: [PATCH 1/3] feat: add accounts API client libraries for v1 PiperOrigin-RevId: 791185257 Source-Link: https://github.com/googleapis/googleapis/commit/d1c0c033f7cdc9a3540ed7eafc7ba096fe56cba5 Source-Link: https://github.com/googleapis/googleapis-gen/commit/725dbb6e34d27f2b313b0b80011f5f7aadd3ffc8 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLXNob3BwaW5nLW1lcmNoYW50LWFjY291bnRzLy5Pd2xCb3QueWFtbCIsImgiOiI3MjVkYmI2ZTM0ZDI3ZjJiMzEzYjBiODAwMTFmNWY3YWFkZDNmZmM4In0= --- .../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 + .../account_issue_service.rst | 10 + .../account_relationships_service.rst | 10 + .../account_services_service.rst | 10 + .../merchant_accounts_v1/accounts_service.rst | 10 + .../autofeed_settings_service.rst | 6 + .../automatic_improvements_service.rst | 6 + .../business_identity_service.rst | 6 + .../business_info_service.rst | 6 + .../checkout_settings_service.rst | 6 + .../developer_registration_service.rst | 6 + .../email_preferences_service.rst | 6 + .../gbp_accounts_service.rst | 10 + .../merchant_accounts_v1/homepage_service.rst | 6 + .../lfp_providers_service.rst | 10 + .../omnichannel_settings_service.rst | 10 + .../online_return_policy_service.rst | 10 + .../merchant_accounts_v1/programs_service.rst | 10 + .../merchant_accounts_v1/regions_service.rst | 10 + .../docs/merchant_accounts_v1/services_.rst | 27 + .../shipping_settings_service.rst | 6 + ...rms_of_service_agreement_state_service.rst | 6 + .../terms_of_service_service.rst | 6 + .../v1/docs/merchant_accounts_v1/types_.rst | 6 + .../merchant_accounts_v1/user_service.rst | 10 + .../v1/docs/multiprocessing.rst | 7 + .../shopping/merchant_accounts/__init__.py | 409 + .../merchant_accounts/gapic_version.py | 16 + .../shopping/merchant_accounts/py.typed | 2 + .../shopping/merchant_accounts_v1/__init__.py | 410 + .../merchant_accounts_v1/gapic_metadata.json | 1477 ++ .../merchant_accounts_v1/gapic_version.py | 16 + .../shopping/merchant_accounts_v1/py.typed | 2 + .../merchant_accounts_v1/services/__init__.py | 15 + .../account_issue_service/__init__.py | 22 + .../account_issue_service/async_client.py | 392 + .../services/account_issue_service/client.py | 761 ++ .../services/account_issue_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_issue_service/transports/base.py | 159 + .../account_issue_service/transports/grpc.py | 353 + .../transports/grpc_asyncio.py | 374 + .../account_issue_service/transports/rest.py | 351 + .../transports/rest_base.py | 128 + .../account_relationships_service/__init__.py | 22 + .../async_client.py | 638 + .../account_relationships_service/client.py | 1005 ++ .../account_relationships_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 187 + .../transports/grpc.py | 399 + .../transports/grpc_asyncio.py | 430 + .../transports/rest.py | 729 + .../transports/rest_base.py | 212 + .../account_services_service/__init__.py | 22 + .../account_services_service/async_client.py | 890 ++ .../account_services_service/client.py | 1255 ++ .../account_services_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 216 + .../transports/grpc.py | 453 + .../transports/grpc_asyncio.py | 494 + .../transports/rest.py | 1058 ++ .../transports/rest_base.py | 307 + .../services/accounts_service/__init__.py | 22 + .../services/accounts_service/async_client.py | 947 ++ .../services/accounts_service/client.py | 1313 ++ .../services/accounts_service/pagers.py | 305 + .../accounts_service/transports/README.rst | 9 + .../accounts_service/transports/__init__.py | 38 + .../accounts_service/transports/base.py | 230 + .../accounts_service/transports/grpc.py | 498 + .../transports/grpc_asyncio.py | 544 + .../accounts_service/transports/rest.py | 1197 ++ .../accounts_service/transports/rest_base.py | 326 + .../autofeed_settings_service/__init__.py | 22 + .../autofeed_settings_service/async_client.py | 493 + .../autofeed_settings_service/client.py | 852 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 374 + .../transports/grpc_asyncio.py | 400 + .../transports/rest.py | 534 + .../transports/rest_base.py | 175 + .../__init__.py | 22 + .../async_client.py | 499 + .../automatic_improvements_service/client.py | 858 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 374 + .../transports/grpc_asyncio.py | 400 + .../transports/rest.py | 537 + .../transports/rest_base.py | 175 + .../business_identity_service/__init__.py | 22 + .../business_identity_service/async_client.py | 502 + .../business_identity_service/client.py | 861 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 375 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 532 + .../transports/rest_base.py | 175 + .../business_info_service/__init__.py | 22 + .../business_info_service/async_client.py | 503 + .../services/business_info_service/client.py | 862 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../business_info_service/transports/base.py | 173 + .../business_info_service/transports/grpc.py | 373 + .../transports/grpc_asyncio.py | 399 + .../business_info_service/transports/rest.py | 537 + .../transports/rest_base.py | 175 + .../checkout_settings_service/__init__.py | 22 + .../checkout_settings_service/async_client.py | 706 + .../checkout_settings_service/client.py | 1063 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 202 + .../transports/grpc.py | 429 + .../transports/grpc_asyncio.py | 465 + .../transports/rest.py | 815 ++ .../transports/rest_base.py | 260 + .../__init__.py | 22 + .../async_client.py | 533 + .../developer_registration_service/client.py | 893 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 188 + .../transports/grpc.py | 405 + .../transports/grpc_asyncio.py | 436 + .../transports/rest.py | 642 + .../transports/rest_base.py | 223 + .../email_preferences_service/__init__.py | 22 + .../email_preferences_service/async_client.py | 511 + .../email_preferences_service/client.py | 870 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 387 + .../transports/grpc_asyncio.py | 413 + .../transports/rest.py | 537 + .../transports/rest_base.py | 175 + .../services/gbp_accounts_service/__init__.py | 22 + .../gbp_accounts_service/async_client.py | 506 + .../services/gbp_accounts_service/client.py | 874 ++ .../services/gbp_accounts_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../gbp_accounts_service/transports/base.py | 173 + .../gbp_accounts_service/transports/grpc.py | 381 + .../transports/grpc_asyncio.py | 407 + .../gbp_accounts_service/transports/rest.py | 535 + .../transports/rest_base.py | 175 + .../services/homepage_service/__init__.py | 22 + .../services/homepage_service/async_client.py | 717 + .../services/homepage_service/client.py | 1076 ++ .../homepage_service/transports/README.rst | 9 + .../homepage_service/transports/__init__.py | 38 + .../homepage_service/transports/base.py | 202 + .../homepage_service/transports/grpc.py | 450 + .../transports/grpc_asyncio.py | 486 + .../homepage_service/transports/rest.py | 918 ++ .../homepage_service/transports/rest_base.py | 270 + .../lfp_providers_service/__init__.py | 22 + .../lfp_providers_service/async_client.py | 503 + .../services/lfp_providers_service/client.py | 871 ++ .../services/lfp_providers_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../lfp_providers_service/transports/base.py | 173 + .../lfp_providers_service/transports/grpc.py | 376 + .../transports/grpc_asyncio.py | 402 + .../lfp_providers_service/transports/rest.py | 534 + .../transports/rest_base.py | 175 + .../omnichannel_settings_service/__init__.py | 22 + .../async_client.py | 866 ++ .../omnichannel_settings_service/client.py | 1231 ++ .../omnichannel_settings_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 215 + .../transports/grpc.py | 459 + .../transports/grpc_asyncio.py | 500 + .../transports/rest.py | 1068 ++ .../transports/rest_base.py | 306 + .../online_return_policy_service/__init__.py | 22 + .../async_client.py | 721 + .../online_return_policy_service/client.py | 1078 ++ .../online_return_policy_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 203 + .../transports/grpc.py | 434 + .../transports/grpc_asyncio.py | 470 + .../transports/rest.py | 827 ++ .../transports/rest_base.py | 251 + .../services/programs_service/__init__.py | 22 + .../services/programs_service/async_client.py | 763 ++ .../services/programs_service/client.py | 1120 ++ .../services/programs_service/pagers.py | 166 + .../programs_service/transports/README.rst | 9 + .../programs_service/transports/__init__.py | 38 + .../programs_service/transports/base.py | 201 + .../programs_service/transports/grpc.py | 436 + .../transports/grpc_asyncio.py | 472 + .../programs_service/transports/rest.py | 934 ++ .../programs_service/transports/rest_base.py | 259 + .../services/regions_service/__init__.py | 22 + .../services/regions_service/async_client.py | 847 ++ .../services/regions_service/client.py | 1212 ++ .../services/regions_service/pagers.py | 166 + .../regions_service/transports/README.rst | 9 + .../regions_service/transports/__init__.py | 38 + .../regions_service/transports/base.py | 216 + .../regions_service/transports/grpc.py | 459 + .../transports/grpc_asyncio.py | 500 + .../regions_service/transports/rest.py | 1004 ++ .../regions_service/transports/rest_base.py | 297 + .../shipping_settings_service/__init__.py | 22 + .../shipping_settings_service/async_client.py | 469 + .../shipping_settings_service/client.py | 838 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 375 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 537 + .../transports/rest_base.py | 175 + .../__init__.py | 22 + .../async_client.py | 537 + .../client.py | 914 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 378 + .../transports/grpc_asyncio.py | 404 + .../transports/rest.py | 581 + .../transports/rest_base.py | 165 + .../terms_of_service_service/__init__.py | 22 + .../terms_of_service_service/async_client.py | 580 + .../terms_of_service_service/client.py | 957 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 187 + .../transports/grpc.py | 402 + .../transports/grpc_asyncio.py | 433 + .../transports/rest.py | 723 + .../transports/rest_base.py | 202 + .../services/user_service/__init__.py | 22 + .../services/user_service/async_client.py | 860 ++ .../services/user_service/client.py | 1225 ++ .../services/user_service/pagers.py | 166 + .../user_service/transports/README.rst | 9 + .../user_service/transports/__init__.py | 38 + .../services/user_service/transports/base.py | 217 + .../services/user_service/transports/grpc.py | 458 + .../user_service/transports/grpc_asyncio.py | 499 + .../services/user_service/transports/rest.py | 995 ++ .../user_service/transports/rest_base.py | 298 + .../merchant_accounts_v1/types/__init__.py | 368 + .../merchant_accounts_v1/types/accessright.py | 61 + .../types/accountissue.py | 239 + .../types/accountrelationships.py | 202 + .../merchant_accounts_v1/types/accounts.py | 429 + .../types/accountservices.py | 450 + .../types/autofeedsettings.py | 111 + .../types/automaticimprovements.py | 386 + .../types/businessidentity.py | 215 + .../types/businessinfo.py | 164 + .../types/checkoutsettings.py | 317 + .../types/customerservice.py | 74 + .../types/developerregistration.py | 123 + .../types/emailpreferences.py | 126 + .../merchant_accounts_v1/types/gbpaccounts.py | 198 + .../merchant_accounts_v1/types/homepage.py | 163 + .../types/lfpproviders.py | 172 + .../types/omnichannelsettings.py | 548 + .../types/online_return_policy.py | 541 + .../types/phoneverificationstate.py | 47 + .../merchant_accounts_v1/types/programs.py | 264 + .../merchant_accounts_v1/types/regions.py | 323 + .../types/shippingsettings.py | 1496 ++ .../types/termsofservice.py | 192 + .../types/termsofserviceagreementstate.py | 220 + .../types/termsofservicekind.py | 44 + .../merchant_accounts_v1/types/user.py | 255 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 591 + ...issue_service_list_account_issues_async.py | 53 + ..._issue_service_list_account_issues_sync.py | 53 + ..._service_get_account_relationship_async.py | 52 + ...s_service_get_account_relationship_sync.py | 52 + ...ervice_list_account_relationships_async.py | 53 + ...service_list_account_relationships_sync.py | 53 + ...rvice_update_account_relationship_async.py | 51 + ...ervice_update_account_relationship_sync.py | 51 + ...s_service_approve_account_service_async.py | 52 + ...es_service_approve_account_service_sync.py | 52 + ...vices_service_get_account_service_async.py | 52 + ...rvices_service_get_account_service_sync.py | 52 + ...ces_service_list_account_services_async.py | 53 + ...ices_service_list_account_services_sync.py | 53 + ...s_service_propose_account_service_async.py | 53 + ...es_service_propose_account_service_sync.py | 53 + ...es_service_reject_account_service_async.py | 50 + ...ces_service_reject_account_service_sync.py | 50 + ...vice_create_and_configure_account_async.py | 56 + ...rvice_create_and_configure_account_sync.py | 56 + ...d_accounts_service_delete_account_async.py | 50 + ...ed_accounts_service_delete_account_sync.py | 50 + ...ated_accounts_service_get_account_async.py | 52 + ...rated_accounts_service_get_account_sync.py | 52 + ...ed_accounts_service_list_accounts_async.py | 52 + ...ted_accounts_service_list_accounts_sync.py | 52 + ...ccounts_service_list_sub_accounts_async.py | 53 + ...accounts_service_list_sub_accounts_sync.py | 53 + ...d_accounts_service_update_account_async.py | 56 + ...ed_accounts_service_update_account_sync.py | 56 + ...ngs_service_get_autofeed_settings_async.py | 52 + ...ings_service_get_autofeed_settings_sync.py | 52 + ..._service_update_autofeed_settings_async.py | 55 + ...s_service_update_autofeed_settings_sync.py | 55 + ...ervice_get_automatic_improvements_async.py | 52 + ...service_get_automatic_improvements_sync.py | 52 + ...ice_update_automatic_improvements_async.py | 51 + ...vice_update_automatic_improvements_sync.py | 51 + ...ity_service_get_business_identity_async.py | 52 + ...tity_service_get_business_identity_sync.py | 52 + ..._service_update_business_identity_async.py | 55 + ...y_service_update_business_identity_sync.py | 55 + ...ss_info_service_get_business_info_async.py | 52 + ...ess_info_service_get_business_info_sync.py | 52 + ...info_service_update_business_info_async.py | 51 + ..._info_service_update_business_info_sync.py | 51 + ..._service_create_checkout_settings_async.py | 52 + ...s_service_create_checkout_settings_sync.py | 52 + ..._service_delete_checkout_settings_async.py | 50 + ...s_service_delete_checkout_settings_sync.py | 50 + ...ngs_service_get_checkout_settings_async.py | 52 + ...ings_service_get_checkout_settings_sync.py | 52 + ..._service_update_checkout_settings_async.py | 51 + ...s_service_update_checkout_settings_sync.py | 51 + ...ervice_get_developer_registration_async.py | 52 + ...service_get_developer_registration_sync.py | 52 + ...registration_service_register_gcp_async.py | 52 + ..._registration_service_register_gcp_sync.py | 52 + ...gistration_service_unregister_gcp_async.py | 50 + ...egistration_service_unregister_gcp_sync.py | 50 + ...ces_service_get_email_preferences_async.py | 52 + ...nces_service_get_email_preferences_sync.py | 52 + ..._service_update_email_preferences_async.py | 51 + ...s_service_update_email_preferences_sync.py | 51 + ...accounts_service_link_gbp_account_async.py | 53 + ..._accounts_service_link_gbp_account_sync.py | 53 + ...ccounts_service_list_gbp_accounts_async.py | 53 + ...accounts_service_list_gbp_accounts_sync.py | 53 + ...d_homepage_service_claim_homepage_async.py | 52 + ...ed_homepage_service_claim_homepage_sync.py | 52 + ...ted_homepage_service_get_homepage_async.py | 52 + ...ated_homepage_service_get_homepage_sync.py | 52 + ...homepage_service_unclaim_homepage_async.py | 52 + ..._homepage_service_unclaim_homepage_sync.py | 52 + ..._homepage_service_update_homepage_async.py | 51 + ...d_homepage_service_update_homepage_sync.py | 51 + ...viders_service_find_lfp_providers_async.py | 53 + ...oviders_service_find_lfp_providers_sync.py | 53 + ...oviders_service_link_lfp_provider_async.py | 53 + ...roviders_service_link_lfp_provider_sync.py | 53 + ...ervice_create_omnichannel_setting_async.py | 57 + ...service_create_omnichannel_setting_sync.py | 57 + ...s_service_get_omnichannel_setting_async.py | 52 + ...gs_service_get_omnichannel_setting_sync.py | 52 + ...service_list_omnichannel_settings_async.py | 53 + ..._service_list_omnichannel_settings_sync.py | 53 + ...ce_request_inventory_verification_async.py | 52 + ...ice_request_inventory_verification_sync.py | 52 + ...ervice_update_omnichannel_setting_async.py | 56 + ...service_update_omnichannel_setting_sync.py | 56 + ...rvice_create_online_return_policy_async.py | 57 + ...ervice_create_online_return_policy_sync.py | 57 + ...rvice_delete_online_return_policy_async.py | 50 + ...ervice_delete_online_return_policy_sync.py | 50 + ..._service_get_online_return_policy_async.py | 52 + ...y_service_get_online_return_policy_sync.py | 52 + ...rvice_list_online_return_policies_async.py | 53 + ...ervice_list_online_return_policies_sync.py | 53 + ..._programs_service_disable_program_async.py | 52 + ...d_programs_service_disable_program_sync.py | 52 + ...d_programs_service_enable_program_async.py | 52 + ...ed_programs_service_enable_program_sync.py | 52 + ...ated_programs_service_get_program_async.py | 52 + ...rated_programs_service_get_program_sync.py | 52 + ...ed_programs_service_list_programs_async.py | 53 + ...ted_programs_service_list_programs_sync.py | 53 + ...ted_regions_service_create_region_async.py | 53 + ...ated_regions_service_create_region_sync.py | 53 + ...ted_regions_service_delete_region_async.py | 50 + ...ated_regions_service_delete_region_sync.py | 50 + ...erated_regions_service_get_region_async.py | 52 + ...nerated_regions_service_get_region_sync.py | 52 + ...ated_regions_service_list_regions_async.py | 53 + ...rated_regions_service_list_regions_sync.py | 53 + ...ted_regions_service_update_region_async.py | 51 + ...ated_regions_service_update_region_sync.py | 51 + ...ngs_service_get_shipping_settings_async.py | 52 + ...ings_service_get_shipping_settings_sync.py | 52 + ..._service_insert_shipping_settings_async.py | 56 + ...s_service_insert_shipping_settings_sync.py | 56 + ..._terms_of_service_agreement_state_async.py | 52 + ...t_terms_of_service_agreement_state_sync.py | 52 + ..._terms_of_service_agreement_state_async.py | 52 + ...n_terms_of_service_agreement_state_sync.py | 52 + ...e_service_accept_terms_of_service_async.py | 54 + ...ce_service_accept_terms_of_service_sync.py | 54 + ...vice_service_get_terms_of_service_async.py | 52 + ...rvice_service_get_terms_of_service_sync.py | 52 + ..._retrieve_latest_terms_of_service_async.py | 53 + ...e_retrieve_latest_terms_of_service_sync.py | 53 + ...enerated_user_service_create_user_async.py | 53 + ...generated_user_service_create_user_sync.py | 53 + ...enerated_user_service_delete_user_async.py | 50 + ...generated_user_service_delete_user_sync.py | 50 + ...1_generated_user_service_get_user_async.py | 52 + ...v1_generated_user_service_get_user_sync.py | 52 + ...generated_user_service_list_users_async.py | 53 + ..._generated_user_service_list_users_sync.py | 53 + ...enerated_user_service_update_user_async.py | 55 + ...generated_user_service_update_user_sync.py | 55 + ..._google.shopping.merchant.accounts.v1.json | 11347 ++++++++++++++++ .../fixup_merchant_accounts_v1_keywords.py | 245 + .../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_accounts_v1/__init__.py | 16 + .../test_account_issue_service.py | 2418 ++++ .../test_account_relationships_service.py | 3845 ++++++ .../test_account_services_service.py | 5133 +++++++ .../test_accounts_service.py | 5633 ++++++++ .../test_autofeed_settings_service.py | 2890 ++++ .../test_automatic_improvements_service.py | 2862 ++++ .../test_business_identity_service.py | 2876 ++++ .../test_business_info_service.py | 2894 ++++ .../test_checkout_settings_service.py | 4334 ++++++ .../test_developer_registration_service.py | 3166 +++++ .../test_email_preferences_service.py | 2878 ++++ .../test_gbp_accounts_service.py | 3072 +++++ .../test_homepage_service.py | 3965 ++++++ .../test_lfp_providers_service.py | 3076 +++++ .../test_omnichannel_settings_service.py | 5231 +++++++ .../test_online_return_policy_service.py | 4561 +++++++ .../test_programs_service.py | 4435 ++++++ .../test_regions_service.py | 5216 +++++++ .../test_shipping_settings_service.py | 2750 ++++ ...erms_of_service_agreement_state_service.py | 2854 ++++ .../test_terms_of_service_service.py | 3373 +++++ .../merchant_accounts_v1/test_user_service.py | 5238 +++++++ .../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 + .../account_issue_service.rst | 10 + .../account_tax_service.rst | 10 + .../accounts_service.rst | 10 + .../autofeed_settings_service.rst | 6 + .../automatic_improvements_service.rst | 6 + .../business_identity_service.rst | 6 + .../business_info_service.rst | 6 + .../checkout_settings_service.rst | 6 + .../email_preferences_service.rst | 6 + .../gbp_accounts_service.rst | 10 + .../homepage_service.rst | 6 + .../lfp_providers_service.rst | 10 + .../omnichannel_settings_service.rst | 10 + .../online_return_policy_service.rst | 10 + .../programs_service.rst | 10 + .../regions_service.rst | 10 + .../merchant_accounts_v1beta/services_.rst | 25 + .../shipping_settings_service.rst | 6 + ...rms_of_service_agreement_state_service.rst | 6 + .../terms_of_service_service.rst | 6 + .../docs/merchant_accounts_v1beta/types_.rst | 6 + .../merchant_accounts_v1beta/user_service.rst | 10 + .../v1beta/docs/multiprocessing.rst | 7 + .../shopping/merchant_accounts/__init__.py | 371 + .../merchant_accounts/gapic_version.py | 16 + .../shopping/merchant_accounts/py.typed | 2 + .../merchant_accounts_v1beta/__init__.py | 372 + .../gapic_metadata.json | 1334 ++ .../merchant_accounts_v1beta/gapic_version.py | 16 + .../merchant_accounts_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../account_issue_service/__init__.py | 22 + .../account_issue_service/async_client.py | 386 + .../services/account_issue_service/client.py | 755 + .../services/account_issue_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_issue_service/transports/base.py | 159 + .../account_issue_service/transports/grpc.py | 347 + .../transports/grpc_asyncio.py | 368 + .../account_issue_service/transports/rest.py | 351 + .../transports/rest_base.py | 128 + .../services/account_tax_service/__init__.py | 22 + .../account_tax_service/async_client.py | 623 + .../services/account_tax_service/client.py | 981 ++ .../services/account_tax_service/pagers.py | 166 + .../account_tax_service/transports/README.rst | 9 + .../transports/__init__.py | 38 + .../account_tax_service/transports/base.py | 188 + .../account_tax_service/transports/grpc.py | 407 + .../transports/grpc_asyncio.py | 438 + .../account_tax_service/transports/rest.py | 715 + .../transports/rest_base.py | 213 + .../services/accounts_service/__init__.py | 22 + .../services/accounts_service/async_client.py | 894 ++ .../services/accounts_service/client.py | 1269 ++ .../services/accounts_service/pagers.py | 305 + .../accounts_service/transports/README.rst | 9 + .../accounts_service/transports/__init__.py | 38 + .../accounts_service/transports/base.py | 230 + .../accounts_service/transports/grpc.py | 501 + .../transports/grpc_asyncio.py | 547 + .../accounts_service/transports/rest.py | 1149 ++ .../accounts_service/transports/rest_base.py | 326 + .../autofeed_settings_service/__init__.py | 22 + .../autofeed_settings_service/async_client.py | 493 + .../autofeed_settings_service/client.py | 852 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 374 + .../transports/grpc_asyncio.py | 400 + .../transports/rest.py | 534 + .../transports/rest_base.py | 175 + .../__init__.py | 22 + .../async_client.py | 499 + .../automatic_improvements_service/client.py | 858 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 374 + .../transports/grpc_asyncio.py | 400 + .../transports/rest.py | 537 + .../transports/rest_base.py | 175 + .../business_identity_service/__init__.py | 22 + .../business_identity_service/async_client.py | 488 + .../business_identity_service/client.py | 847 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 375 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 532 + .../transports/rest_base.py | 175 + .../business_info_service/__init__.py | 22 + .../business_info_service/async_client.py | 488 + .../services/business_info_service/client.py | 847 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../business_info_service/transports/base.py | 173 + .../business_info_service/transports/grpc.py | 373 + .../transports/grpc_asyncio.py | 399 + .../business_info_service/transports/rest.py | 529 + .../transports/rest_base.py | 175 + .../checkout_settings_service/__init__.py | 22 + .../checkout_settings_service/async_client.py | 706 + .../checkout_settings_service/client.py | 1063 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 202 + .../transports/grpc.py | 429 + .../transports/grpc_asyncio.py | 465 + .../transports/rest.py | 815 ++ .../transports/rest_base.py | 260 + .../email_preferences_service/__init__.py | 22 + .../email_preferences_service/async_client.py | 511 + .../email_preferences_service/client.py | 870 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 390 + .../transports/grpc_asyncio.py | 416 + .../transports/rest.py | 540 + .../transports/rest_base.py | 175 + .../services/gbp_accounts_service/__init__.py | 22 + .../gbp_accounts_service/async_client.py | 502 + .../services/gbp_accounts_service/client.py | 870 ++ .../services/gbp_accounts_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../gbp_accounts_service/transports/base.py | 173 + .../gbp_accounts_service/transports/grpc.py | 377 + .../transports/grpc_asyncio.py | 403 + .../gbp_accounts_service/transports/rest.py | 535 + .../transports/rest_base.py | 175 + .../services/homepage_service/__init__.py | 22 + .../services/homepage_service/async_client.py | 658 + .../services/homepage_service/client.py | 1017 ++ .../homepage_service/transports/README.rst | 9 + .../homepage_service/transports/__init__.py | 38 + .../homepage_service/transports/base.py | 202 + .../homepage_service/transports/grpc.py | 439 + .../transports/grpc_asyncio.py | 475 + .../homepage_service/transports/rest.py | 874 ++ .../homepage_service/transports/rest_base.py | 270 + .../lfp_providers_service/__init__.py | 22 + .../lfp_providers_service/async_client.py | 503 + .../services/lfp_providers_service/client.py | 871 ++ .../services/lfp_providers_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../lfp_providers_service/transports/base.py | 173 + .../lfp_providers_service/transports/grpc.py | 376 + .../transports/grpc_asyncio.py | 402 + .../lfp_providers_service/transports/rest.py | 534 + .../transports/rest_base.py | 175 + .../omnichannel_settings_service/__init__.py | 22 + .../async_client.py | 866 ++ .../omnichannel_settings_service/client.py | 1231 ++ .../omnichannel_settings_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 215 + .../transports/grpc.py | 459 + .../transports/grpc_asyncio.py | 500 + .../transports/rest.py | 1068 ++ .../transports/rest_base.py | 306 + .../online_return_policy_service/__init__.py | 22 + .../async_client.py | 860 ++ .../online_return_policy_service/client.py | 1216 ++ .../online_return_policy_service/pagers.py | 166 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 217 + .../transports/grpc.py | 461 + .../transports/grpc_asyncio.py | 502 + .../transports/rest.py | 1009 ++ .../transports/rest_base.py | 298 + .../services/programs_service/__init__.py | 22 + .../services/programs_service/async_client.py | 740 + .../services/programs_service/client.py | 1097 ++ .../services/programs_service/pagers.py | 166 + .../programs_service/transports/README.rst | 9 + .../programs_service/transports/__init__.py | 38 + .../programs_service/transports/base.py | 201 + .../programs_service/transports/grpc.py | 437 + .../transports/grpc_asyncio.py | 473 + .../programs_service/transports/rest.py | 913 ++ .../programs_service/transports/rest_base.py | 259 + .../services/regions_service/__init__.py | 22 + .../services/regions_service/async_client.py | 847 ++ .../services/regions_service/client.py | 1212 ++ .../services/regions_service/pagers.py | 166 + .../regions_service/transports/README.rst | 9 + .../regions_service/transports/__init__.py | 38 + .../regions_service/transports/base.py | 216 + .../regions_service/transports/grpc.py | 459 + .../transports/grpc_asyncio.py | 500 + .../regions_service/transports/rest.py | 1004 ++ .../regions_service/transports/rest_base.py | 297 + .../shipping_settings_service/__init__.py | 22 + .../shipping_settings_service/async_client.py | 461 + .../shipping_settings_service/client.py | 821 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 375 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 531 + .../transports/rest_base.py | 175 + .../__init__.py | 22 + .../async_client.py | 536 + .../client.py | 913 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 173 + .../transports/grpc.py | 375 + .../transports/grpc_asyncio.py | 401 + .../transports/rest.py | 583 + .../transports/rest_base.py | 165 + .../terms_of_service_service/__init__.py | 22 + .../terms_of_service_service/async_client.py | 543 + .../terms_of_service_service/client.py | 911 ++ .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../transports/base.py | 188 + .../transports/grpc.py | 403 + .../transports/grpc_asyncio.py | 434 + .../transports/rest.py | 630 + .../transports/rest_base.py | 203 + .../services/user_service/__init__.py | 22 + .../services/user_service/async_client.py | 827 ++ .../services/user_service/client.py | 1192 ++ .../services/user_service/pagers.py | 166 + .../user_service/transports/README.rst | 9 + .../user_service/transports/__init__.py | 38 + .../services/user_service/transports/base.py | 217 + .../services/user_service/transports/grpc.py | 455 + .../user_service/transports/grpc_asyncio.py | 496 + .../services/user_service/transports/rest.py | 983 ++ .../user_service/transports/rest_base.py | 298 + .../types/__init__.py | 338 + .../types/accessright.py | 51 + .../types/account_tax.py | 167 + .../types/accountissue.py | 236 + .../types/accounts.py | 408 + .../types/accountservices.py | 36 + .../types/autofeedsettings.py | 111 + .../types/automaticimprovements.py | 386 + .../types/businessidentity.py | 204 + .../types/businessinfo.py | 148 + .../types/checkoutsettings.py | 316 + .../types/customerservice.py | 74 + .../types/emailpreferences.py | 121 + .../types/gbpaccounts.py | 198 + .../types/homepage.py | 139 + .../types/lfpproviders.py | 172 + .../types/omnichannelsettings.py | 548 + .../types/online_return_policy.py | 581 + .../types/phoneverificationstate.py | 47 + .../types/programs.py | 254 + .../merchant_accounts_v1beta/types/regions.py | 323 + .../types/shippingsettings.py | 1489 ++ .../types/tax_rule.py | 149 + .../types/termsofservice.py | 164 + .../types/termsofserviceagreementstate.py | 217 + .../types/termsofservicekind.py | 44 + .../merchant_accounts_v1beta/types/user.py | 246 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 591 + ...issue_service_list_account_issues_async.py | 53 + ..._issue_service_list_account_issues_sync.py | 53 + ...count_tax_service_get_account_tax_async.py | 52 + ...ccount_tax_service_get_account_tax_sync.py | 52 + ...ount_tax_service_list_account_tax_async.py | 53 + ...count_tax_service_list_account_tax_sync.py | 53 + ...nt_tax_service_update_account_tax_async.py | 51 + ...unt_tax_service_update_account_tax_sync.py | 51 + ...vice_create_and_configure_account_async.py | 56 + ...rvice_create_and_configure_account_sync.py | 56 + ...d_accounts_service_delete_account_async.py | 50 + ...ed_accounts_service_delete_account_sync.py | 50 + ...ated_accounts_service_get_account_async.py | 52 + ...rated_accounts_service_get_account_sync.py | 52 + ...ed_accounts_service_list_accounts_async.py | 52 + ...ted_accounts_service_list_accounts_sync.py | 52 + ...ccounts_service_list_sub_accounts_async.py | 53 + ...accounts_service_list_sub_accounts_sync.py | 53 + ...d_accounts_service_update_account_async.py | 56 + ...ed_accounts_service_update_account_sync.py | 56 + ...ngs_service_get_autofeed_settings_async.py | 52 + ...ings_service_get_autofeed_settings_sync.py | 52 + ..._service_update_autofeed_settings_async.py | 55 + ...s_service_update_autofeed_settings_sync.py | 55 + ...ervice_get_automatic_improvements_async.py | 52 + ...service_get_automatic_improvements_sync.py | 52 + ...ice_update_automatic_improvements_async.py | 51 + ...vice_update_automatic_improvements_sync.py | 51 + ...ity_service_get_business_identity_async.py | 52 + ...tity_service_get_business_identity_sync.py | 52 + ..._service_update_business_identity_async.py | 51 + ...y_service_update_business_identity_sync.py | 51 + ...ss_info_service_get_business_info_async.py | 52 + ...ess_info_service_get_business_info_sync.py | 52 + ...info_service_update_business_info_async.py | 51 + ..._info_service_update_business_info_sync.py | 51 + ..._service_create_checkout_settings_async.py | 52 + ...s_service_create_checkout_settings_sync.py | 52 + ..._service_delete_checkout_settings_async.py | 50 + ...s_service_delete_checkout_settings_sync.py | 50 + ...ngs_service_get_checkout_settings_async.py | 52 + ...ings_service_get_checkout_settings_sync.py | 52 + ..._service_update_checkout_settings_async.py | 51 + ...s_service_update_checkout_settings_sync.py | 51 + ...ces_service_get_email_preferences_async.py | 52 + ...nces_service_get_email_preferences_sync.py | 52 + ..._service_update_email_preferences_async.py | 51 + ...s_service_update_email_preferences_sync.py | 51 + ...accounts_service_link_gbp_account_async.py | 53 + ..._accounts_service_link_gbp_account_sync.py | 53 + ...ccounts_service_list_gbp_accounts_async.py | 53 + ...accounts_service_list_gbp_accounts_sync.py | 53 + ...d_homepage_service_claim_homepage_async.py | 52 + ...ed_homepage_service_claim_homepage_sync.py | 52 + ...ted_homepage_service_get_homepage_async.py | 52 + ...ated_homepage_service_get_homepage_sync.py | 52 + ...homepage_service_unclaim_homepage_async.py | 52 + ..._homepage_service_unclaim_homepage_sync.py | 52 + ..._homepage_service_update_homepage_async.py | 51 + ...d_homepage_service_update_homepage_sync.py | 51 + ...viders_service_find_lfp_providers_async.py | 53 + ...oviders_service_find_lfp_providers_sync.py | 53 + ...oviders_service_link_lfp_provider_async.py | 53 + ...roviders_service_link_lfp_provider_sync.py | 53 + ...ervice_create_omnichannel_setting_async.py | 57 + ...service_create_omnichannel_setting_sync.py | 57 + ...s_service_get_omnichannel_setting_async.py | 52 + ...gs_service_get_omnichannel_setting_sync.py | 52 + ...service_list_omnichannel_settings_async.py | 53 + ..._service_list_omnichannel_settings_sync.py | 53 + ...ce_request_inventory_verification_async.py | 52 + ...ice_request_inventory_verification_sync.py | 52 + ...ervice_update_omnichannel_setting_async.py | 56 + ...service_update_omnichannel_setting_sync.py | 56 + ...rvice_create_online_return_policy_async.py | 58 + ...ervice_create_online_return_policy_sync.py | 58 + ...rvice_delete_online_return_policy_async.py | 50 + ...ervice_delete_online_return_policy_sync.py | 50 + ..._service_get_online_return_policy_async.py | 52 + ...y_service_get_online_return_policy_sync.py | 52 + ...rvice_list_online_return_policies_async.py | 53 + ...ervice_list_online_return_policies_sync.py | 53 + ...rvice_update_online_return_policy_async.py | 57 + ...ervice_update_online_return_policy_sync.py | 57 + ..._programs_service_disable_program_async.py | 52 + ...d_programs_service_disable_program_sync.py | 52 + ...d_programs_service_enable_program_async.py | 52 + ...ed_programs_service_enable_program_sync.py | 52 + ...ated_programs_service_get_program_async.py | 52 + ...rated_programs_service_get_program_sync.py | 52 + ...ed_programs_service_list_programs_async.py | 53 + ...ted_programs_service_list_programs_sync.py | 53 + ...ted_regions_service_create_region_async.py | 53 + ...ated_regions_service_create_region_sync.py | 53 + ...ted_regions_service_delete_region_async.py | 50 + ...ated_regions_service_delete_region_sync.py | 50 + ...erated_regions_service_get_region_async.py | 52 + ...nerated_regions_service_get_region_sync.py | 52 + ...ated_regions_service_list_regions_async.py | 53 + ...rated_regions_service_list_regions_sync.py | 53 + ...ted_regions_service_update_region_async.py | 51 + ...ated_regions_service_update_region_sync.py | 51 + ...ngs_service_get_shipping_settings_async.py | 52 + ...ings_service_get_shipping_settings_sync.py | 52 + ..._service_insert_shipping_settings_async.py | 56 + ...s_service_insert_shipping_settings_sync.py | 56 + ..._terms_of_service_agreement_state_async.py | 52 + ...t_terms_of_service_agreement_state_sync.py | 52 + ..._terms_of_service_agreement_state_async.py | 52 + ...n_terms_of_service_agreement_state_sync.py | 52 + ...e_service_accept_terms_of_service_async.py | 52 + ...ce_service_accept_terms_of_service_sync.py | 52 + ...vice_service_get_terms_of_service_async.py | 52 + ...rvice_service_get_terms_of_service_sync.py | 52 + ..._retrieve_latest_terms_of_service_async.py | 53 + ...e_retrieve_latest_terms_of_service_sync.py | 53 + ...enerated_user_service_create_user_async.py | 53 + ...generated_user_service_create_user_sync.py | 53 + ...enerated_user_service_delete_user_async.py | 50 + ...generated_user_service_delete_user_sync.py | 50 + ...a_generated_user_service_get_user_async.py | 52 + ...ta_generated_user_service_get_user_sync.py | 52 + ...generated_user_service_list_users_async.py | 53 + ..._generated_user_service_list_users_sync.py | 53 + ...enerated_user_service_update_user_async.py | 51 + ...generated_user_service_update_user_sync.py | 51 + ...gle.shopping.merchant.accounts.v1beta.json | 10226 ++++++++++++++ ...fixup_merchant_accounts_v1beta_keywords.py | 238 + .../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_accounts_v1beta/__init__.py | 16 + .../test_account_issue_service.py | 2418 ++++ .../test_account_tax_service.py | 3803 ++++++ .../test_accounts_service.py | 5650 ++++++++ .../test_autofeed_settings_service.py | 2890 ++++ .../test_automatic_improvements_service.py | 2862 ++++ .../test_business_identity_service.py | 2876 ++++ .../test_business_info_service.py | 2894 ++++ .../test_checkout_settings_service.py | 4334 ++++++ .../test_email_preferences_service.py | 2878 ++++ .../test_gbp_accounts_service.py | 3072 +++++ .../test_homepage_service.py | 3965 ++++++ .../test_lfp_providers_service.py | 3076 +++++ .../test_omnichannel_settings_service.py | 5231 +++++++ .../test_online_return_policy_service.py | 5362 ++++++++ .../test_programs_service.py | 4435 ++++++ .../test_regions_service.py | 5216 +++++++ .../test_shipping_settings_service.py | 2733 ++++ ...erms_of_service_agreement_state_service.py | 2854 ++++ .../test_terms_of_service_service.py | 3331 +++++ .../test_user_service.py | 5226 +++++++ 917 files changed, 375303 insertions(+) create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/LICENSE create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_issue_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_relationships_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_services_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/accounts_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/autofeed_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/automatic_improvements_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_identity_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_info_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/checkout_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/developer_registration_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/email_preferences_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/gbp_accounts_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/homepage_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/lfp_providers_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/omnichannel_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/online_return_policy_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/programs_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/regions_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/shipping_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/user_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/scripts/fixup_merchant_accounts_v1_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/.flake8 create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/LICENSE create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/setup.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/__init__.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py create mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc b/owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc new file mode 100644 index 000000000000..8338bbe3403b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_accounts/__init__.py + google/shopping/merchant_accounts/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-accounts/v1/.flake8 b/owl-bot-staging/google-shopping-merchant-accounts/v1/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/LICENSE b/owl-bot-staging/google-shopping-merchant-accounts/v1/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-accounts/v1/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/README.rst new file mode 100644 index 000000000000..419480c445c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Shopping Merchant Accounts 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 Accounts 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-accounts/v1/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/docs/conf.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/conf.py new file mode 100644 index 000000000000..11bd96e58d11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts 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-accounts" +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-accounts", + "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-accounts-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-accounts.tex", + u"google-shopping-merchant-accounts 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-accounts", + "google-shopping-merchant-accounts 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-accounts", + "google-shopping-merchant-accounts Documentation", + author, + "google-shopping-merchant-accounts", + "google-shopping-merchant-accounts 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-accounts/v1/docs/index.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/index.rst new file mode 100644 index 000000000000..3155169d729f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_accounts_v1/services_ + merchant_accounts_v1/types_ diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_issue_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_issue_service.rst new file mode 100644 index 000000000000..35d53a9ea009 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_issue_service.rst @@ -0,0 +1,10 @@ +AccountIssueService +------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.account_issue_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.account_issue_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_relationships_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_relationships_service.rst new file mode 100644 index 000000000000..bad86c16ea68 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_relationships_service.rst @@ -0,0 +1,10 @@ +AccountRelationshipsService +--------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.account_relationships_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.account_relationships_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_services_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_services_service.rst new file mode 100644 index 000000000000..52d0a8771015 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_services_service.rst @@ -0,0 +1,10 @@ +AccountServicesService +---------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.account_services_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.account_services_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/accounts_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/accounts_service.rst new file mode 100644 index 000000000000..a0d42d724ad0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/accounts_service.rst @@ -0,0 +1,10 @@ +AccountsService +--------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.accounts_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.accounts_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/autofeed_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/autofeed_settings_service.rst new file mode 100644 index 000000000000..6dbc67ca69ea --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/autofeed_settings_service.rst @@ -0,0 +1,6 @@ +AutofeedSettingsService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.autofeed_settings_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/automatic_improvements_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/automatic_improvements_service.rst new file mode 100644 index 000000000000..eb03f0ddd0e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/automatic_improvements_service.rst @@ -0,0 +1,6 @@ +AutomaticImprovementsService +---------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.automatic_improvements_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_identity_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_identity_service.rst new file mode 100644 index 000000000000..6ee0be19654d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_identity_service.rst @@ -0,0 +1,6 @@ +BusinessIdentityService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.business_identity_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_info_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_info_service.rst new file mode 100644 index 000000000000..0f04d3e17a2a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_info_service.rst @@ -0,0 +1,6 @@ +BusinessInfoService +------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.business_info_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/checkout_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/checkout_settings_service.rst new file mode 100644 index 000000000000..1d1f318edc0f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/checkout_settings_service.rst @@ -0,0 +1,6 @@ +CheckoutSettingsService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.checkout_settings_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/developer_registration_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/developer_registration_service.rst new file mode 100644 index 000000000000..8597be0e4123 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/developer_registration_service.rst @@ -0,0 +1,6 @@ +DeveloperRegistrationService +---------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.developer_registration_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/email_preferences_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/email_preferences_service.rst new file mode 100644 index 000000000000..f1aa4fc71425 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/email_preferences_service.rst @@ -0,0 +1,6 @@ +EmailPreferencesService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.email_preferences_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/gbp_accounts_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/gbp_accounts_service.rst new file mode 100644 index 000000000000..d38aab192cb7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/gbp_accounts_service.rst @@ -0,0 +1,10 @@ +GbpAccountsService +------------------------------------ + +.. automodule:: google.shopping.merchant_accounts_v1.services.gbp_accounts_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.gbp_accounts_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/homepage_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/homepage_service.rst new file mode 100644 index 000000000000..050cdd84dc78 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/homepage_service.rst @@ -0,0 +1,6 @@ +HomepageService +--------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.homepage_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/lfp_providers_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/lfp_providers_service.rst new file mode 100644 index 000000000000..c353290f667a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/lfp_providers_service.rst @@ -0,0 +1,10 @@ +LfpProvidersService +------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.lfp_providers_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.lfp_providers_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/omnichannel_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/omnichannel_settings_service.rst new file mode 100644 index 000000000000..23c3b54d9a04 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/omnichannel_settings_service.rst @@ -0,0 +1,10 @@ +OmnichannelSettingsService +-------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.omnichannel_settings_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/online_return_policy_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/online_return_policy_service.rst new file mode 100644 index 000000000000..c799ac77156a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/online_return_policy_service.rst @@ -0,0 +1,10 @@ +OnlineReturnPolicyService +------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.online_return_policy_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.online_return_policy_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/programs_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/programs_service.rst new file mode 100644 index 000000000000..b55429de7302 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/programs_service.rst @@ -0,0 +1,10 @@ +ProgramsService +--------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.programs_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.programs_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/regions_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/regions_service.rst new file mode 100644 index 000000000000..3db184703dfb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/regions_service.rst @@ -0,0 +1,10 @@ +RegionsService +-------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.regions_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.regions_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/services_.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/services_.rst new file mode 100644 index 000000000000..074a322ada11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/services_.rst @@ -0,0 +1,27 @@ +Services for Google Shopping Merchant Accounts v1 API +===================================================== +.. toctree:: + :maxdepth: 2 + + account_issue_service + account_relationships_service + account_services_service + accounts_service + autofeed_settings_service + automatic_improvements_service + business_identity_service + business_info_service + checkout_settings_service + developer_registration_service + email_preferences_service + gbp_accounts_service + homepage_service + lfp_providers_service + omnichannel_settings_service + online_return_policy_service + programs_service + regions_service + shipping_settings_service + terms_of_service_agreement_state_service + terms_of_service_service + user_service diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/shipping_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/shipping_settings_service.rst new file mode 100644 index 000000000000..8e80ae015bfc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/shipping_settings_service.rst @@ -0,0 +1,6 @@ +ShippingSettingsService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.shipping_settings_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst new file mode 100644 index 000000000000..09dadc4b109b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst @@ -0,0 +1,6 @@ +TermsOfServiceAgreementStateService +----------------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_service.rst new file mode 100644 index 000000000000..f0be154933b7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_service.rst @@ -0,0 +1,6 @@ +TermsOfServiceService +--------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.terms_of_service_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/types_.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/types_.rst new file mode 100644 index 000000000000..b687f33f8552 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Accounts v1 API +================================================== + +.. automodule:: google.shopping.merchant_accounts_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/user_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/user_service.rst new file mode 100644 index 000000000000..a4ff3642a88f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/user_service.rst @@ -0,0 +1,10 @@ +UserService +----------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1.services.user_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1.services.user_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/google/shopping/merchant_accounts/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/__init__.py new file mode 100644 index 000000000000..ba62edbc93f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/__init__.py @@ -0,0 +1,409 @@ +# -*- 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_accounts import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_accounts_v1.services.account_issue_service.client import AccountIssueServiceClient +from google.shopping.merchant_accounts_v1.services.account_issue_service.async_client import AccountIssueServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.account_relationships_service.client import AccountRelationshipsServiceClient +from google.shopping.merchant_accounts_v1.services.account_relationships_service.async_client import AccountRelationshipsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.account_services_service.client import AccountServicesServiceClient +from google.shopping.merchant_accounts_v1.services.account_services_service.async_client import AccountServicesServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.accounts_service.client import AccountsServiceClient +from google.shopping.merchant_accounts_v1.services.accounts_service.async_client import AccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.autofeed_settings_service.client import AutofeedSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.autofeed_settings_service.async_client import AutofeedSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.automatic_improvements_service.client import AutomaticImprovementsServiceClient +from google.shopping.merchant_accounts_v1.services.automatic_improvements_service.async_client import AutomaticImprovementsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.business_identity_service.client import BusinessIdentityServiceClient +from google.shopping.merchant_accounts_v1.services.business_identity_service.async_client import BusinessIdentityServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.business_info_service.client import BusinessInfoServiceClient +from google.shopping.merchant_accounts_v1.services.business_info_service.async_client import BusinessInfoServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.checkout_settings_service.client import CheckoutSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.checkout_settings_service.async_client import CheckoutSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.developer_registration_service.client import DeveloperRegistrationServiceClient +from google.shopping.merchant_accounts_v1.services.developer_registration_service.async_client import DeveloperRegistrationServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.email_preferences_service.client import EmailPreferencesServiceClient +from google.shopping.merchant_accounts_v1.services.email_preferences_service.async_client import EmailPreferencesServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service.client import GbpAccountsServiceClient +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service.async_client import GbpAccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.homepage_service.client import HomepageServiceClient +from google.shopping.merchant_accounts_v1.services.homepage_service.async_client import HomepageServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.lfp_providers_service.client import LfpProvidersServiceClient +from google.shopping.merchant_accounts_v1.services.lfp_providers_service.async_client import LfpProvidersServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.client import OmnichannelSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.async_client import OmnichannelSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.online_return_policy_service.client import OnlineReturnPolicyServiceClient +from google.shopping.merchant_accounts_v1.services.online_return_policy_service.async_client import OnlineReturnPolicyServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.programs_service.client import ProgramsServiceClient +from google.shopping.merchant_accounts_v1.services.programs_service.async_client import ProgramsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.regions_service.client import RegionsServiceClient +from google.shopping.merchant_accounts_v1.services.regions_service.async_client import RegionsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.shipping_settings_service.client import ShippingSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.shipping_settings_service.async_client import ShippingSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.client import TermsOfServiceAgreementStateServiceClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.async_client import TermsOfServiceAgreementStateServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_service.client import TermsOfServiceServiceClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_service.async_client import TermsOfServiceServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.user_service.client import UserServiceClient +from google.shopping.merchant_accounts_v1.services.user_service.async_client import UserServiceAsyncClient + +from google.shopping.merchant_accounts_v1.types.accessright import AccessRight +from google.shopping.merchant_accounts_v1.types.accountissue import AccountIssue +from google.shopping.merchant_accounts_v1.types.accountissue import ListAccountIssuesRequest +from google.shopping.merchant_accounts_v1.types.accountissue import ListAccountIssuesResponse +from google.shopping.merchant_accounts_v1.types.accountrelationships import AccountRelationship +from google.shopping.merchant_accounts_v1.types.accountrelationships import GetAccountRelationshipRequest +from google.shopping.merchant_accounts_v1.types.accountrelationships import ListAccountRelationshipsRequest +from google.shopping.merchant_accounts_v1.types.accountrelationships import ListAccountRelationshipsResponse +from google.shopping.merchant_accounts_v1.types.accountrelationships import UpdateAccountRelationshipRequest +from google.shopping.merchant_accounts_v1.types.accounts import Account +from google.shopping.merchant_accounts_v1.types.accounts import CreateAndConfigureAccountRequest +from google.shopping.merchant_accounts_v1.types.accounts import DeleteAccountRequest +from google.shopping.merchant_accounts_v1.types.accounts import GetAccountRequest +from google.shopping.merchant_accounts_v1.types.accounts import ListAccountsRequest +from google.shopping.merchant_accounts_v1.types.accounts import ListAccountsResponse +from google.shopping.merchant_accounts_v1.types.accounts import ListSubAccountsRequest +from google.shopping.merchant_accounts_v1.types.accounts import ListSubAccountsResponse +from google.shopping.merchant_accounts_v1.types.accounts import UpdateAccountRequest +from google.shopping.merchant_accounts_v1.types.accountservices import AccountAggregation +from google.shopping.merchant_accounts_v1.types.accountservices import AccountManagement +from google.shopping.merchant_accounts_v1.types.accountservices import AccountService +from google.shopping.merchant_accounts_v1.types.accountservices import ApproveAccountServiceRequest +from google.shopping.merchant_accounts_v1.types.accountservices import CampaignsManagement +from google.shopping.merchant_accounts_v1.types.accountservices import GetAccountServiceRequest +from google.shopping.merchant_accounts_v1.types.accountservices import Handshake +from google.shopping.merchant_accounts_v1.types.accountservices import ListAccountServicesRequest +from google.shopping.merchant_accounts_v1.types.accountservices import ListAccountServicesResponse +from google.shopping.merchant_accounts_v1.types.accountservices import LocalListingManagement +from google.shopping.merchant_accounts_v1.types.accountservices import ProductsManagement +from google.shopping.merchant_accounts_v1.types.accountservices import ProposeAccountServiceRequest +from google.shopping.merchant_accounts_v1.types.accountservices import RejectAccountServiceRequest +from google.shopping.merchant_accounts_v1.types.autofeedsettings import AutofeedSettings +from google.shopping.merchant_accounts_v1.types.autofeedsettings import GetAutofeedSettingsRequest +from google.shopping.merchant_accounts_v1.types.autofeedsettings import UpdateAutofeedSettingsRequest +from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticImageImprovements +from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticImprovements +from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticItemUpdates +from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticShippingImprovements +from google.shopping.merchant_accounts_v1.types.automaticimprovements import GetAutomaticImprovementsRequest +from google.shopping.merchant_accounts_v1.types.automaticimprovements import UpdateAutomaticImprovementsRequest +from google.shopping.merchant_accounts_v1.types.businessidentity import BusinessIdentity +from google.shopping.merchant_accounts_v1.types.businessidentity import GetBusinessIdentityRequest +from google.shopping.merchant_accounts_v1.types.businessidentity import UpdateBusinessIdentityRequest +from google.shopping.merchant_accounts_v1.types.businessinfo import BusinessInfo +from google.shopping.merchant_accounts_v1.types.businessinfo import GetBusinessInfoRequest +from google.shopping.merchant_accounts_v1.types.businessinfo import UpdateBusinessInfoRequest +from google.shopping.merchant_accounts_v1.types.checkoutsettings import CheckoutSettings +from google.shopping.merchant_accounts_v1.types.checkoutsettings import CreateCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1.types.checkoutsettings import DeleteCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1.types.checkoutsettings import GetCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1.types.checkoutsettings import UpdateCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1.types.checkoutsettings import UriSettings +from google.shopping.merchant_accounts_v1.types.customerservice import CustomerService +from google.shopping.merchant_accounts_v1.types.developerregistration import DeveloperRegistration +from google.shopping.merchant_accounts_v1.types.developerregistration import GetDeveloperRegistrationRequest +from google.shopping.merchant_accounts_v1.types.developerregistration import RegisterGcpRequest +from google.shopping.merchant_accounts_v1.types.developerregistration import UnregisterGcpRequest +from google.shopping.merchant_accounts_v1.types.emailpreferences import EmailPreferences +from google.shopping.merchant_accounts_v1.types.emailpreferences import GetEmailPreferencesRequest +from google.shopping.merchant_accounts_v1.types.emailpreferences import UpdateEmailPreferencesRequest +from google.shopping.merchant_accounts_v1.types.gbpaccounts import GbpAccount +from google.shopping.merchant_accounts_v1.types.gbpaccounts import LinkGbpAccountRequest +from google.shopping.merchant_accounts_v1.types.gbpaccounts import LinkGbpAccountResponse +from google.shopping.merchant_accounts_v1.types.gbpaccounts import ListGbpAccountsRequest +from google.shopping.merchant_accounts_v1.types.gbpaccounts import ListGbpAccountsResponse +from google.shopping.merchant_accounts_v1.types.homepage import ClaimHomepageRequest +from google.shopping.merchant_accounts_v1.types.homepage import GetHomepageRequest +from google.shopping.merchant_accounts_v1.types.homepage import Homepage +from google.shopping.merchant_accounts_v1.types.homepage import UnclaimHomepageRequest +from google.shopping.merchant_accounts_v1.types.homepage import UpdateHomepageRequest +from google.shopping.merchant_accounts_v1.types.lfpproviders import FindLfpProvidersRequest +from google.shopping.merchant_accounts_v1.types.lfpproviders import FindLfpProvidersResponse +from google.shopping.merchant_accounts_v1.types.lfpproviders import LfpProvider +from google.shopping.merchant_accounts_v1.types.lfpproviders import LinkLfpProviderRequest +from google.shopping.merchant_accounts_v1.types.lfpproviders import LinkLfpProviderResponse +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import About +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import CreateOmnichannelSettingRequest +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import GetOmnichannelSettingRequest +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import InStock +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import InventoryVerification +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import LfpLink +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import ListOmnichannelSettingsRequest +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import ListOmnichannelSettingsResponse +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import OmnichannelSetting +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import OnDisplayToOrder +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import Pickup +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import RequestInventoryVerificationRequest +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import RequestInventoryVerificationResponse +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import ReviewState +from google.shopping.merchant_accounts_v1.types.omnichannelsettings import UpdateOmnichannelSettingRequest +from google.shopping.merchant_accounts_v1.types.online_return_policy import CreateOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1.types.online_return_policy import DeleteOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1.types.online_return_policy import GetOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1.types.online_return_policy import ListOnlineReturnPoliciesRequest +from google.shopping.merchant_accounts_v1.types.online_return_policy import ListOnlineReturnPoliciesResponse +from google.shopping.merchant_accounts_v1.types.online_return_policy import OnlineReturnPolicy +from google.shopping.merchant_accounts_v1.types.phoneverificationstate import PhoneVerificationState +from google.shopping.merchant_accounts_v1.types.programs import DisableProgramRequest +from google.shopping.merchant_accounts_v1.types.programs import EnableProgramRequest +from google.shopping.merchant_accounts_v1.types.programs import GetProgramRequest +from google.shopping.merchant_accounts_v1.types.programs import ListProgramsRequest +from google.shopping.merchant_accounts_v1.types.programs import ListProgramsResponse +from google.shopping.merchant_accounts_v1.types.programs import Program +from google.shopping.merchant_accounts_v1.types.regions import CreateRegionRequest +from google.shopping.merchant_accounts_v1.types.regions import DeleteRegionRequest +from google.shopping.merchant_accounts_v1.types.regions import GetRegionRequest +from google.shopping.merchant_accounts_v1.types.regions import ListRegionsRequest +from google.shopping.merchant_accounts_v1.types.regions import ListRegionsResponse +from google.shopping.merchant_accounts_v1.types.regions import Region +from google.shopping.merchant_accounts_v1.types.regions import UpdateRegionRequest +from google.shopping.merchant_accounts_v1.types.shippingsettings import Address +from google.shopping.merchant_accounts_v1.types.shippingsettings import BusinessDayConfig +from google.shopping.merchant_accounts_v1.types.shippingsettings import CarrierRate +from google.shopping.merchant_accounts_v1.types.shippingsettings import CutoffTime +from google.shopping.merchant_accounts_v1.types.shippingsettings import DeliveryTime +from google.shopping.merchant_accounts_v1.types.shippingsettings import Distance +from google.shopping.merchant_accounts_v1.types.shippingsettings import GetShippingSettingsRequest +from google.shopping.merchant_accounts_v1.types.shippingsettings import Headers +from google.shopping.merchant_accounts_v1.types.shippingsettings import InsertShippingSettingsRequest +from google.shopping.merchant_accounts_v1.types.shippingsettings import LocationIdSet +from google.shopping.merchant_accounts_v1.types.shippingsettings import MinimumOrderValueTable +from google.shopping.merchant_accounts_v1.types.shippingsettings import RateGroup +from google.shopping.merchant_accounts_v1.types.shippingsettings import Row +from google.shopping.merchant_accounts_v1.types.shippingsettings import Service +from google.shopping.merchant_accounts_v1.types.shippingsettings import ShippingSettings +from google.shopping.merchant_accounts_v1.types.shippingsettings import Table +from google.shopping.merchant_accounts_v1.types.shippingsettings import TransitTable +from google.shopping.merchant_accounts_v1.types.shippingsettings import Value +from google.shopping.merchant_accounts_v1.types.shippingsettings import Warehouse +from google.shopping.merchant_accounts_v1.types.shippingsettings import WarehouseBasedDeliveryTime +from google.shopping.merchant_accounts_v1.types.shippingsettings import WarehouseCutoffTime +from google.shopping.merchant_accounts_v1.types.termsofservice import AcceptTermsOfServiceRequest +from google.shopping.merchant_accounts_v1.types.termsofservice import AcceptTermsOfServiceResponse +from google.shopping.merchant_accounts_v1.types.termsofservice import GetTermsOfServiceRequest +from google.shopping.merchant_accounts_v1.types.termsofservice import RetrieveLatestTermsOfServiceRequest +from google.shopping.merchant_accounts_v1.types.termsofservice import TermsOfService +from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import Accepted +from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest +from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import Required +from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest +from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import TermsOfServiceAgreementState +from google.shopping.merchant_accounts_v1.types.termsofservicekind import TermsOfServiceKind +from google.shopping.merchant_accounts_v1.types.user import CreateUserRequest +from google.shopping.merchant_accounts_v1.types.user import DeleteUserRequest +from google.shopping.merchant_accounts_v1.types.user import GetUserRequest +from google.shopping.merchant_accounts_v1.types.user import ListUsersRequest +from google.shopping.merchant_accounts_v1.types.user import ListUsersResponse +from google.shopping.merchant_accounts_v1.types.user import UpdateUserRequest +from google.shopping.merchant_accounts_v1.types.user import User + +__all__ = ('AccountIssueServiceClient', + 'AccountIssueServiceAsyncClient', + 'AccountRelationshipsServiceClient', + 'AccountRelationshipsServiceAsyncClient', + 'AccountServicesServiceClient', + 'AccountServicesServiceAsyncClient', + 'AccountsServiceClient', + 'AccountsServiceAsyncClient', + 'AutofeedSettingsServiceClient', + 'AutofeedSettingsServiceAsyncClient', + 'AutomaticImprovementsServiceClient', + 'AutomaticImprovementsServiceAsyncClient', + 'BusinessIdentityServiceClient', + 'BusinessIdentityServiceAsyncClient', + 'BusinessInfoServiceClient', + 'BusinessInfoServiceAsyncClient', + 'CheckoutSettingsServiceClient', + 'CheckoutSettingsServiceAsyncClient', + 'DeveloperRegistrationServiceClient', + 'DeveloperRegistrationServiceAsyncClient', + 'EmailPreferencesServiceClient', + 'EmailPreferencesServiceAsyncClient', + 'GbpAccountsServiceClient', + 'GbpAccountsServiceAsyncClient', + 'HomepageServiceClient', + 'HomepageServiceAsyncClient', + 'LfpProvidersServiceClient', + 'LfpProvidersServiceAsyncClient', + 'OmnichannelSettingsServiceClient', + 'OmnichannelSettingsServiceAsyncClient', + 'OnlineReturnPolicyServiceClient', + 'OnlineReturnPolicyServiceAsyncClient', + 'ProgramsServiceClient', + 'ProgramsServiceAsyncClient', + 'RegionsServiceClient', + 'RegionsServiceAsyncClient', + 'ShippingSettingsServiceClient', + 'ShippingSettingsServiceAsyncClient', + 'TermsOfServiceAgreementStateServiceClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', + 'TermsOfServiceServiceClient', + 'TermsOfServiceServiceAsyncClient', + 'UserServiceClient', + 'UserServiceAsyncClient', + 'AccessRight', + 'AccountIssue', + 'ListAccountIssuesRequest', + 'ListAccountIssuesResponse', + 'AccountRelationship', + 'GetAccountRelationshipRequest', + 'ListAccountRelationshipsRequest', + 'ListAccountRelationshipsResponse', + 'UpdateAccountRelationshipRequest', + 'Account', + 'CreateAndConfigureAccountRequest', + 'DeleteAccountRequest', + 'GetAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListSubAccountsRequest', + 'ListSubAccountsResponse', + 'UpdateAccountRequest', + 'AccountAggregation', + 'AccountManagement', + 'AccountService', + 'ApproveAccountServiceRequest', + 'CampaignsManagement', + 'GetAccountServiceRequest', + 'Handshake', + 'ListAccountServicesRequest', + 'ListAccountServicesResponse', + 'LocalListingManagement', + 'ProductsManagement', + 'ProposeAccountServiceRequest', + 'RejectAccountServiceRequest', + 'AutofeedSettings', + 'GetAutofeedSettingsRequest', + 'UpdateAutofeedSettingsRequest', + 'AutomaticImageImprovements', + 'AutomaticImprovements', + 'AutomaticItemUpdates', + 'AutomaticShippingImprovements', + 'GetAutomaticImprovementsRequest', + 'UpdateAutomaticImprovementsRequest', + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + 'CheckoutSettings', + 'CreateCheckoutSettingsRequest', + 'DeleteCheckoutSettingsRequest', + 'GetCheckoutSettingsRequest', + 'UpdateCheckoutSettingsRequest', + 'UriSettings', + 'CustomerService', + 'DeveloperRegistration', + 'GetDeveloperRegistrationRequest', + 'RegisterGcpRequest', + 'UnregisterGcpRequest', + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + 'GbpAccount', + 'LinkGbpAccountRequest', + 'LinkGbpAccountResponse', + 'ListGbpAccountsRequest', + 'ListGbpAccountsResponse', + 'ClaimHomepageRequest', + 'GetHomepageRequest', + 'Homepage', + 'UnclaimHomepageRequest', + 'UpdateHomepageRequest', + 'FindLfpProvidersRequest', + 'FindLfpProvidersResponse', + 'LfpProvider', + 'LinkLfpProviderRequest', + 'LinkLfpProviderResponse', + 'About', + 'CreateOmnichannelSettingRequest', + 'GetOmnichannelSettingRequest', + 'InStock', + 'InventoryVerification', + 'LfpLink', + 'ListOmnichannelSettingsRequest', + 'ListOmnichannelSettingsResponse', + 'OmnichannelSetting', + 'OnDisplayToOrder', + 'Pickup', + 'RequestInventoryVerificationRequest', + 'RequestInventoryVerificationResponse', + 'ReviewState', + 'UpdateOmnichannelSettingRequest', + 'CreateOnlineReturnPolicyRequest', + 'DeleteOnlineReturnPolicyRequest', + 'GetOnlineReturnPolicyRequest', + 'ListOnlineReturnPoliciesRequest', + 'ListOnlineReturnPoliciesResponse', + 'OnlineReturnPolicy', + 'PhoneVerificationState', + 'DisableProgramRequest', + 'EnableProgramRequest', + 'GetProgramRequest', + 'ListProgramsRequest', + 'ListProgramsResponse', + 'Program', + 'CreateRegionRequest', + 'DeleteRegionRequest', + 'GetRegionRequest', + 'ListRegionsRequest', + 'ListRegionsResponse', + 'Region', + 'UpdateRegionRequest', + 'Address', + 'BusinessDayConfig', + 'CarrierRate', + 'CutoffTime', + 'DeliveryTime', + 'Distance', + 'GetShippingSettingsRequest', + 'Headers', + 'InsertShippingSettingsRequest', + 'LocationIdSet', + 'MinimumOrderValueTable', + 'RateGroup', + 'Row', + 'Service', + 'ShippingSettings', + 'Table', + 'TransitTable', + 'Value', + 'Warehouse', + 'WarehouseBasedDeliveryTime', + 'WarehouseCutoffTime', + 'AcceptTermsOfServiceRequest', + 'AcceptTermsOfServiceResponse', + 'GetTermsOfServiceRequest', + 'RetrieveLatestTermsOfServiceRequest', + 'TermsOfService', + 'Accepted', + 'GetTermsOfServiceAgreementStateRequest', + 'Required', + 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + 'TermsOfServiceAgreementState', + 'TermsOfServiceKind', + 'CreateUserRequest', + 'DeleteUserRequest', + 'GetUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + 'UpdateUserRequest', + 'User', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/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-accounts/v1/google/shopping/merchant_accounts/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/py.typed new file mode 100644 index 000000000000..19aa2588b0f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py new file mode 100644 index 000000000000..a20f2045d3f0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py @@ -0,0 +1,410 @@ +# -*- 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_accounts_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.account_issue_service import AccountIssueServiceClient +from .services.account_issue_service import AccountIssueServiceAsyncClient +from .services.account_relationships_service import AccountRelationshipsServiceClient +from .services.account_relationships_service import AccountRelationshipsServiceAsyncClient +from .services.account_services_service import AccountServicesServiceClient +from .services.account_services_service import AccountServicesServiceAsyncClient +from .services.accounts_service import AccountsServiceClient +from .services.accounts_service import AccountsServiceAsyncClient +from .services.autofeed_settings_service import AutofeedSettingsServiceClient +from .services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient +from .services.automatic_improvements_service import AutomaticImprovementsServiceClient +from .services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient +from .services.business_identity_service import BusinessIdentityServiceClient +from .services.business_identity_service import BusinessIdentityServiceAsyncClient +from .services.business_info_service import BusinessInfoServiceClient +from .services.business_info_service import BusinessInfoServiceAsyncClient +from .services.checkout_settings_service import CheckoutSettingsServiceClient +from .services.checkout_settings_service import CheckoutSettingsServiceAsyncClient +from .services.developer_registration_service import DeveloperRegistrationServiceClient +from .services.developer_registration_service import DeveloperRegistrationServiceAsyncClient +from .services.email_preferences_service import EmailPreferencesServiceClient +from .services.email_preferences_service import EmailPreferencesServiceAsyncClient +from .services.gbp_accounts_service import GbpAccountsServiceClient +from .services.gbp_accounts_service import GbpAccountsServiceAsyncClient +from .services.homepage_service import HomepageServiceClient +from .services.homepage_service import HomepageServiceAsyncClient +from .services.lfp_providers_service import LfpProvidersServiceClient +from .services.lfp_providers_service import LfpProvidersServiceAsyncClient +from .services.omnichannel_settings_service import OmnichannelSettingsServiceClient +from .services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient +from .services.online_return_policy_service import OnlineReturnPolicyServiceClient +from .services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient +from .services.programs_service import ProgramsServiceClient +from .services.programs_service import ProgramsServiceAsyncClient +from .services.regions_service import RegionsServiceClient +from .services.regions_service import RegionsServiceAsyncClient +from .services.shipping_settings_service import ShippingSettingsServiceClient +from .services.shipping_settings_service import ShippingSettingsServiceAsyncClient +from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient +from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient +from .services.terms_of_service_service import TermsOfServiceServiceClient +from .services.terms_of_service_service import TermsOfServiceServiceAsyncClient +from .services.user_service import UserServiceClient +from .services.user_service import UserServiceAsyncClient + +from .types.accessright import AccessRight +from .types.accountissue import AccountIssue +from .types.accountissue import ListAccountIssuesRequest +from .types.accountissue import ListAccountIssuesResponse +from .types.accountrelationships import AccountRelationship +from .types.accountrelationships import GetAccountRelationshipRequest +from .types.accountrelationships import ListAccountRelationshipsRequest +from .types.accountrelationships import ListAccountRelationshipsResponse +from .types.accountrelationships import UpdateAccountRelationshipRequest +from .types.accounts import Account +from .types.accounts import CreateAndConfigureAccountRequest +from .types.accounts import DeleteAccountRequest +from .types.accounts import GetAccountRequest +from .types.accounts import ListAccountsRequest +from .types.accounts import ListAccountsResponse +from .types.accounts import ListSubAccountsRequest +from .types.accounts import ListSubAccountsResponse +from .types.accounts import UpdateAccountRequest +from .types.accountservices import AccountAggregation +from .types.accountservices import AccountManagement +from .types.accountservices import AccountService +from .types.accountservices import ApproveAccountServiceRequest +from .types.accountservices import CampaignsManagement +from .types.accountservices import GetAccountServiceRequest +from .types.accountservices import Handshake +from .types.accountservices import ListAccountServicesRequest +from .types.accountservices import ListAccountServicesResponse +from .types.accountservices import LocalListingManagement +from .types.accountservices import ProductsManagement +from .types.accountservices import ProposeAccountServiceRequest +from .types.accountservices import RejectAccountServiceRequest +from .types.autofeedsettings import AutofeedSettings +from .types.autofeedsettings import GetAutofeedSettingsRequest +from .types.autofeedsettings import UpdateAutofeedSettingsRequest +from .types.automaticimprovements import AutomaticImageImprovements +from .types.automaticimprovements import AutomaticImprovements +from .types.automaticimprovements import AutomaticItemUpdates +from .types.automaticimprovements import AutomaticShippingImprovements +from .types.automaticimprovements import GetAutomaticImprovementsRequest +from .types.automaticimprovements import UpdateAutomaticImprovementsRequest +from .types.businessidentity import BusinessIdentity +from .types.businessidentity import GetBusinessIdentityRequest +from .types.businessidentity import UpdateBusinessIdentityRequest +from .types.businessinfo import BusinessInfo +from .types.businessinfo import GetBusinessInfoRequest +from .types.businessinfo import UpdateBusinessInfoRequest +from .types.checkoutsettings import CheckoutSettings +from .types.checkoutsettings import CreateCheckoutSettingsRequest +from .types.checkoutsettings import DeleteCheckoutSettingsRequest +from .types.checkoutsettings import GetCheckoutSettingsRequest +from .types.checkoutsettings import UpdateCheckoutSettingsRequest +from .types.checkoutsettings import UriSettings +from .types.customerservice import CustomerService +from .types.developerregistration import DeveloperRegistration +from .types.developerregistration import GetDeveloperRegistrationRequest +from .types.developerregistration import RegisterGcpRequest +from .types.developerregistration import UnregisterGcpRequest +from .types.emailpreferences import EmailPreferences +from .types.emailpreferences import GetEmailPreferencesRequest +from .types.emailpreferences import UpdateEmailPreferencesRequest +from .types.gbpaccounts import GbpAccount +from .types.gbpaccounts import LinkGbpAccountRequest +from .types.gbpaccounts import LinkGbpAccountResponse +from .types.gbpaccounts import ListGbpAccountsRequest +from .types.gbpaccounts import ListGbpAccountsResponse +from .types.homepage import ClaimHomepageRequest +from .types.homepage import GetHomepageRequest +from .types.homepage import Homepage +from .types.homepage import UnclaimHomepageRequest +from .types.homepage import UpdateHomepageRequest +from .types.lfpproviders import FindLfpProvidersRequest +from .types.lfpproviders import FindLfpProvidersResponse +from .types.lfpproviders import LfpProvider +from .types.lfpproviders import LinkLfpProviderRequest +from .types.lfpproviders import LinkLfpProviderResponse +from .types.omnichannelsettings import About +from .types.omnichannelsettings import CreateOmnichannelSettingRequest +from .types.omnichannelsettings import GetOmnichannelSettingRequest +from .types.omnichannelsettings import InStock +from .types.omnichannelsettings import InventoryVerification +from .types.omnichannelsettings import LfpLink +from .types.omnichannelsettings import ListOmnichannelSettingsRequest +from .types.omnichannelsettings import ListOmnichannelSettingsResponse +from .types.omnichannelsettings import OmnichannelSetting +from .types.omnichannelsettings import OnDisplayToOrder +from .types.omnichannelsettings import Pickup +from .types.omnichannelsettings import RequestInventoryVerificationRequest +from .types.omnichannelsettings import RequestInventoryVerificationResponse +from .types.omnichannelsettings import ReviewState +from .types.omnichannelsettings import UpdateOmnichannelSettingRequest +from .types.online_return_policy import CreateOnlineReturnPolicyRequest +from .types.online_return_policy import DeleteOnlineReturnPolicyRequest +from .types.online_return_policy import GetOnlineReturnPolicyRequest +from .types.online_return_policy import ListOnlineReturnPoliciesRequest +from .types.online_return_policy import ListOnlineReturnPoliciesResponse +from .types.online_return_policy import OnlineReturnPolicy +from .types.phoneverificationstate import PhoneVerificationState +from .types.programs import DisableProgramRequest +from .types.programs import EnableProgramRequest +from .types.programs import GetProgramRequest +from .types.programs import ListProgramsRequest +from .types.programs import ListProgramsResponse +from .types.programs import Program +from .types.regions import CreateRegionRequest +from .types.regions import DeleteRegionRequest +from .types.regions import GetRegionRequest +from .types.regions import ListRegionsRequest +from .types.regions import ListRegionsResponse +from .types.regions import Region +from .types.regions import UpdateRegionRequest +from .types.shippingsettings import Address +from .types.shippingsettings import BusinessDayConfig +from .types.shippingsettings import CarrierRate +from .types.shippingsettings import CutoffTime +from .types.shippingsettings import DeliveryTime +from .types.shippingsettings import Distance +from .types.shippingsettings import GetShippingSettingsRequest +from .types.shippingsettings import Headers +from .types.shippingsettings import InsertShippingSettingsRequest +from .types.shippingsettings import LocationIdSet +from .types.shippingsettings import MinimumOrderValueTable +from .types.shippingsettings import RateGroup +from .types.shippingsettings import Row +from .types.shippingsettings import Service +from .types.shippingsettings import ShippingSettings +from .types.shippingsettings import Table +from .types.shippingsettings import TransitTable +from .types.shippingsettings import Value +from .types.shippingsettings import Warehouse +from .types.shippingsettings import WarehouseBasedDeliveryTime +from .types.shippingsettings import WarehouseCutoffTime +from .types.termsofservice import AcceptTermsOfServiceRequest +from .types.termsofservice import AcceptTermsOfServiceResponse +from .types.termsofservice import GetTermsOfServiceRequest +from .types.termsofservice import RetrieveLatestTermsOfServiceRequest +from .types.termsofservice import TermsOfService +from .types.termsofserviceagreementstate import Accepted +from .types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest +from .types.termsofserviceagreementstate import Required +from .types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest +from .types.termsofserviceagreementstate import TermsOfServiceAgreementState +from .types.termsofservicekind import TermsOfServiceKind +from .types.user import CreateUserRequest +from .types.user import DeleteUserRequest +from .types.user import GetUserRequest +from .types.user import ListUsersRequest +from .types.user import ListUsersResponse +from .types.user import UpdateUserRequest +from .types.user import User + +__all__ = ( + 'AccountIssueServiceAsyncClient', + 'AccountRelationshipsServiceAsyncClient', + 'AccountServicesServiceAsyncClient', + 'AccountsServiceAsyncClient', + 'AutofeedSettingsServiceAsyncClient', + 'AutomaticImprovementsServiceAsyncClient', + 'BusinessIdentityServiceAsyncClient', + 'BusinessInfoServiceAsyncClient', + 'CheckoutSettingsServiceAsyncClient', + 'DeveloperRegistrationServiceAsyncClient', + 'EmailPreferencesServiceAsyncClient', + 'GbpAccountsServiceAsyncClient', + 'HomepageServiceAsyncClient', + 'LfpProvidersServiceAsyncClient', + 'OmnichannelSettingsServiceAsyncClient', + 'OnlineReturnPolicyServiceAsyncClient', + 'ProgramsServiceAsyncClient', + 'RegionsServiceAsyncClient', + 'ShippingSettingsServiceAsyncClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', + 'TermsOfServiceServiceAsyncClient', + 'UserServiceAsyncClient', +'About', +'AcceptTermsOfServiceRequest', +'AcceptTermsOfServiceResponse', +'Accepted', +'AccessRight', +'Account', +'AccountAggregation', +'AccountIssue', +'AccountIssueServiceClient', +'AccountManagement', +'AccountRelationship', +'AccountRelationshipsServiceClient', +'AccountService', +'AccountServicesServiceClient', +'AccountsServiceClient', +'Address', +'ApproveAccountServiceRequest', +'AutofeedSettings', +'AutofeedSettingsServiceClient', +'AutomaticImageImprovements', +'AutomaticImprovements', +'AutomaticImprovementsServiceClient', +'AutomaticItemUpdates', +'AutomaticShippingImprovements', +'BusinessDayConfig', +'BusinessIdentity', +'BusinessIdentityServiceClient', +'BusinessInfo', +'BusinessInfoServiceClient', +'CampaignsManagement', +'CarrierRate', +'CheckoutSettings', +'CheckoutSettingsServiceClient', +'ClaimHomepageRequest', +'CreateAndConfigureAccountRequest', +'CreateCheckoutSettingsRequest', +'CreateOmnichannelSettingRequest', +'CreateOnlineReturnPolicyRequest', +'CreateRegionRequest', +'CreateUserRequest', +'CustomerService', +'CutoffTime', +'DeleteAccountRequest', +'DeleteCheckoutSettingsRequest', +'DeleteOnlineReturnPolicyRequest', +'DeleteRegionRequest', +'DeleteUserRequest', +'DeliveryTime', +'DeveloperRegistration', +'DeveloperRegistrationServiceClient', +'DisableProgramRequest', +'Distance', +'EmailPreferences', +'EmailPreferencesServiceClient', +'EnableProgramRequest', +'FindLfpProvidersRequest', +'FindLfpProvidersResponse', +'GbpAccount', +'GbpAccountsServiceClient', +'GetAccountRelationshipRequest', +'GetAccountRequest', +'GetAccountServiceRequest', +'GetAutofeedSettingsRequest', +'GetAutomaticImprovementsRequest', +'GetBusinessIdentityRequest', +'GetBusinessInfoRequest', +'GetCheckoutSettingsRequest', +'GetDeveloperRegistrationRequest', +'GetEmailPreferencesRequest', +'GetHomepageRequest', +'GetOmnichannelSettingRequest', +'GetOnlineReturnPolicyRequest', +'GetProgramRequest', +'GetRegionRequest', +'GetShippingSettingsRequest', +'GetTermsOfServiceAgreementStateRequest', +'GetTermsOfServiceRequest', +'GetUserRequest', +'Handshake', +'Headers', +'Homepage', +'HomepageServiceClient', +'InStock', +'InsertShippingSettingsRequest', +'InventoryVerification', +'LfpLink', +'LfpProvider', +'LfpProvidersServiceClient', +'LinkGbpAccountRequest', +'LinkGbpAccountResponse', +'LinkLfpProviderRequest', +'LinkLfpProviderResponse', +'ListAccountIssuesRequest', +'ListAccountIssuesResponse', +'ListAccountRelationshipsRequest', +'ListAccountRelationshipsResponse', +'ListAccountServicesRequest', +'ListAccountServicesResponse', +'ListAccountsRequest', +'ListAccountsResponse', +'ListGbpAccountsRequest', +'ListGbpAccountsResponse', +'ListOmnichannelSettingsRequest', +'ListOmnichannelSettingsResponse', +'ListOnlineReturnPoliciesRequest', +'ListOnlineReturnPoliciesResponse', +'ListProgramsRequest', +'ListProgramsResponse', +'ListRegionsRequest', +'ListRegionsResponse', +'ListSubAccountsRequest', +'ListSubAccountsResponse', +'ListUsersRequest', +'ListUsersResponse', +'LocalListingManagement', +'LocationIdSet', +'MinimumOrderValueTable', +'OmnichannelSetting', +'OmnichannelSettingsServiceClient', +'OnDisplayToOrder', +'OnlineReturnPolicy', +'OnlineReturnPolicyServiceClient', +'PhoneVerificationState', +'Pickup', +'ProductsManagement', +'Program', +'ProgramsServiceClient', +'ProposeAccountServiceRequest', +'RateGroup', +'Region', +'RegionsServiceClient', +'RegisterGcpRequest', +'RejectAccountServiceRequest', +'RequestInventoryVerificationRequest', +'RequestInventoryVerificationResponse', +'Required', +'RetrieveForApplicationTermsOfServiceAgreementStateRequest', +'RetrieveLatestTermsOfServiceRequest', +'ReviewState', +'Row', +'Service', +'ShippingSettings', +'ShippingSettingsServiceClient', +'Table', +'TermsOfService', +'TermsOfServiceAgreementState', +'TermsOfServiceAgreementStateServiceClient', +'TermsOfServiceKind', +'TermsOfServiceServiceClient', +'TransitTable', +'UnclaimHomepageRequest', +'UnregisterGcpRequest', +'UpdateAccountRelationshipRequest', +'UpdateAccountRequest', +'UpdateAutofeedSettingsRequest', +'UpdateAutomaticImprovementsRequest', +'UpdateBusinessIdentityRequest', +'UpdateBusinessInfoRequest', +'UpdateCheckoutSettingsRequest', +'UpdateEmailPreferencesRequest', +'UpdateHomepageRequest', +'UpdateOmnichannelSettingRequest', +'UpdateRegionRequest', +'UpdateUserRequest', +'UriSettings', +'User', +'UserServiceClient', +'Value', +'Warehouse', +'WarehouseBasedDeliveryTime', +'WarehouseCutoffTime', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_metadata.json new file mode 100644 index 000000000000..25de395b2c93 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_metadata.json @@ -0,0 +1,1477 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_accounts_v1", + "protoPackage": "google.shopping.merchant.accounts.v1", + "schema": "1.0", + "services": { + "AccountIssueService": { + "clients": { + "grpc": { + "libraryClient": "AccountIssueServiceClient", + "rpcs": { + "ListAccountIssues": { + "methods": [ + "list_account_issues" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountIssueServiceAsyncClient", + "rpcs": { + "ListAccountIssues": { + "methods": [ + "list_account_issues" + ] + } + } + }, + "rest": { + "libraryClient": "AccountIssueServiceClient", + "rpcs": { + "ListAccountIssues": { + "methods": [ + "list_account_issues" + ] + } + } + } + } + }, + "AccountRelationshipsService": { + "clients": { + "grpc": { + "libraryClient": "AccountRelationshipsServiceClient", + "rpcs": { + "GetAccountRelationship": { + "methods": [ + "get_account_relationship" + ] + }, + "ListAccountRelationships": { + "methods": [ + "list_account_relationships" + ] + }, + "UpdateAccountRelationship": { + "methods": [ + "update_account_relationship" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountRelationshipsServiceAsyncClient", + "rpcs": { + "GetAccountRelationship": { + "methods": [ + "get_account_relationship" + ] + }, + "ListAccountRelationships": { + "methods": [ + "list_account_relationships" + ] + }, + "UpdateAccountRelationship": { + "methods": [ + "update_account_relationship" + ] + } + } + }, + "rest": { + "libraryClient": "AccountRelationshipsServiceClient", + "rpcs": { + "GetAccountRelationship": { + "methods": [ + "get_account_relationship" + ] + }, + "ListAccountRelationships": { + "methods": [ + "list_account_relationships" + ] + }, + "UpdateAccountRelationship": { + "methods": [ + "update_account_relationship" + ] + } + } + } + } + }, + "AccountServicesService": { + "clients": { + "grpc": { + "libraryClient": "AccountServicesServiceClient", + "rpcs": { + "ApproveAccountService": { + "methods": [ + "approve_account_service" + ] + }, + "GetAccountService": { + "methods": [ + "get_account_service" + ] + }, + "ListAccountServices": { + "methods": [ + "list_account_services" + ] + }, + "ProposeAccountService": { + "methods": [ + "propose_account_service" + ] + }, + "RejectAccountService": { + "methods": [ + "reject_account_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountServicesServiceAsyncClient", + "rpcs": { + "ApproveAccountService": { + "methods": [ + "approve_account_service" + ] + }, + "GetAccountService": { + "methods": [ + "get_account_service" + ] + }, + "ListAccountServices": { + "methods": [ + "list_account_services" + ] + }, + "ProposeAccountService": { + "methods": [ + "propose_account_service" + ] + }, + "RejectAccountService": { + "methods": [ + "reject_account_service" + ] + } + } + }, + "rest": { + "libraryClient": "AccountServicesServiceClient", + "rpcs": { + "ApproveAccountService": { + "methods": [ + "approve_account_service" + ] + }, + "GetAccountService": { + "methods": [ + "get_account_service" + ] + }, + "ListAccountServices": { + "methods": [ + "list_account_services" + ] + }, + "ProposeAccountService": { + "methods": [ + "propose_account_service" + ] + }, + "RejectAccountService": { + "methods": [ + "reject_account_service" + ] + } + } + } + } + }, + "AccountsService": { + "clients": { + "grpc": { + "libraryClient": "AccountsServiceClient", + "rpcs": { + "CreateAndConfigureAccount": { + "methods": [ + "create_and_configure_account" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListSubAccounts": { + "methods": [ + "list_sub_accounts" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountsServiceAsyncClient", + "rpcs": { + "CreateAndConfigureAccount": { + "methods": [ + "create_and_configure_account" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListSubAccounts": { + "methods": [ + "list_sub_accounts" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + } + } + }, + "rest": { + "libraryClient": "AccountsServiceClient", + "rpcs": { + "CreateAndConfigureAccount": { + "methods": [ + "create_and_configure_account" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListSubAccounts": { + "methods": [ + "list_sub_accounts" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + } + } + } + } + }, + "AutofeedSettingsService": { + "clients": { + "grpc": { + "libraryClient": "AutofeedSettingsServiceClient", + "rpcs": { + "GetAutofeedSettings": { + "methods": [ + "get_autofeed_settings" + ] + }, + "UpdateAutofeedSettings": { + "methods": [ + "update_autofeed_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutofeedSettingsServiceAsyncClient", + "rpcs": { + "GetAutofeedSettings": { + "methods": [ + "get_autofeed_settings" + ] + }, + "UpdateAutofeedSettings": { + "methods": [ + "update_autofeed_settings" + ] + } + } + }, + "rest": { + "libraryClient": "AutofeedSettingsServiceClient", + "rpcs": { + "GetAutofeedSettings": { + "methods": [ + "get_autofeed_settings" + ] + }, + "UpdateAutofeedSettings": { + "methods": [ + "update_autofeed_settings" + ] + } + } + } + } + }, + "AutomaticImprovementsService": { + "clients": { + "grpc": { + "libraryClient": "AutomaticImprovementsServiceClient", + "rpcs": { + "GetAutomaticImprovements": { + "methods": [ + "get_automatic_improvements" + ] + }, + "UpdateAutomaticImprovements": { + "methods": [ + "update_automatic_improvements" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutomaticImprovementsServiceAsyncClient", + "rpcs": { + "GetAutomaticImprovements": { + "methods": [ + "get_automatic_improvements" + ] + }, + "UpdateAutomaticImprovements": { + "methods": [ + "update_automatic_improvements" + ] + } + } + }, + "rest": { + "libraryClient": "AutomaticImprovementsServiceClient", + "rpcs": { + "GetAutomaticImprovements": { + "methods": [ + "get_automatic_improvements" + ] + }, + "UpdateAutomaticImprovements": { + "methods": [ + "update_automatic_improvements" + ] + } + } + } + } + }, + "BusinessIdentityService": { + "clients": { + "grpc": { + "libraryClient": "BusinessIdentityServiceClient", + "rpcs": { + "GetBusinessIdentity": { + "methods": [ + "get_business_identity" + ] + }, + "UpdateBusinessIdentity": { + "methods": [ + "update_business_identity" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BusinessIdentityServiceAsyncClient", + "rpcs": { + "GetBusinessIdentity": { + "methods": [ + "get_business_identity" + ] + }, + "UpdateBusinessIdentity": { + "methods": [ + "update_business_identity" + ] + } + } + }, + "rest": { + "libraryClient": "BusinessIdentityServiceClient", + "rpcs": { + "GetBusinessIdentity": { + "methods": [ + "get_business_identity" + ] + }, + "UpdateBusinessIdentity": { + "methods": [ + "update_business_identity" + ] + } + } + } + } + }, + "BusinessInfoService": { + "clients": { + "grpc": { + "libraryClient": "BusinessInfoServiceClient", + "rpcs": { + "GetBusinessInfo": { + "methods": [ + "get_business_info" + ] + }, + "UpdateBusinessInfo": { + "methods": [ + "update_business_info" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BusinessInfoServiceAsyncClient", + "rpcs": { + "GetBusinessInfo": { + "methods": [ + "get_business_info" + ] + }, + "UpdateBusinessInfo": { + "methods": [ + "update_business_info" + ] + } + } + }, + "rest": { + "libraryClient": "BusinessInfoServiceClient", + "rpcs": { + "GetBusinessInfo": { + "methods": [ + "get_business_info" + ] + }, + "UpdateBusinessInfo": { + "methods": [ + "update_business_info" + ] + } + } + } + } + }, + "CheckoutSettingsService": { + "clients": { + "grpc": { + "libraryClient": "CheckoutSettingsServiceClient", + "rpcs": { + "CreateCheckoutSettings": { + "methods": [ + "create_checkout_settings" + ] + }, + "DeleteCheckoutSettings": { + "methods": [ + "delete_checkout_settings" + ] + }, + "GetCheckoutSettings": { + "methods": [ + "get_checkout_settings" + ] + }, + "UpdateCheckoutSettings": { + "methods": [ + "update_checkout_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CheckoutSettingsServiceAsyncClient", + "rpcs": { + "CreateCheckoutSettings": { + "methods": [ + "create_checkout_settings" + ] + }, + "DeleteCheckoutSettings": { + "methods": [ + "delete_checkout_settings" + ] + }, + "GetCheckoutSettings": { + "methods": [ + "get_checkout_settings" + ] + }, + "UpdateCheckoutSettings": { + "methods": [ + "update_checkout_settings" + ] + } + } + }, + "rest": { + "libraryClient": "CheckoutSettingsServiceClient", + "rpcs": { + "CreateCheckoutSettings": { + "methods": [ + "create_checkout_settings" + ] + }, + "DeleteCheckoutSettings": { + "methods": [ + "delete_checkout_settings" + ] + }, + "GetCheckoutSettings": { + "methods": [ + "get_checkout_settings" + ] + }, + "UpdateCheckoutSettings": { + "methods": [ + "update_checkout_settings" + ] + } + } + } + } + }, + "DeveloperRegistrationService": { + "clients": { + "grpc": { + "libraryClient": "DeveloperRegistrationServiceClient", + "rpcs": { + "GetDeveloperRegistration": { + "methods": [ + "get_developer_registration" + ] + }, + "RegisterGcp": { + "methods": [ + "register_gcp" + ] + }, + "UnregisterGcp": { + "methods": [ + "unregister_gcp" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DeveloperRegistrationServiceAsyncClient", + "rpcs": { + "GetDeveloperRegistration": { + "methods": [ + "get_developer_registration" + ] + }, + "RegisterGcp": { + "methods": [ + "register_gcp" + ] + }, + "UnregisterGcp": { + "methods": [ + "unregister_gcp" + ] + } + } + }, + "rest": { + "libraryClient": "DeveloperRegistrationServiceClient", + "rpcs": { + "GetDeveloperRegistration": { + "methods": [ + "get_developer_registration" + ] + }, + "RegisterGcp": { + "methods": [ + "register_gcp" + ] + }, + "UnregisterGcp": { + "methods": [ + "unregister_gcp" + ] + } + } + } + } + }, + "EmailPreferencesService": { + "clients": { + "grpc": { + "libraryClient": "EmailPreferencesServiceClient", + "rpcs": { + "GetEmailPreferences": { + "methods": [ + "get_email_preferences" + ] + }, + "UpdateEmailPreferences": { + "methods": [ + "update_email_preferences" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EmailPreferencesServiceAsyncClient", + "rpcs": { + "GetEmailPreferences": { + "methods": [ + "get_email_preferences" + ] + }, + "UpdateEmailPreferences": { + "methods": [ + "update_email_preferences" + ] + } + } + }, + "rest": { + "libraryClient": "EmailPreferencesServiceClient", + "rpcs": { + "GetEmailPreferences": { + "methods": [ + "get_email_preferences" + ] + }, + "UpdateEmailPreferences": { + "methods": [ + "update_email_preferences" + ] + } + } + } + } + }, + "GbpAccountsService": { + "clients": { + "grpc": { + "libraryClient": "GbpAccountsServiceClient", + "rpcs": { + "LinkGbpAccount": { + "methods": [ + "link_gbp_account" + ] + }, + "ListGbpAccounts": { + "methods": [ + "list_gbp_accounts" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GbpAccountsServiceAsyncClient", + "rpcs": { + "LinkGbpAccount": { + "methods": [ + "link_gbp_account" + ] + }, + "ListGbpAccounts": { + "methods": [ + "list_gbp_accounts" + ] + } + } + }, + "rest": { + "libraryClient": "GbpAccountsServiceClient", + "rpcs": { + "LinkGbpAccount": { + "methods": [ + "link_gbp_account" + ] + }, + "ListGbpAccounts": { + "methods": [ + "list_gbp_accounts" + ] + } + } + } + } + }, + "HomepageService": { + "clients": { + "grpc": { + "libraryClient": "HomepageServiceClient", + "rpcs": { + "ClaimHomepage": { + "methods": [ + "claim_homepage" + ] + }, + "GetHomepage": { + "methods": [ + "get_homepage" + ] + }, + "UnclaimHomepage": { + "methods": [ + "unclaim_homepage" + ] + }, + "UpdateHomepage": { + "methods": [ + "update_homepage" + ] + } + } + }, + "grpc-async": { + "libraryClient": "HomepageServiceAsyncClient", + "rpcs": { + "ClaimHomepage": { + "methods": [ + "claim_homepage" + ] + }, + "GetHomepage": { + "methods": [ + "get_homepage" + ] + }, + "UnclaimHomepage": { + "methods": [ + "unclaim_homepage" + ] + }, + "UpdateHomepage": { + "methods": [ + "update_homepage" + ] + } + } + }, + "rest": { + "libraryClient": "HomepageServiceClient", + "rpcs": { + "ClaimHomepage": { + "methods": [ + "claim_homepage" + ] + }, + "GetHomepage": { + "methods": [ + "get_homepage" + ] + }, + "UnclaimHomepage": { + "methods": [ + "unclaim_homepage" + ] + }, + "UpdateHomepage": { + "methods": [ + "update_homepage" + ] + } + } + } + } + }, + "LfpProvidersService": { + "clients": { + "grpc": { + "libraryClient": "LfpProvidersServiceClient", + "rpcs": { + "FindLfpProviders": { + "methods": [ + "find_lfp_providers" + ] + }, + "LinkLfpProvider": { + "methods": [ + "link_lfp_provider" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LfpProvidersServiceAsyncClient", + "rpcs": { + "FindLfpProviders": { + "methods": [ + "find_lfp_providers" + ] + }, + "LinkLfpProvider": { + "methods": [ + "link_lfp_provider" + ] + } + } + }, + "rest": { + "libraryClient": "LfpProvidersServiceClient", + "rpcs": { + "FindLfpProviders": { + "methods": [ + "find_lfp_providers" + ] + }, + "LinkLfpProvider": { + "methods": [ + "link_lfp_provider" + ] + } + } + } + } + }, + "OmnichannelSettingsService": { + "clients": { + "grpc": { + "libraryClient": "OmnichannelSettingsServiceClient", + "rpcs": { + "CreateOmnichannelSetting": { + "methods": [ + "create_omnichannel_setting" + ] + }, + "GetOmnichannelSetting": { + "methods": [ + "get_omnichannel_setting" + ] + }, + "ListOmnichannelSettings": { + "methods": [ + "list_omnichannel_settings" + ] + }, + "RequestInventoryVerification": { + "methods": [ + "request_inventory_verification" + ] + }, + "UpdateOmnichannelSetting": { + "methods": [ + "update_omnichannel_setting" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OmnichannelSettingsServiceAsyncClient", + "rpcs": { + "CreateOmnichannelSetting": { + "methods": [ + "create_omnichannel_setting" + ] + }, + "GetOmnichannelSetting": { + "methods": [ + "get_omnichannel_setting" + ] + }, + "ListOmnichannelSettings": { + "methods": [ + "list_omnichannel_settings" + ] + }, + "RequestInventoryVerification": { + "methods": [ + "request_inventory_verification" + ] + }, + "UpdateOmnichannelSetting": { + "methods": [ + "update_omnichannel_setting" + ] + } + } + }, + "rest": { + "libraryClient": "OmnichannelSettingsServiceClient", + "rpcs": { + "CreateOmnichannelSetting": { + "methods": [ + "create_omnichannel_setting" + ] + }, + "GetOmnichannelSetting": { + "methods": [ + "get_omnichannel_setting" + ] + }, + "ListOmnichannelSettings": { + "methods": [ + "list_omnichannel_settings" + ] + }, + "RequestInventoryVerification": { + "methods": [ + "request_inventory_verification" + ] + }, + "UpdateOmnichannelSetting": { + "methods": [ + "update_omnichannel_setting" + ] + } + } + } + } + }, + "OnlineReturnPolicyService": { + "clients": { + "grpc": { + "libraryClient": "OnlineReturnPolicyServiceClient", + "rpcs": { + "CreateOnlineReturnPolicy": { + "methods": [ + "create_online_return_policy" + ] + }, + "DeleteOnlineReturnPolicy": { + "methods": [ + "delete_online_return_policy" + ] + }, + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OnlineReturnPolicyServiceAsyncClient", + "rpcs": { + "CreateOnlineReturnPolicy": { + "methods": [ + "create_online_return_policy" + ] + }, + "DeleteOnlineReturnPolicy": { + "methods": [ + "delete_online_return_policy" + ] + }, + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + } + } + }, + "rest": { + "libraryClient": "OnlineReturnPolicyServiceClient", + "rpcs": { + "CreateOnlineReturnPolicy": { + "methods": [ + "create_online_return_policy" + ] + }, + "DeleteOnlineReturnPolicy": { + "methods": [ + "delete_online_return_policy" + ] + }, + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + } + } + } + } + }, + "ProgramsService": { + "clients": { + "grpc": { + "libraryClient": "ProgramsServiceClient", + "rpcs": { + "DisableProgram": { + "methods": [ + "disable_program" + ] + }, + "EnableProgram": { + "methods": [ + "enable_program" + ] + }, + "GetProgram": { + "methods": [ + "get_program" + ] + }, + "ListPrograms": { + "methods": [ + "list_programs" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProgramsServiceAsyncClient", + "rpcs": { + "DisableProgram": { + "methods": [ + "disable_program" + ] + }, + "EnableProgram": { + "methods": [ + "enable_program" + ] + }, + "GetProgram": { + "methods": [ + "get_program" + ] + }, + "ListPrograms": { + "methods": [ + "list_programs" + ] + } + } + }, + "rest": { + "libraryClient": "ProgramsServiceClient", + "rpcs": { + "DisableProgram": { + "methods": [ + "disable_program" + ] + }, + "EnableProgram": { + "methods": [ + "enable_program" + ] + }, + "GetProgram": { + "methods": [ + "get_program" + ] + }, + "ListPrograms": { + "methods": [ + "list_programs" + ] + } + } + } + } + }, + "RegionsService": { + "clients": { + "grpc": { + "libraryClient": "RegionsServiceClient", + "rpcs": { + "CreateRegion": { + "methods": [ + "create_region" + ] + }, + "DeleteRegion": { + "methods": [ + "delete_region" + ] + }, + "GetRegion": { + "methods": [ + "get_region" + ] + }, + "ListRegions": { + "methods": [ + "list_regions" + ] + }, + "UpdateRegion": { + "methods": [ + "update_region" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegionsServiceAsyncClient", + "rpcs": { + "CreateRegion": { + "methods": [ + "create_region" + ] + }, + "DeleteRegion": { + "methods": [ + "delete_region" + ] + }, + "GetRegion": { + "methods": [ + "get_region" + ] + }, + "ListRegions": { + "methods": [ + "list_regions" + ] + }, + "UpdateRegion": { + "methods": [ + "update_region" + ] + } + } + }, + "rest": { + "libraryClient": "RegionsServiceClient", + "rpcs": { + "CreateRegion": { + "methods": [ + "create_region" + ] + }, + "DeleteRegion": { + "methods": [ + "delete_region" + ] + }, + "GetRegion": { + "methods": [ + "get_region" + ] + }, + "ListRegions": { + "methods": [ + "list_regions" + ] + }, + "UpdateRegion": { + "methods": [ + "update_region" + ] + } + } + } + } + }, + "ShippingSettingsService": { + "clients": { + "grpc": { + "libraryClient": "ShippingSettingsServiceClient", + "rpcs": { + "GetShippingSettings": { + "methods": [ + "get_shipping_settings" + ] + }, + "InsertShippingSettings": { + "methods": [ + "insert_shipping_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ShippingSettingsServiceAsyncClient", + "rpcs": { + "GetShippingSettings": { + "methods": [ + "get_shipping_settings" + ] + }, + "InsertShippingSettings": { + "methods": [ + "insert_shipping_settings" + ] + } + } + }, + "rest": { + "libraryClient": "ShippingSettingsServiceClient", + "rpcs": { + "GetShippingSettings": { + "methods": [ + "get_shipping_settings" + ] + }, + "InsertShippingSettings": { + "methods": [ + "insert_shipping_settings" + ] + } + } + } + } + }, + "TermsOfServiceAgreementStateService": { + "clients": { + "grpc": { + "libraryClient": "TermsOfServiceAgreementStateServiceClient", + "rpcs": { + "GetTermsOfServiceAgreementState": { + "methods": [ + "get_terms_of_service_agreement_state" + ] + }, + "RetrieveForApplicationTermsOfServiceAgreementState": { + "methods": [ + "retrieve_for_application_terms_of_service_agreement_state" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TermsOfServiceAgreementStateServiceAsyncClient", + "rpcs": { + "GetTermsOfServiceAgreementState": { + "methods": [ + "get_terms_of_service_agreement_state" + ] + }, + "RetrieveForApplicationTermsOfServiceAgreementState": { + "methods": [ + "retrieve_for_application_terms_of_service_agreement_state" + ] + } + } + }, + "rest": { + "libraryClient": "TermsOfServiceAgreementStateServiceClient", + "rpcs": { + "GetTermsOfServiceAgreementState": { + "methods": [ + "get_terms_of_service_agreement_state" + ] + }, + "RetrieveForApplicationTermsOfServiceAgreementState": { + "methods": [ + "retrieve_for_application_terms_of_service_agreement_state" + ] + } + } + } + } + }, + "TermsOfServiceService": { + "clients": { + "grpc": { + "libraryClient": "TermsOfServiceServiceClient", + "rpcs": { + "AcceptTermsOfService": { + "methods": [ + "accept_terms_of_service" + ] + }, + "GetTermsOfService": { + "methods": [ + "get_terms_of_service" + ] + }, + "RetrieveLatestTermsOfService": { + "methods": [ + "retrieve_latest_terms_of_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TermsOfServiceServiceAsyncClient", + "rpcs": { + "AcceptTermsOfService": { + "methods": [ + "accept_terms_of_service" + ] + }, + "GetTermsOfService": { + "methods": [ + "get_terms_of_service" + ] + }, + "RetrieveLatestTermsOfService": { + "methods": [ + "retrieve_latest_terms_of_service" + ] + } + } + }, + "rest": { + "libraryClient": "TermsOfServiceServiceClient", + "rpcs": { + "AcceptTermsOfService": { + "methods": [ + "accept_terms_of_service" + ] + }, + "GetTermsOfService": { + "methods": [ + "get_terms_of_service" + ] + }, + "RetrieveLatestTermsOfService": { + "methods": [ + "retrieve_latest_terms_of_service" + ] + } + } + } + } + }, + "UserService": { + "clients": { + "grpc": { + "libraryClient": "UserServiceClient", + "rpcs": { + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserServiceAsyncClient", + "rpcs": { + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "rest": { + "libraryClient": "UserServiceClient", + "rpcs": { + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_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-accounts/v1/google/shopping/merchant_accounts_v1/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/py.typed new file mode 100644 index 000000000000..19aa2588b0f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py new file mode 100644 index 000000000000..1c1c6dd19914 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_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 AccountIssueServiceClient +from .async_client import AccountIssueServiceAsyncClient + +__all__ = ( + 'AccountIssueServiceClient', + 'AccountIssueServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py new file mode 100644 index 000000000000..68442169c311 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py @@ -0,0 +1,392 @@ +# -*- 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_accounts_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_accounts_v1.services.account_issue_service import pagers +from google.shopping.merchant_accounts_v1.types import accountissue +from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport +from .client import AccountIssueServiceClient + +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 AccountIssueServiceAsyncClient: + """Service to support ``AccountIssueService`` API.""" + + _client: AccountIssueServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountIssueServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountIssueServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AccountIssueServiceClient.account_path) + parse_account_path = staticmethod(AccountIssueServiceClient.parse_account_path) + account_issue_path = staticmethod(AccountIssueServiceClient.account_issue_path) + parse_account_issue_path = staticmethod(AccountIssueServiceClient.parse_account_issue_path) + common_billing_account_path = staticmethod(AccountIssueServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountIssueServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountIssueServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountIssueServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountIssueServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountIssueServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountIssueServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountIssueServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountIssueServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountIssueServiceClient.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: + AccountIssueServiceAsyncClient: The constructed client. + """ + return AccountIssueServiceClient.from_service_account_info.__func__(AccountIssueServiceAsyncClient, 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: + AccountIssueServiceAsyncClient: The constructed client. + """ + return AccountIssueServiceClient.from_service_account_file.__func__(AccountIssueServiceAsyncClient, 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 AccountIssueServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountIssueServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountIssueServiceTransport: 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 = AccountIssueServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account issue 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,AccountIssueServiceTransport,Callable[..., AccountIssueServiceTransport]]]): + 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 AccountIssueServiceTransport 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 = AccountIssueServiceClient( + 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.accounts_v1.AccountIssueServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", + "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.accounts.v1.AccountIssueService", + "credentialsType": None, + } + ) + + async def list_account_issues(self, + request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesAsyncPager: + r"""Lists all account issues of a Merchant Center account. + + When called on a multi-client account, this method only returns + issues belonging to that account, not its sub-accounts. To + retrieve issues for sub-accounts, you must first call the + [accounts.listSubaccounts][google.shopping.merchant.accounts.v1.AccountsService.ListSubAccounts] + method to obtain a list of sub-accounts, and then call + ``accounts.issues.list`` for each sub-account individually. + + .. 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_accounts_v1 + + async def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1.AccountIssueServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListAccountIssuesRequest, dict]]): + The request object. Request message for the ``ListAccountIssues`` method. + parent (:class:`str`): + Required. The parent, which owns this collection of + issues. Format: ``accounts/{account}`` + + 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_accounts_v1.services.account_issue_service.pagers.ListAccountIssuesAsyncPager: + Response message for the ListAccountIssues 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, accountissue.ListAccountIssuesRequest): + request = accountissue.ListAccountIssuesRequest(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_account_issues] + + # 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.ListAccountIssuesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AccountIssueServiceAsyncClient": + 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__ = ( + "AccountIssueServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py new file mode 100644 index 000000000000..978fe2a0c0cc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py @@ -0,0 +1,761 @@ +# -*- 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_accounts_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_accounts_v1.services.account_issue_service import pagers +from google.shopping.merchant_accounts_v1.types import accountissue +from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountIssueServiceGrpcTransport +from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport +from .transports.rest import AccountIssueServiceRestTransport + + +class AccountIssueServiceClientMeta(type): + """Metaclass for the AccountIssueService 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[AccountIssueServiceTransport]] + _transport_registry["grpc"] = AccountIssueServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountIssueServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountIssueServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountIssueServiceTransport]: + """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 AccountIssueServiceClient(metaclass=AccountIssueServiceClientMeta): + """Service to support ``AccountIssueService`` API.""" + + @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: + AccountIssueServiceClient: 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: + AccountIssueServiceClient: 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) -> AccountIssueServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountIssueServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_issue_path(account: str,issue: str,) -> str: + """Returns a fully-qualified account_issue string.""" + return "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) + + @staticmethod + def parse_account_issue_path(path: str) -> Dict[str,str]: + """Parses a account_issue path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/issues/(?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 = AccountIssueServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountIssueServiceClient._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 = AccountIssueServiceClient._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, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account issue 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,AccountIssueServiceTransport,Callable[..., AccountIssueServiceTransport]]]): + 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 AccountIssueServiceTransport 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 = AccountIssueServiceClient._read_environment_variables() + self._client_cert_source = AccountIssueServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountIssueServiceClient._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, AccountIssueServiceTransport) + if transport_provided: + # transport is a AccountIssueServiceTransport 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(AccountIssueServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountIssueServiceClient._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[AccountIssueServiceTransport], Callable[..., AccountIssueServiceTransport]] = ( + AccountIssueServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountIssueServiceTransport], 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.accounts_v1.AccountIssueServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", + "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.accounts.v1.AccountIssueService", + "credentialsType": None, + } + ) + + def list_account_issues(self, + request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesPager: + r"""Lists all account issues of a Merchant Center account. + + When called on a multi-client account, this method only returns + issues belonging to that account, not its sub-accounts. To + retrieve issues for sub-accounts, you must first call the + [accounts.listSubaccounts][google.shopping.merchant.accounts.v1.AccountsService.ListSubAccounts] + method to obtain a list of sub-accounts, and then call + ``accounts.issues.list`` for each sub-account individually. + + .. 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_accounts_v1 + + def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1.AccountIssueServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListAccountIssuesRequest, dict]): + The request object. Request message for the ``ListAccountIssues`` method. + parent (str): + Required. The parent, which owns this collection of + issues. Format: ``accounts/{account}`` + + 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_accounts_v1.services.account_issue_service.pagers.ListAccountIssuesPager: + Response message for the ListAccountIssues 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, accountissue.ListAccountIssuesRequest): + request = accountissue.ListAccountIssuesRequest(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_account_issues] + + # 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.ListAccountIssuesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AccountIssueServiceClient": + 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__ = ( + "AccountIssueServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py new file mode 100644 index 000000000000..30d1a072306a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_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_accounts_v1.types import accountissue + + +class ListAccountIssuesPager: + """A pager for iterating through ``list_account_issues`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountIssuesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_issues`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountIssues`` requests and continue to iterate + through the ``account_issues`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountIssuesResponse` + 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[..., accountissue.ListAccountIssuesResponse], + request: accountissue.ListAccountIssuesRequest, + response: accountissue.ListAccountIssuesResponse, + *, + 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_accounts_v1.types.ListAccountIssuesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountIssuesResponse): + 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 = accountissue.ListAccountIssuesRequest(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[accountissue.ListAccountIssuesResponse]: + 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[accountissue.AccountIssue]: + for page in self.pages: + yield from page.account_issues + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountIssuesAsyncPager: + """A pager for iterating through ``list_account_issues`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountIssuesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_issues`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountIssues`` requests and continue to iterate + through the ``account_issues`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountIssuesResponse` + 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[accountissue.ListAccountIssuesResponse]], + request: accountissue.ListAccountIssuesRequest, + response: accountissue.ListAccountIssuesResponse, + *, + 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_accounts_v1.types.ListAccountIssuesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountIssuesResponse): + 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 = accountissue.ListAccountIssuesRequest(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[accountissue.ListAccountIssuesResponse]: + 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[accountissue.AccountIssue]: + async def async_generator(): + async for page in self.pages: + for response in page.account_issues: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst new file mode 100644 index 000000000000..c03ba991127e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountIssueServiceTransport` is the ABC for all transports. +- public child `AccountIssueServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountIssueServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountIssueServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountIssueServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py new file mode 100644 index 000000000000..7a24cf1c8dd1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_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 AccountIssueServiceTransport +from .grpc import AccountIssueServiceGrpcTransport +from .grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport +from .rest import AccountIssueServiceRestTransport +from .rest import AccountIssueServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountIssueServiceTransport]] +_transport_registry['grpc'] = AccountIssueServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountIssueServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountIssueServiceRestTransport + +__all__ = ( + 'AccountIssueServiceTransport', + 'AccountIssueServiceGrpcTransport', + 'AccountIssueServiceGrpcAsyncIOTransport', + 'AccountIssueServiceRestTransport', + 'AccountIssueServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py new file mode 100644 index 000000000000..c113b8e7fc4e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py @@ -0,0 +1,159 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import accountissue + +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 AccountIssueServiceTransport(abc.ABC): + """Abstract transport class for AccountIssueService.""" + + 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_account_issues: gapic_v1.method.wrap_method( + self.list_account_issues, + 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_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + Union[ + accountissue.ListAccountIssuesResponse, + Awaitable[accountissue.ListAccountIssuesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountIssueServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py new file mode 100644 index 000000000000..e5c456fba4d1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py @@ -0,0 +1,353 @@ +# -*- 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.shopping.merchant_accounts_v1.types import accountissue +from .base import AccountIssueServiceTransport, 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.accounts.v1.AccountIssueService", + "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.accounts.v1.AccountIssueService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountIssueServiceGrpcTransport(AccountIssueServiceTransport): + """gRPC backend transport for AccountIssueService. + + Service to support ``AccountIssueService`` API. + + 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_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + accountissue.ListAccountIssuesResponse]: + r"""Return a callable for the list account issues method over gRPC. + + Lists all account issues of a Merchant Center account. + + When called on a multi-client account, this method only returns + issues belonging to that account, not its sub-accounts. To + retrieve issues for sub-accounts, you must first call the + [accounts.listSubaccounts][google.shopping.merchant.accounts.v1.AccountsService.ListSubAccounts] + method to obtain a list of sub-accounts, and then call + ``accounts.issues.list`` for each sub-account individually. + + Returns: + Callable[[~.ListAccountIssuesRequest], + ~.ListAccountIssuesResponse]: + 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_account_issues' not in self._stubs: + self._stubs['list_account_issues'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountIssueService/ListAccountIssues', + request_serializer=accountissue.ListAccountIssuesRequest.serialize, + response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, + ) + return self._stubs['list_account_issues'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountIssueServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..482fc58b21a1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py @@ -0,0 +1,374 @@ +# -*- 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.shopping.merchant_accounts_v1.types import accountissue +from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountIssueServiceGrpcTransport + +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.accounts.v1.AccountIssueService", + "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.accounts.v1.AccountIssueService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountIssueServiceGrpcAsyncIOTransport(AccountIssueServiceTransport): + """gRPC AsyncIO backend transport for AccountIssueService. + + Service to support ``AccountIssueService`` API. + + 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_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + Awaitable[accountissue.ListAccountIssuesResponse]]: + r"""Return a callable for the list account issues method over gRPC. + + Lists all account issues of a Merchant Center account. + + When called on a multi-client account, this method only returns + issues belonging to that account, not its sub-accounts. To + retrieve issues for sub-accounts, you must first call the + [accounts.listSubaccounts][google.shopping.merchant.accounts.v1.AccountsService.ListSubAccounts] + method to obtain a list of sub-accounts, and then call + ``accounts.issues.list`` for each sub-account individually. + + Returns: + Callable[[~.ListAccountIssuesRequest], + Awaitable[~.ListAccountIssuesResponse]]: + 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_account_issues' not in self._stubs: + self._stubs['list_account_issues'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountIssueService/ListAccountIssues', + request_serializer=accountissue.ListAccountIssuesRequest.serialize, + response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, + ) + return self._stubs['list_account_issues'] + + 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_account_issues: self._wrap_method( + self.list_account_issues, + 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__ = ( + 'AccountIssueServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py new file mode 100644 index 000000000000..5a9fbfaf4a7b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py @@ -0,0 +1,351 @@ +# -*- 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.shopping.merchant_accounts_v1.types import accountissue + + +from .rest_base import _BaseAccountIssueServiceRestTransport +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 AccountIssueServiceRestInterceptor: + """Interceptor for AccountIssueService. + + 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 AccountIssueServiceRestTransport. + + .. code-block:: python + class MyCustomAccountIssueServiceInterceptor(AccountIssueServiceRestInterceptor): + def pre_list_account_issues(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_issues(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AccountIssueServiceRestTransport(interceptor=MyCustomAccountIssueServiceInterceptor()) + client = AccountIssueServiceClient(transport=transport) + + + """ + def pre_list_account_issues(self, request: accountissue.ListAccountIssuesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_account_issues + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountIssueService server. + """ + return request, metadata + + def post_list_account_issues(self, response: accountissue.ListAccountIssuesResponse) -> accountissue.ListAccountIssuesResponse: + """Post-rpc interceptor for list_account_issues + + DEPRECATED. Please use the `post_list_account_issues_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountIssueService server but before + it is returned to user code. This `post_list_account_issues` interceptor runs + before the `post_list_account_issues_with_metadata` interceptor. + """ + return response + + def post_list_account_issues_with_metadata(self, response: accountissue.ListAccountIssuesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_account_issues + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountIssueService server but before it is returned to user code. + + We recommend only using this `post_list_account_issues_with_metadata` + interceptor in new development instead of the `post_list_account_issues` interceptor. + When both interceptors are used, this `post_list_account_issues_with_metadata` interceptor runs after the + `post_list_account_issues` interceptor. The (possibly modified) response returned by + `post_list_account_issues` will be passed to + `post_list_account_issues_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AccountIssueServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountIssueServiceRestInterceptor + + +class AccountIssueServiceRestTransport(_BaseAccountIssueServiceRestTransport): + """REST backend synchronous transport for AccountIssueService. + + Service to support ``AccountIssueService`` API. + + 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[AccountIssueServiceRestInterceptor] = 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 AccountIssueServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListAccountIssues(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues, AccountIssueServiceRestStub): + def __hash__(self): + return hash("AccountIssueServiceRestTransport.ListAccountIssues") + + @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: accountissue.ListAccountIssuesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountissue.ListAccountIssuesResponse: + r"""Call the list account issues method over HTTP. + + Args: + request (~.accountissue.ListAccountIssuesRequest): + The request object. Request message for the ``ListAccountIssues`` 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: + ~.accountissue.ListAccountIssuesResponse: + Response message for the ``ListAccountIssues`` method. + """ + + http_options = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_http_options() + + request, metadata = self._interceptor.pre_list_account_issues(request, metadata) + transcoded_request = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountIssueServiceClient.ListAccountIssues", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", + "rpcName": "ListAccountIssues", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountIssueServiceRestTransport._ListAccountIssues._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 = accountissue.ListAccountIssuesResponse() + pb_resp = accountissue.ListAccountIssuesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_account_issues(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_account_issues_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountissue.ListAccountIssuesResponse.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.accounts_v1.AccountIssueServiceClient.list_account_issues", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", + "rpcName": "ListAccountIssues", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def list_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + accountissue.ListAccountIssuesResponse]: + # 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._ListAccountIssues(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountIssueServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py new file mode 100644 index 000000000000..e5a8f8cbb4b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py @@ -0,0 +1,128 @@ +# -*- 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 AccountIssueServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import accountissue + + +class _BaseAccountIssueServiceRestTransport(AccountIssueServiceTransport): + """Base REST backend transport for AccountIssueService. + + 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 _BaseListAccountIssues: + 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': '/accounts/v1/{parent=accounts/*}/issues', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountissue.ListAccountIssuesRequest.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(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountIssueServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py new file mode 100644 index 000000000000..fc0969e77119 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_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 AccountRelationshipsServiceClient +from .async_client import AccountRelationshipsServiceAsyncClient + +__all__ = ( + 'AccountRelationshipsServiceClient', + 'AccountRelationshipsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py new file mode 100644 index 000000000000..6c7fd12e68b3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py @@ -0,0 +1,638 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.account_relationships_service import pagers +from google.shopping.merchant_accounts_v1.types import accountrelationships +from .transports.base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport +from .client import AccountRelationshipsServiceClient + +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 AccountRelationshipsServiceAsyncClient: + """Service to support AccountRelationship API.""" + + _client: AccountRelationshipsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountRelationshipsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AccountRelationshipsServiceClient.account_path) + parse_account_path = staticmethod(AccountRelationshipsServiceClient.parse_account_path) + account_relationship_path = staticmethod(AccountRelationshipsServiceClient.account_relationship_path) + parse_account_relationship_path = staticmethod(AccountRelationshipsServiceClient.parse_account_relationship_path) + common_billing_account_path = staticmethod(AccountRelationshipsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountRelationshipsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountRelationshipsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountRelationshipsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountRelationshipsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountRelationshipsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountRelationshipsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountRelationshipsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountRelationshipsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountRelationshipsServiceClient.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: + AccountRelationshipsServiceAsyncClient: The constructed client. + """ + return AccountRelationshipsServiceClient.from_service_account_info.__func__(AccountRelationshipsServiceAsyncClient, 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: + AccountRelationshipsServiceAsyncClient: The constructed client. + """ + return AccountRelationshipsServiceClient.from_service_account_file.__func__(AccountRelationshipsServiceAsyncClient, 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 AccountRelationshipsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountRelationshipsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountRelationshipsServiceTransport: 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 = AccountRelationshipsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountRelationshipsServiceTransport, Callable[..., AccountRelationshipsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account relationships 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,AccountRelationshipsServiceTransport,Callable[..., AccountRelationshipsServiceTransport]]]): + 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 AccountRelationshipsServiceTransport 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 = AccountRelationshipsServiceClient( + 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.accounts_v1.AccountRelationshipsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "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.accounts.v1.AccountRelationshipsService", + "credentialsType": None, + } + ) + + async def get_account_relationship(self, + request: Optional[Union[accountrelationships.GetAccountRelationshipRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: + r"""Retrieve an account relationship. + + .. 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_accounts_v1 + + async def sample_get_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRelationshipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account_relationship(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetAccountRelationshipRequest, dict]]): + The request object. Request to get an account + relationship. + name (:class:`str`): + Required. The resource name of the account relationship + to get. Format: + ``accounts/{account}/relationships/{relationship}``. For + example, ``accounts/123456/relationships/567890``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AccountRelationship: + The AccountRelationship message defines a formal connection between a + merchant's account and a service provider's account. + This relationship enables the provider to offer + specific services to the business, such as product + management or campaign management. It specifies the + access rights and permissions to the business's data + relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). + + """ + # 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, accountrelationships.GetAccountRelationshipRequest): + request = accountrelationships.GetAccountRelationshipRequest(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.get_account_relationship] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_account_relationship(self, + request: Optional[Union[accountrelationships.UpdateAccountRelationshipRequest, dict]] = None, + *, + account_relationship: Optional[accountrelationships.AccountRelationship] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: + r"""Updates the account relationship. Executing this + method requires admin access. + + .. 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_accounts_v1 + + async def sample_update_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAccountRelationshipRequest( + ) + + # Make the request + response = await client.update_account_relationship(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateAccountRelationshipRequest, dict]]): + The request object. Request message for the ``UpdateAccountRelationship`` + method. + account_relationship (:class:`google.shopping.merchant_accounts_v1.types.AccountRelationship`): + Required. The new version of the + account relationship. + + This corresponds to the ``account_relationship`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``account_id_alias`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.AccountRelationship: + The AccountRelationship message defines a formal connection between a + merchant's account and a service provider's account. + This relationship enables the provider to offer + specific services to the business, such as product + management or campaign management. It specifies the + access rights and permissions to the business's data + relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). + + """ + # 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 = [account_relationship, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accountrelationships.UpdateAccountRelationshipRequest): + request = accountrelationships.UpdateAccountRelationshipRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account_relationship is not None: + request.account_relationship = account_relationship + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_account_relationship] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account_relationship.name", request.account_relationship.name), + )), + ) + + # 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 list_account_relationships(self, + request: Optional[Union[accountrelationships.ListAccountRelationshipsRequest, 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.ListAccountRelationshipsAsyncPager: + r"""List account relationships for the specified 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_accounts_v1 + + async def sample_list_account_relationships(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountRelationshipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_relationships(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsRequest, dict]]): + The request object. Request to list account + relationships. + parent (:class:`str`): + Required. The parent account of the account relationship + to filter by. Format: ``accounts/{account}`` + + 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_accounts_v1.services.account_relationships_service.pagers.ListAccountRelationshipsAsyncPager: + Response after trying to list account + relationships. + 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, accountrelationships.ListAccountRelationshipsRequest): + request = accountrelationships.ListAccountRelationshipsRequest(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_account_relationships] + + # 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.ListAccountRelationshipsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AccountRelationshipsServiceAsyncClient": + 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__ = ( + "AccountRelationshipsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py new file mode 100644 index 000000000000..f35d0a48eb1e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py @@ -0,0 +1,1005 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.account_relationships_service import pagers +from google.shopping.merchant_accounts_v1.types import accountrelationships +from .transports.base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountRelationshipsServiceGrpcTransport +from .transports.grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport +from .transports.rest import AccountRelationshipsServiceRestTransport + + +class AccountRelationshipsServiceClientMeta(type): + """Metaclass for the AccountRelationshipsService 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[AccountRelationshipsServiceTransport]] + _transport_registry["grpc"] = AccountRelationshipsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountRelationshipsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountRelationshipsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountRelationshipsServiceTransport]: + """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 AccountRelationshipsServiceClient(metaclass=AccountRelationshipsServiceClientMeta): + """Service to support AccountRelationship API.""" + + @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: + AccountRelationshipsServiceClient: 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: + AccountRelationshipsServiceClient: 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) -> AccountRelationshipsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountRelationshipsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_relationship_path(account: str,relationship: str,) -> str: + """Returns a fully-qualified account_relationship string.""" + return "accounts/{account}/relationships/{relationship}".format(account=account, relationship=relationship, ) + + @staticmethod + def parse_account_relationship_path(path: str) -> Dict[str,str]: + """Parses a account_relationship path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/relationships/(?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 = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountRelationshipsServiceClient._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 = AccountRelationshipsServiceClient._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, AccountRelationshipsServiceTransport, Callable[..., AccountRelationshipsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account relationships 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,AccountRelationshipsServiceTransport,Callable[..., AccountRelationshipsServiceTransport]]]): + 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 AccountRelationshipsServiceTransport 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 = AccountRelationshipsServiceClient._read_environment_variables() + self._client_cert_source = AccountRelationshipsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountRelationshipsServiceClient._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, AccountRelationshipsServiceTransport) + if transport_provided: + # transport is a AccountRelationshipsServiceTransport 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(AccountRelationshipsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountRelationshipsServiceClient._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[AccountRelationshipsServiceTransport], Callable[..., AccountRelationshipsServiceTransport]] = ( + AccountRelationshipsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountRelationshipsServiceTransport], 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.accounts_v1.AccountRelationshipsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "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.accounts.v1.AccountRelationshipsService", + "credentialsType": None, + } + ) + + def get_account_relationship(self, + request: Optional[Union[accountrelationships.GetAccountRelationshipRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: + r"""Retrieve an account relationship. + + .. 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_accounts_v1 + + def sample_get_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRelationshipRequest( + name="name_value", + ) + + # Make the request + response = client.get_account_relationship(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetAccountRelationshipRequest, dict]): + The request object. Request to get an account + relationship. + name (str): + Required. The resource name of the account relationship + to get. Format: + ``accounts/{account}/relationships/{relationship}``. For + example, ``accounts/123456/relationships/567890``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AccountRelationship: + The AccountRelationship message defines a formal connection between a + merchant's account and a service provider's account. + This relationship enables the provider to offer + specific services to the business, such as product + management or campaign management. It specifies the + access rights and permissions to the business's data + relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). + + """ + # 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, accountrelationships.GetAccountRelationshipRequest): + request = accountrelationships.GetAccountRelationshipRequest(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.get_account_relationship] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_account_relationship(self, + request: Optional[Union[accountrelationships.UpdateAccountRelationshipRequest, dict]] = None, + *, + account_relationship: Optional[accountrelationships.AccountRelationship] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: + r"""Updates the account relationship. Executing this + method requires admin access. + + .. 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_accounts_v1 + + def sample_update_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAccountRelationshipRequest( + ) + + # Make the request + response = client.update_account_relationship(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateAccountRelationshipRequest, dict]): + The request object. Request message for the ``UpdateAccountRelationship`` + method. + account_relationship (google.shopping.merchant_accounts_v1.types.AccountRelationship): + Required. The new version of the + account relationship. + + This corresponds to the ``account_relationship`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``account_id_alias`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.AccountRelationship: + The AccountRelationship message defines a formal connection between a + merchant's account and a service provider's account. + This relationship enables the provider to offer + specific services to the business, such as product + management or campaign management. It specifies the + access rights and permissions to the business's data + relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). + + """ + # 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 = [account_relationship, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accountrelationships.UpdateAccountRelationshipRequest): + request = accountrelationships.UpdateAccountRelationshipRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account_relationship is not None: + request.account_relationship = account_relationship + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_account_relationship] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account_relationship.name", request.account_relationship.name), + )), + ) + + # 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 list_account_relationships(self, + request: Optional[Union[accountrelationships.ListAccountRelationshipsRequest, 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.ListAccountRelationshipsPager: + r"""List account relationships for the specified 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_accounts_v1 + + def sample_list_account_relationships(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountRelationshipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_relationships(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsRequest, dict]): + The request object. Request to list account + relationships. + parent (str): + Required. The parent account of the account relationship + to filter by. Format: ``accounts/{account}`` + + 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_accounts_v1.services.account_relationships_service.pagers.ListAccountRelationshipsPager: + Response after trying to list account + relationships. + 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, accountrelationships.ListAccountRelationshipsRequest): + request = accountrelationships.ListAccountRelationshipsRequest(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_account_relationships] + + # 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.ListAccountRelationshipsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AccountRelationshipsServiceClient": + 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__ = ( + "AccountRelationshipsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py new file mode 100644 index 000000000000..d05f4807759b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_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_accounts_v1.types import accountrelationships + + +class ListAccountRelationshipsPager: + """A pager for iterating through ``list_account_relationships`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_relationships`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountRelationships`` requests and continue to iterate + through the ``account_relationships`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsResponse` + 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[..., accountrelationships.ListAccountRelationshipsResponse], + request: accountrelationships.ListAccountRelationshipsRequest, + response: accountrelationships.ListAccountRelationshipsResponse, + *, + 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_accounts_v1.types.ListAccountRelationshipsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsResponse): + 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 = accountrelationships.ListAccountRelationshipsRequest(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[accountrelationships.ListAccountRelationshipsResponse]: + 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[accountrelationships.AccountRelationship]: + for page in self.pages: + yield from page.account_relationships + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountRelationshipsAsyncPager: + """A pager for iterating through ``list_account_relationships`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_relationships`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountRelationships`` requests and continue to iterate + through the ``account_relationships`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsResponse` + 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[accountrelationships.ListAccountRelationshipsResponse]], + request: accountrelationships.ListAccountRelationshipsRequest, + response: accountrelationships.ListAccountRelationshipsResponse, + *, + 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_accounts_v1.types.ListAccountRelationshipsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsResponse): + 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 = accountrelationships.ListAccountRelationshipsRequest(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[accountrelationships.ListAccountRelationshipsResponse]: + 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[accountrelationships.AccountRelationship]: + async def async_generator(): + async for page in self.pages: + for response in page.account_relationships: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst new file mode 100644 index 000000000000..08bddb1c4886 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountRelationshipsServiceTransport` is the ABC for all transports. +- public child `AccountRelationshipsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountRelationshipsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountRelationshipsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountRelationshipsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py new file mode 100644 index 000000000000..4f29f69c39f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_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 AccountRelationshipsServiceTransport +from .grpc import AccountRelationshipsServiceGrpcTransport +from .grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport +from .rest import AccountRelationshipsServiceRestTransport +from .rest import AccountRelationshipsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountRelationshipsServiceTransport]] +_transport_registry['grpc'] = AccountRelationshipsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountRelationshipsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountRelationshipsServiceRestTransport + +__all__ = ( + 'AccountRelationshipsServiceTransport', + 'AccountRelationshipsServiceGrpcTransport', + 'AccountRelationshipsServiceGrpcAsyncIOTransport', + 'AccountRelationshipsServiceRestTransport', + 'AccountRelationshipsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py new file mode 100644 index 000000000000..74824d32ffd2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py @@ -0,0 +1,187 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import accountrelationships + +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 AccountRelationshipsServiceTransport(abc.ABC): + """Abstract transport class for AccountRelationshipsService.""" + + 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.get_account_relationship: gapic_v1.method.wrap_method( + self.get_account_relationship, + default_timeout=None, + client_info=client_info, + ), + self.update_account_relationship: gapic_v1.method.wrap_method( + self.update_account_relationship, + default_timeout=None, + client_info=client_info, + ), + self.list_account_relationships: gapic_v1.method.wrap_method( + self.list_account_relationships, + 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 get_account_relationship(self) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + Union[ + accountrelationships.AccountRelationship, + Awaitable[accountrelationships.AccountRelationship] + ]]: + raise NotImplementedError() + + @property + def update_account_relationship(self) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + Union[ + accountrelationships.AccountRelationship, + Awaitable[accountrelationships.AccountRelationship] + ]]: + raise NotImplementedError() + + @property + def list_account_relationships(self) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + Union[ + accountrelationships.ListAccountRelationshipsResponse, + Awaitable[accountrelationships.ListAccountRelationshipsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountRelationshipsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py new file mode 100644 index 000000000000..93d4b61901e9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py @@ -0,0 +1,399 @@ +# -*- 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.shopping.merchant_accounts_v1.types import accountrelationships +from .base import AccountRelationshipsServiceTransport, 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.accounts.v1.AccountRelationshipsService", + "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.accounts.v1.AccountRelationshipsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountRelationshipsServiceGrpcTransport(AccountRelationshipsServiceTransport): + """gRPC backend transport for AccountRelationshipsService. + + Service to support AccountRelationship API. + + 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 get_account_relationship(self) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + accountrelationships.AccountRelationship]: + r"""Return a callable for the get account relationship method over gRPC. + + Retrieve an account relationship. + + Returns: + Callable[[~.GetAccountRelationshipRequest], + ~.AccountRelationship]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account_relationship' not in self._stubs: + self._stubs['get_account_relationship'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/GetAccountRelationship', + request_serializer=accountrelationships.GetAccountRelationshipRequest.serialize, + response_deserializer=accountrelationships.AccountRelationship.deserialize, + ) + return self._stubs['get_account_relationship'] + + @property + def update_account_relationship(self) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + accountrelationships.AccountRelationship]: + r"""Return a callable for the update account relationship method over gRPC. + + Updates the account relationship. Executing this + method requires admin access. + + Returns: + Callable[[~.UpdateAccountRelationshipRequest], + ~.AccountRelationship]: + 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 'update_account_relationship' not in self._stubs: + self._stubs['update_account_relationship'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/UpdateAccountRelationship', + request_serializer=accountrelationships.UpdateAccountRelationshipRequest.serialize, + response_deserializer=accountrelationships.AccountRelationship.deserialize, + ) + return self._stubs['update_account_relationship'] + + @property + def list_account_relationships(self) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + accountrelationships.ListAccountRelationshipsResponse]: + r"""Return a callable for the list account relationships method over gRPC. + + List account relationships for the specified account. + + Returns: + Callable[[~.ListAccountRelationshipsRequest], + ~.ListAccountRelationshipsResponse]: + 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_account_relationships' not in self._stubs: + self._stubs['list_account_relationships'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/ListAccountRelationships', + request_serializer=accountrelationships.ListAccountRelationshipsRequest.serialize, + response_deserializer=accountrelationships.ListAccountRelationshipsResponse.deserialize, + ) + return self._stubs['list_account_relationships'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountRelationshipsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..cc85204a38cc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py @@ -0,0 +1,430 @@ +# -*- 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.shopping.merchant_accounts_v1.types import accountrelationships +from .base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountRelationshipsServiceGrpcTransport + +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.accounts.v1.AccountRelationshipsService", + "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.accounts.v1.AccountRelationshipsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountRelationshipsServiceGrpcAsyncIOTransport(AccountRelationshipsServiceTransport): + """gRPC AsyncIO backend transport for AccountRelationshipsService. + + Service to support AccountRelationship API. + + 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 get_account_relationship(self) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + Awaitable[accountrelationships.AccountRelationship]]: + r"""Return a callable for the get account relationship method over gRPC. + + Retrieve an account relationship. + + Returns: + Callable[[~.GetAccountRelationshipRequest], + Awaitable[~.AccountRelationship]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account_relationship' not in self._stubs: + self._stubs['get_account_relationship'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/GetAccountRelationship', + request_serializer=accountrelationships.GetAccountRelationshipRequest.serialize, + response_deserializer=accountrelationships.AccountRelationship.deserialize, + ) + return self._stubs['get_account_relationship'] + + @property + def update_account_relationship(self) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + Awaitable[accountrelationships.AccountRelationship]]: + r"""Return a callable for the update account relationship method over gRPC. + + Updates the account relationship. Executing this + method requires admin access. + + Returns: + Callable[[~.UpdateAccountRelationshipRequest], + Awaitable[~.AccountRelationship]]: + 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 'update_account_relationship' not in self._stubs: + self._stubs['update_account_relationship'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/UpdateAccountRelationship', + request_serializer=accountrelationships.UpdateAccountRelationshipRequest.serialize, + response_deserializer=accountrelationships.AccountRelationship.deserialize, + ) + return self._stubs['update_account_relationship'] + + @property + def list_account_relationships(self) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + Awaitable[accountrelationships.ListAccountRelationshipsResponse]]: + r"""Return a callable for the list account relationships method over gRPC. + + List account relationships for the specified account. + + Returns: + Callable[[~.ListAccountRelationshipsRequest], + Awaitable[~.ListAccountRelationshipsResponse]]: + 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_account_relationships' not in self._stubs: + self._stubs['list_account_relationships'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/ListAccountRelationships', + request_serializer=accountrelationships.ListAccountRelationshipsRequest.serialize, + response_deserializer=accountrelationships.ListAccountRelationshipsResponse.deserialize, + ) + return self._stubs['list_account_relationships'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account_relationship: self._wrap_method( + self.get_account_relationship, + default_timeout=None, + client_info=client_info, + ), + self.update_account_relationship: self._wrap_method( + self.update_account_relationship, + default_timeout=None, + client_info=client_info, + ), + self.list_account_relationships: self._wrap_method( + self.list_account_relationships, + 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__ = ( + 'AccountRelationshipsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py new file mode 100644 index 000000000000..7a58a0d4e438 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py @@ -0,0 +1,729 @@ +# -*- 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.shopping.merchant_accounts_v1.types import accountrelationships + + +from .rest_base import _BaseAccountRelationshipsServiceRestTransport +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 AccountRelationshipsServiceRestInterceptor: + """Interceptor for AccountRelationshipsService. + + 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 AccountRelationshipsServiceRestTransport. + + .. code-block:: python + class MyCustomAccountRelationshipsServiceInterceptor(AccountRelationshipsServiceRestInterceptor): + def pre_get_account_relationship(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account_relationship(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_account_relationships(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_relationships(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_account_relationship(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_account_relationship(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AccountRelationshipsServiceRestTransport(interceptor=MyCustomAccountRelationshipsServiceInterceptor()) + client = AccountRelationshipsServiceClient(transport=transport) + + + """ + def pre_get_account_relationship(self, request: accountrelationships.GetAccountRelationshipRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.GetAccountRelationshipRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_account_relationship + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountRelationshipsService server. + """ + return request, metadata + + def post_get_account_relationship(self, response: accountrelationships.AccountRelationship) -> accountrelationships.AccountRelationship: + """Post-rpc interceptor for get_account_relationship + + DEPRECATED. Please use the `post_get_account_relationship_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountRelationshipsService server but before + it is returned to user code. This `post_get_account_relationship` interceptor runs + before the `post_get_account_relationship_with_metadata` interceptor. + """ + return response + + def post_get_account_relationship_with_metadata(self, response: accountrelationships.AccountRelationship, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.AccountRelationship, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_account_relationship + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountRelationshipsService server but before it is returned to user code. + + We recommend only using this `post_get_account_relationship_with_metadata` + interceptor in new development instead of the `post_get_account_relationship` interceptor. + When both interceptors are used, this `post_get_account_relationship_with_metadata` interceptor runs after the + `post_get_account_relationship` interceptor. The (possibly modified) response returned by + `post_get_account_relationship` will be passed to + `post_get_account_relationship_with_metadata`. + """ + return response, metadata + + def pre_list_account_relationships(self, request: accountrelationships.ListAccountRelationshipsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.ListAccountRelationshipsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_account_relationships + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountRelationshipsService server. + """ + return request, metadata + + def post_list_account_relationships(self, response: accountrelationships.ListAccountRelationshipsResponse) -> accountrelationships.ListAccountRelationshipsResponse: + """Post-rpc interceptor for list_account_relationships + + DEPRECATED. Please use the `post_list_account_relationships_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountRelationshipsService server but before + it is returned to user code. This `post_list_account_relationships` interceptor runs + before the `post_list_account_relationships_with_metadata` interceptor. + """ + return response + + def post_list_account_relationships_with_metadata(self, response: accountrelationships.ListAccountRelationshipsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.ListAccountRelationshipsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_account_relationships + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountRelationshipsService server but before it is returned to user code. + + We recommend only using this `post_list_account_relationships_with_metadata` + interceptor in new development instead of the `post_list_account_relationships` interceptor. + When both interceptors are used, this `post_list_account_relationships_with_metadata` interceptor runs after the + `post_list_account_relationships` interceptor. The (possibly modified) response returned by + `post_list_account_relationships` will be passed to + `post_list_account_relationships_with_metadata`. + """ + return response, metadata + + def pre_update_account_relationship(self, request: accountrelationships.UpdateAccountRelationshipRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.UpdateAccountRelationshipRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_account_relationship + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountRelationshipsService server. + """ + return request, metadata + + def post_update_account_relationship(self, response: accountrelationships.AccountRelationship) -> accountrelationships.AccountRelationship: + """Post-rpc interceptor for update_account_relationship + + DEPRECATED. Please use the `post_update_account_relationship_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountRelationshipsService server but before + it is returned to user code. This `post_update_account_relationship` interceptor runs + before the `post_update_account_relationship_with_metadata` interceptor. + """ + return response + + def post_update_account_relationship_with_metadata(self, response: accountrelationships.AccountRelationship, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.AccountRelationship, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_account_relationship + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountRelationshipsService server but before it is returned to user code. + + We recommend only using this `post_update_account_relationship_with_metadata` + interceptor in new development instead of the `post_update_account_relationship` interceptor. + When both interceptors are used, this `post_update_account_relationship_with_metadata` interceptor runs after the + `post_update_account_relationship` interceptor. The (possibly modified) response returned by + `post_update_account_relationship` will be passed to + `post_update_account_relationship_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AccountRelationshipsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountRelationshipsServiceRestInterceptor + + +class AccountRelationshipsServiceRestTransport(_BaseAccountRelationshipsServiceRestTransport): + """REST backend synchronous transport for AccountRelationshipsService. + + Service to support AccountRelationship API. + + 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[AccountRelationshipsServiceRestInterceptor] = 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 AccountRelationshipsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAccountRelationship(_BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship, AccountRelationshipsServiceRestStub): + def __hash__(self): + return hash("AccountRelationshipsServiceRestTransport.GetAccountRelationship") + + @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: accountrelationships.GetAccountRelationshipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountrelationships.AccountRelationship: + r"""Call the get account relationship method over HTTP. + + Args: + request (~.accountrelationships.GetAccountRelationshipRequest): + The request object. Request to get an account + relationship. + 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: + ~.accountrelationships.AccountRelationship: + The ``AccountRelationship`` message defines a formal + connection between a merchant's account and a service + provider's account. This relationship enables the + provider to offer specific services to the business, + such as product management or campaign management. It + specifies the access rights and permissions to the + business's data relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). + + """ + + http_options = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_http_options() + + request, metadata = self._interceptor.pre_get_account_relationship(request, metadata) + transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountRelationshipsServiceClient.GetAccountRelationship", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "rpcName": "GetAccountRelationship", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountRelationshipsServiceRestTransport._GetAccountRelationship._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 = accountrelationships.AccountRelationship() + pb_resp = accountrelationships.AccountRelationship.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_account_relationship(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_account_relationship_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountrelationships.AccountRelationship.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.accounts_v1.AccountRelationshipsServiceClient.get_account_relationship", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "rpcName": "GetAccountRelationship", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAccountRelationships(_BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships, AccountRelationshipsServiceRestStub): + def __hash__(self): + return hash("AccountRelationshipsServiceRestTransport.ListAccountRelationships") + + @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: accountrelationships.ListAccountRelationshipsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountrelationships.ListAccountRelationshipsResponse: + r"""Call the list account + relationships method over HTTP. + + Args: + request (~.accountrelationships.ListAccountRelationshipsRequest): + The request object. Request to list account + relationships. + 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: + ~.accountrelationships.ListAccountRelationshipsResponse: + Response after trying to list account + relationships. + + """ + + http_options = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_http_options() + + request, metadata = self._interceptor.pre_list_account_relationships(request, metadata) + transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountRelationshipsServiceClient.ListAccountRelationships", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "rpcName": "ListAccountRelationships", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountRelationshipsServiceRestTransport._ListAccountRelationships._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 = accountrelationships.ListAccountRelationshipsResponse() + pb_resp = accountrelationships.ListAccountRelationshipsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_account_relationships(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_account_relationships_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountrelationships.ListAccountRelationshipsResponse.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.accounts_v1.AccountRelationshipsServiceClient.list_account_relationships", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "rpcName": "ListAccountRelationships", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAccountRelationship(_BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship, AccountRelationshipsServiceRestStub): + def __hash__(self): + return hash("AccountRelationshipsServiceRestTransport.UpdateAccountRelationship") + + @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: accountrelationships.UpdateAccountRelationshipRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountrelationships.AccountRelationship: + r"""Call the update account + relationship method over HTTP. + + Args: + request (~.accountrelationships.UpdateAccountRelationshipRequest): + The request object. Request message for the ``UpdateAccountRelationship`` + 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: + ~.accountrelationships.AccountRelationship: + The ``AccountRelationship`` message defines a formal + connection between a merchant's account and a service + provider's account. This relationship enables the + provider to offer specific services to the business, + such as product management or campaign management. It + specifies the access rights and permissions to the + business's data relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). + + """ + + http_options = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_http_options() + + request, metadata = self._interceptor.pre_update_account_relationship(request, metadata) + transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_transcoded_request(http_options, request) + + body = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountRelationshipsServiceClient.UpdateAccountRelationship", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "rpcName": "UpdateAccountRelationship", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountRelationshipsServiceRestTransport._UpdateAccountRelationship._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 = accountrelationships.AccountRelationship() + pb_resp = accountrelationships.AccountRelationship.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_account_relationship(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_account_relationship_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountrelationships.AccountRelationship.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.accounts_v1.AccountRelationshipsServiceClient.update_account_relationship", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "rpcName": "UpdateAccountRelationship", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_account_relationship(self) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + accountrelationships.AccountRelationship]: + # 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._GetAccountRelationship(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_account_relationships(self) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + accountrelationships.ListAccountRelationshipsResponse]: + # 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._ListAccountRelationships(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_account_relationship(self) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + accountrelationships.AccountRelationship]: + # 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._UpdateAccountRelationship(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountRelationshipsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py new file mode 100644 index 000000000000..a7128850a38e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py @@ -0,0 +1,212 @@ +# -*- 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 AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import accountrelationships + + +class _BaseAccountRelationshipsServiceRestTransport(AccountRelationshipsServiceTransport): + """Base REST backend transport for AccountRelationshipsService. + + 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 _BaseGetAccountRelationship: + 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': '/accounts/v1/{name=accounts/*/relationships/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountrelationships.GetAccountRelationshipRequest.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(_BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAccountRelationships: + 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': '/accounts/v1/{parent=accounts/*}/relationships', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountrelationships.ListAccountRelationshipsRequest.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(_BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAccountRelationship: + 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': 'patch', + 'uri': '/accounts/v1/{account_relationship.name=accounts/*/relationships/*}', + 'body': 'account_relationship', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountrelationships.UpdateAccountRelationshipRequest.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(_BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountRelationshipsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py new file mode 100644 index 000000000000..efc4082a21be --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_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 AccountServicesServiceClient +from .async_client import AccountServicesServiceAsyncClient + +__all__ = ( + 'AccountServicesServiceClient', + 'AccountServicesServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py new file mode 100644 index 000000000000..58cc86a7124f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py @@ -0,0 +1,890 @@ +# -*- 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_accounts_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_accounts_v1.services.account_services_service import pagers +from google.shopping.merchant_accounts_v1.types import accountservices +from .transports.base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport +from .client import AccountServicesServiceClient + +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 AccountServicesServiceAsyncClient: + """Service to support AccountService API.""" + + _client: AccountServicesServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountServicesServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountServicesServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AccountServicesServiceClient.account_path) + parse_account_path = staticmethod(AccountServicesServiceClient.parse_account_path) + account_service_path = staticmethod(AccountServicesServiceClient.account_service_path) + parse_account_service_path = staticmethod(AccountServicesServiceClient.parse_account_service_path) + common_billing_account_path = staticmethod(AccountServicesServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountServicesServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountServicesServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountServicesServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountServicesServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountServicesServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountServicesServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountServicesServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountServicesServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountServicesServiceClient.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: + AccountServicesServiceAsyncClient: The constructed client. + """ + return AccountServicesServiceClient.from_service_account_info.__func__(AccountServicesServiceAsyncClient, 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: + AccountServicesServiceAsyncClient: The constructed client. + """ + return AccountServicesServiceClient.from_service_account_file.__func__(AccountServicesServiceAsyncClient, 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 AccountServicesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountServicesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountServicesServiceTransport: 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 = AccountServicesServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountServicesServiceTransport, Callable[..., AccountServicesServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account services 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,AccountServicesServiceTransport,Callable[..., AccountServicesServiceTransport]]]): + 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 AccountServicesServiceTransport 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 = AccountServicesServiceClient( + 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.accounts_v1.AccountServicesServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "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.accounts.v1.AccountServicesService", + "credentialsType": None, + } + ) + + async def get_account_service(self, + request: Optional[Union[accountservices.GetAccountServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: + r"""Retrieve an account service. + + .. 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_accounts_v1 + + async def sample_get_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetAccountServiceRequest, dict]]): + The request object. Request to get an account service. + name (:class:`str`): + Required. The resource name of the account service to + get. Format: ``accounts/{account}/services/{service}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AccountService: + The AccountService message represents a specific service that a provider + account offers to a Merchant Center account. + + AccountService defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an AccountService involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts + or rejects it. This handshake mechanism ensures + mutual consent before any access is granted. This + mechanism safeguards both parties by ensuring that + access rights are granted appropriately and that both + the business and provider are aware of the services + enabled. In scenarios where a user is an admin of + both accounts, the approval can happen automatically. + + The mutability of a service is also managed through + AccountService. Some services might be immutable, for + example, if they were established through other + systems or APIs, and you cannot alter them through + this API. + + """ + # 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, accountservices.GetAccountServiceRequest): + request = accountservices.GetAccountServiceRequest(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.get_account_service] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_account_services(self, + request: Optional[Union[accountservices.ListAccountServicesRequest, 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.ListAccountServicesAsyncPager: + r"""List account services for the specified accounts. + Supports filtering. + + .. 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_accounts_v1 + + async def sample_list_account_services(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListAccountServicesRequest, dict]]): + The request object. Request to list account services. + parent (:class:`str`): + Required. The parent account of the account service to + filter by. Format: ``accounts/{account}`` + + 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_accounts_v1.services.account_services_service.pagers.ListAccountServicesAsyncPager: + Response after trying to list account + services. + 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, accountservices.ListAccountServicesRequest): + request = accountservices.ListAccountServicesRequest(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_account_services] + + # 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.ListAccountServicesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def propose_account_service(self, + request: Optional[Union[accountservices.ProposeAccountServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + provider: Optional[str] = None, + account_service: Optional[accountservices.AccountService] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: + r"""Propose an account service. + + .. 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_accounts_v1 + + async def sample_propose_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ProposeAccountServiceRequest( + parent="parent_value", + provider="provider_value", + ) + + # Make the request + response = await client.propose_account_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ProposeAccountServiceRequest, dict]]): + The request object. Request to propose an account + service. + parent (:class:`str`): + Required. The resource name of the parent account for + the service. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + provider (:class:`str`): + Required. The provider of the service. Either the + reference to an account such as ``providers/123`` or a + well-known service provider (one of + ``providers/GOOGLE_ADS`` or + ``providers/GOOGLE_BUSINESS_PROFILE``). + + This corresponds to the ``provider`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + account_service (:class:`google.shopping.merchant_accounts_v1.types.AccountService`): + Required. The account service to + propose. + + This corresponds to the ``account_service`` 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_accounts_v1.types.AccountService: + The AccountService message represents a specific service that a provider + account offers to a Merchant Center account. + + AccountService defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an AccountService involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts + or rejects it. This handshake mechanism ensures + mutual consent before any access is granted. This + mechanism safeguards both parties by ensuring that + access rights are granted appropriately and that both + the business and provider are aware of the services + enabled. In scenarios where a user is an admin of + both accounts, the approval can happen automatically. + + The mutability of a service is also managed through + AccountService. Some services might be immutable, for + example, if they were established through other + systems or APIs, and you cannot alter them through + this API. + + """ + # 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, provider, account_service] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accountservices.ProposeAccountServiceRequest): + request = accountservices.ProposeAccountServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if provider is not None: + request.provider = provider + if account_service is not None: + request.account_service = account_service + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.propose_account_service] + + # 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 approve_account_service(self, + request: Optional[Union[accountservices.ApproveAccountServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: + r"""Approve an account service proposal. + + .. 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_accounts_v1 + + async def sample_approve_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ApproveAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.approve_account_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ApproveAccountServiceRequest, dict]]): + The request object. Request to approve an account + service. + name (:class:`str`): + Required. The resource name of the account service to + approve. Format: + ``accounts/{account}/services/{service}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AccountService: + The AccountService message represents a specific service that a provider + account offers to a Merchant Center account. + + AccountService defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an AccountService involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts + or rejects it. This handshake mechanism ensures + mutual consent before any access is granted. This + mechanism safeguards both parties by ensuring that + access rights are granted appropriately and that both + the business and provider are aware of the services + enabled. In scenarios where a user is an admin of + both accounts, the approval can happen automatically. + + The mutability of a service is also managed through + AccountService. Some services might be immutable, for + example, if they were established through other + systems or APIs, and you cannot alter them through + this API. + + """ + # 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, accountservices.ApproveAccountServiceRequest): + request = accountservices.ApproveAccountServiceRequest(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.approve_account_service] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def reject_account_service(self, + request: Optional[Union[accountservices.RejectAccountServiceRequest, dict]] = None, + *, + name: 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"""Reject an account service (both proposed and approve + services can be rejected). + + .. 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_accounts_v1 + + async def sample_reject_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RejectAccountServiceRequest( + name="name_value", + ) + + # Make the request + await client.reject_account_service(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.RejectAccountServiceRequest, dict]]): + The request object. Request to reject an account service. + name (:class:`str`): + Required. The resource name of the account service to + reject. Format: + ``accounts/{account}/services/{service}`` + + 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, accountservices.RejectAccountServiceRequest): + request = accountservices.RejectAccountServiceRequest(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.reject_account_service] + + # 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) -> "AccountServicesServiceAsyncClient": + 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__ = ( + "AccountServicesServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py new file mode 100644 index 000000000000..28ae78a24341 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py @@ -0,0 +1,1255 @@ +# -*- 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_accounts_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_accounts_v1.services.account_services_service import pagers +from google.shopping.merchant_accounts_v1.types import accountservices +from .transports.base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountServicesServiceGrpcTransport +from .transports.grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport +from .transports.rest import AccountServicesServiceRestTransport + + +class AccountServicesServiceClientMeta(type): + """Metaclass for the AccountServicesService 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[AccountServicesServiceTransport]] + _transport_registry["grpc"] = AccountServicesServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountServicesServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountServicesServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountServicesServiceTransport]: + """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 AccountServicesServiceClient(metaclass=AccountServicesServiceClientMeta): + """Service to support AccountService API.""" + + @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: + AccountServicesServiceClient: 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: + AccountServicesServiceClient: 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) -> AccountServicesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountServicesServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_service_path(account: str,service: str,) -> str: + """Returns a fully-qualified account_service string.""" + return "accounts/{account}/services/{service}".format(account=account, service=service, ) + + @staticmethod + def parse_account_service_path(path: str) -> Dict[str,str]: + """Parses a account_service path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/services/(?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 = AccountServicesServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountServicesServiceClient._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 = AccountServicesServiceClient._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, AccountServicesServiceTransport, Callable[..., AccountServicesServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account services 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,AccountServicesServiceTransport,Callable[..., AccountServicesServiceTransport]]]): + 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 AccountServicesServiceTransport 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 = AccountServicesServiceClient._read_environment_variables() + self._client_cert_source = AccountServicesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountServicesServiceClient._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, AccountServicesServiceTransport) + if transport_provided: + # transport is a AccountServicesServiceTransport 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(AccountServicesServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountServicesServiceClient._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[AccountServicesServiceTransport], Callable[..., AccountServicesServiceTransport]] = ( + AccountServicesServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountServicesServiceTransport], 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.accounts_v1.AccountServicesServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "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.accounts.v1.AccountServicesService", + "credentialsType": None, + } + ) + + def get_account_service(self, + request: Optional[Union[accountservices.GetAccountServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: + r"""Retrieve an account service. + + .. 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_accounts_v1 + + def sample_get_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_account_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetAccountServiceRequest, dict]): + The request object. Request to get an account service. + name (str): + Required. The resource name of the account service to + get. Format: ``accounts/{account}/services/{service}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AccountService: + The AccountService message represents a specific service that a provider + account offers to a Merchant Center account. + + AccountService defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an AccountService involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts + or rejects it. This handshake mechanism ensures + mutual consent before any access is granted. This + mechanism safeguards both parties by ensuring that + access rights are granted appropriately and that both + the business and provider are aware of the services + enabled. In scenarios where a user is an admin of + both accounts, the approval can happen automatically. + + The mutability of a service is also managed through + AccountService. Some services might be immutable, for + example, if they were established through other + systems or APIs, and you cannot alter them through + this API. + + """ + # 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, accountservices.GetAccountServiceRequest): + request = accountservices.GetAccountServiceRequest(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.get_account_service] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_account_services(self, + request: Optional[Union[accountservices.ListAccountServicesRequest, 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.ListAccountServicesPager: + r"""List account services for the specified accounts. + Supports filtering. + + .. 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_accounts_v1 + + def sample_list_account_services(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_services(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListAccountServicesRequest, dict]): + The request object. Request to list account services. + parent (str): + Required. The parent account of the account service to + filter by. Format: ``accounts/{account}`` + + 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_accounts_v1.services.account_services_service.pagers.ListAccountServicesPager: + Response after trying to list account + services. + 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, accountservices.ListAccountServicesRequest): + request = accountservices.ListAccountServicesRequest(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_account_services] + + # 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.ListAccountServicesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def propose_account_service(self, + request: Optional[Union[accountservices.ProposeAccountServiceRequest, dict]] = None, + *, + parent: Optional[str] = None, + provider: Optional[str] = None, + account_service: Optional[accountservices.AccountService] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: + r"""Propose an account service. + + .. 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_accounts_v1 + + def sample_propose_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ProposeAccountServiceRequest( + parent="parent_value", + provider="provider_value", + ) + + # Make the request + response = client.propose_account_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ProposeAccountServiceRequest, dict]): + The request object. Request to propose an account + service. + parent (str): + Required. The resource name of the parent account for + the service. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + provider (str): + Required. The provider of the service. Either the + reference to an account such as ``providers/123`` or a + well-known service provider (one of + ``providers/GOOGLE_ADS`` or + ``providers/GOOGLE_BUSINESS_PROFILE``). + + This corresponds to the ``provider`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + account_service (google.shopping.merchant_accounts_v1.types.AccountService): + Required. The account service to + propose. + + This corresponds to the ``account_service`` 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_accounts_v1.types.AccountService: + The AccountService message represents a specific service that a provider + account offers to a Merchant Center account. + + AccountService defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an AccountService involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts + or rejects it. This handshake mechanism ensures + mutual consent before any access is granted. This + mechanism safeguards both parties by ensuring that + access rights are granted appropriately and that both + the business and provider are aware of the services + enabled. In scenarios where a user is an admin of + both accounts, the approval can happen automatically. + + The mutability of a service is also managed through + AccountService. Some services might be immutable, for + example, if they were established through other + systems or APIs, and you cannot alter them through + this API. + + """ + # 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, provider, account_service] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accountservices.ProposeAccountServiceRequest): + request = accountservices.ProposeAccountServiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if provider is not None: + request.provider = provider + if account_service is not None: + request.account_service = account_service + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.propose_account_service] + + # 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 approve_account_service(self, + request: Optional[Union[accountservices.ApproveAccountServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: + r"""Approve an account service proposal. + + .. 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_accounts_v1 + + def sample_approve_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ApproveAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = client.approve_account_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ApproveAccountServiceRequest, dict]): + The request object. Request to approve an account + service. + name (str): + Required. The resource name of the account service to + approve. Format: + ``accounts/{account}/services/{service}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AccountService: + The AccountService message represents a specific service that a provider + account offers to a Merchant Center account. + + AccountService defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an AccountService involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts + or rejects it. This handshake mechanism ensures + mutual consent before any access is granted. This + mechanism safeguards both parties by ensuring that + access rights are granted appropriately and that both + the business and provider are aware of the services + enabled. In scenarios where a user is an admin of + both accounts, the approval can happen automatically. + + The mutability of a service is also managed through + AccountService. Some services might be immutable, for + example, if they were established through other + systems or APIs, and you cannot alter them through + this API. + + """ + # 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, accountservices.ApproveAccountServiceRequest): + request = accountservices.ApproveAccountServiceRequest(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.approve_account_service] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def reject_account_service(self, + request: Optional[Union[accountservices.RejectAccountServiceRequest, dict]] = None, + *, + name: 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"""Reject an account service (both proposed and approve + services can be rejected). + + .. 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_accounts_v1 + + def sample_reject_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RejectAccountServiceRequest( + name="name_value", + ) + + # Make the request + client.reject_account_service(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.RejectAccountServiceRequest, dict]): + The request object. Request to reject an account service. + name (str): + Required. The resource name of the account service to + reject. Format: + ``accounts/{account}/services/{service}`` + + 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, accountservices.RejectAccountServiceRequest): + request = accountservices.RejectAccountServiceRequest(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.reject_account_service] + + # 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) -> "AccountServicesServiceClient": + 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__ = ( + "AccountServicesServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py new file mode 100644 index 000000000000..9c6b3e52eaf5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_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_accounts_v1.types import accountservices + + +class ListAccountServicesPager: + """A pager for iterating through ``list_account_services`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountServices`` requests and continue to iterate + through the ``account_services`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountServicesResponse` + 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[..., accountservices.ListAccountServicesResponse], + request: accountservices.ListAccountServicesRequest, + response: accountservices.ListAccountServicesResponse, + *, + 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_accounts_v1.types.ListAccountServicesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountServicesResponse): + 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 = accountservices.ListAccountServicesRequest(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[accountservices.ListAccountServicesResponse]: + 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[accountservices.AccountService]: + for page in self.pages: + yield from page.account_services + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountServicesAsyncPager: + """A pager for iterating through ``list_account_services`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountServices`` requests and continue to iterate + through the ``account_services`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountServicesResponse` + 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[accountservices.ListAccountServicesResponse]], + request: accountservices.ListAccountServicesRequest, + response: accountservices.ListAccountServicesResponse, + *, + 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_accounts_v1.types.ListAccountServicesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountServicesResponse): + 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 = accountservices.ListAccountServicesRequest(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[accountservices.ListAccountServicesResponse]: + 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[accountservices.AccountService]: + async def async_generator(): + async for page in self.pages: + for response in page.account_services: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst new file mode 100644 index 000000000000..9488a4e8af5d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountServicesServiceTransport` is the ABC for all transports. +- public child `AccountServicesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountServicesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountServicesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountServicesServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py new file mode 100644 index 000000000000..51c38ac42781 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_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 AccountServicesServiceTransport +from .grpc import AccountServicesServiceGrpcTransport +from .grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport +from .rest import AccountServicesServiceRestTransport +from .rest import AccountServicesServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountServicesServiceTransport]] +_transport_registry['grpc'] = AccountServicesServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountServicesServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountServicesServiceRestTransport + +__all__ = ( + 'AccountServicesServiceTransport', + 'AccountServicesServiceGrpcTransport', + 'AccountServicesServiceGrpcAsyncIOTransport', + 'AccountServicesServiceRestTransport', + 'AccountServicesServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py new file mode 100644 index 000000000000..dd1d691bdd22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py @@ -0,0 +1,216 @@ +# -*- 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_accounts_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_accounts_v1.types import accountservices + +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 AccountServicesServiceTransport(abc.ABC): + """Abstract transport class for AccountServicesService.""" + + 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.get_account_service: gapic_v1.method.wrap_method( + self.get_account_service, + default_timeout=None, + client_info=client_info, + ), + self.list_account_services: gapic_v1.method.wrap_method( + self.list_account_services, + default_timeout=None, + client_info=client_info, + ), + self.propose_account_service: gapic_v1.method.wrap_method( + self.propose_account_service, + default_timeout=None, + client_info=client_info, + ), + self.approve_account_service: gapic_v1.method.wrap_method( + self.approve_account_service, + default_timeout=None, + client_info=client_info, + ), + self.reject_account_service: gapic_v1.method.wrap_method( + self.reject_account_service, + 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 get_account_service(self) -> Callable[ + [accountservices.GetAccountServiceRequest], + Union[ + accountservices.AccountService, + Awaitable[accountservices.AccountService] + ]]: + raise NotImplementedError() + + @property + def list_account_services(self) -> Callable[ + [accountservices.ListAccountServicesRequest], + Union[ + accountservices.ListAccountServicesResponse, + Awaitable[accountservices.ListAccountServicesResponse] + ]]: + raise NotImplementedError() + + @property + def propose_account_service(self) -> Callable[ + [accountservices.ProposeAccountServiceRequest], + Union[ + accountservices.AccountService, + Awaitable[accountservices.AccountService] + ]]: + raise NotImplementedError() + + @property + def approve_account_service(self) -> Callable[ + [accountservices.ApproveAccountServiceRequest], + Union[ + accountservices.AccountService, + Awaitable[accountservices.AccountService] + ]]: + raise NotImplementedError() + + @property + def reject_account_service(self) -> Callable[ + [accountservices.RejectAccountServiceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountServicesServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py new file mode 100644 index 000000000000..f009ad51edf7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py @@ -0,0 +1,453 @@ +# -*- 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_accounts_v1.types import accountservices +from .base import AccountServicesServiceTransport, 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.accounts.v1.AccountServicesService", + "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.accounts.v1.AccountServicesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountServicesServiceGrpcTransport(AccountServicesServiceTransport): + """gRPC backend transport for AccountServicesService. + + Service to support AccountService API. + + 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 get_account_service(self) -> Callable[ + [accountservices.GetAccountServiceRequest], + accountservices.AccountService]: + r"""Return a callable for the get account service method over gRPC. + + Retrieve an account service. + + Returns: + Callable[[~.GetAccountServiceRequest], + ~.AccountService]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account_service' not in self._stubs: + self._stubs['get_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/GetAccountService', + request_serializer=accountservices.GetAccountServiceRequest.serialize, + response_deserializer=accountservices.AccountService.deserialize, + ) + return self._stubs['get_account_service'] + + @property + def list_account_services(self) -> Callable[ + [accountservices.ListAccountServicesRequest], + accountservices.ListAccountServicesResponse]: + r"""Return a callable for the list account services method over gRPC. + + List account services for the specified accounts. + Supports filtering. + + Returns: + Callable[[~.ListAccountServicesRequest], + ~.ListAccountServicesResponse]: + 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_account_services' not in self._stubs: + self._stubs['list_account_services'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/ListAccountServices', + request_serializer=accountservices.ListAccountServicesRequest.serialize, + response_deserializer=accountservices.ListAccountServicesResponse.deserialize, + ) + return self._stubs['list_account_services'] + + @property + def propose_account_service(self) -> Callable[ + [accountservices.ProposeAccountServiceRequest], + accountservices.AccountService]: + r"""Return a callable for the propose account service method over gRPC. + + Propose an account service. + + Returns: + Callable[[~.ProposeAccountServiceRequest], + ~.AccountService]: + 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 'propose_account_service' not in self._stubs: + self._stubs['propose_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/ProposeAccountService', + request_serializer=accountservices.ProposeAccountServiceRequest.serialize, + response_deserializer=accountservices.AccountService.deserialize, + ) + return self._stubs['propose_account_service'] + + @property + def approve_account_service(self) -> Callable[ + [accountservices.ApproveAccountServiceRequest], + accountservices.AccountService]: + r"""Return a callable for the approve account service method over gRPC. + + Approve an account service proposal. + + Returns: + Callable[[~.ApproveAccountServiceRequest], + ~.AccountService]: + 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 'approve_account_service' not in self._stubs: + self._stubs['approve_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/ApproveAccountService', + request_serializer=accountservices.ApproveAccountServiceRequest.serialize, + response_deserializer=accountservices.AccountService.deserialize, + ) + return self._stubs['approve_account_service'] + + @property + def reject_account_service(self) -> Callable[ + [accountservices.RejectAccountServiceRequest], + empty_pb2.Empty]: + r"""Return a callable for the reject account service method over gRPC. + + Reject an account service (both proposed and approve + services can be rejected). + + Returns: + Callable[[~.RejectAccountServiceRequest], + ~.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 'reject_account_service' not in self._stubs: + self._stubs['reject_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/RejectAccountService', + request_serializer=accountservices.RejectAccountServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['reject_account_service'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountServicesServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9e23f8c0f3c1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py @@ -0,0 +1,494 @@ +# -*- 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_accounts_v1.types import accountservices +from .base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountServicesServiceGrpcTransport + +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.accounts.v1.AccountServicesService", + "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.accounts.v1.AccountServicesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountServicesServiceGrpcAsyncIOTransport(AccountServicesServiceTransport): + """gRPC AsyncIO backend transport for AccountServicesService. + + Service to support AccountService API. + + 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 get_account_service(self) -> Callable[ + [accountservices.GetAccountServiceRequest], + Awaitable[accountservices.AccountService]]: + r"""Return a callable for the get account service method over gRPC. + + Retrieve an account service. + + Returns: + Callable[[~.GetAccountServiceRequest], + Awaitable[~.AccountService]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account_service' not in self._stubs: + self._stubs['get_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/GetAccountService', + request_serializer=accountservices.GetAccountServiceRequest.serialize, + response_deserializer=accountservices.AccountService.deserialize, + ) + return self._stubs['get_account_service'] + + @property + def list_account_services(self) -> Callable[ + [accountservices.ListAccountServicesRequest], + Awaitable[accountservices.ListAccountServicesResponse]]: + r"""Return a callable for the list account services method over gRPC. + + List account services for the specified accounts. + Supports filtering. + + Returns: + Callable[[~.ListAccountServicesRequest], + Awaitable[~.ListAccountServicesResponse]]: + 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_account_services' not in self._stubs: + self._stubs['list_account_services'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/ListAccountServices', + request_serializer=accountservices.ListAccountServicesRequest.serialize, + response_deserializer=accountservices.ListAccountServicesResponse.deserialize, + ) + return self._stubs['list_account_services'] + + @property + def propose_account_service(self) -> Callable[ + [accountservices.ProposeAccountServiceRequest], + Awaitable[accountservices.AccountService]]: + r"""Return a callable for the propose account service method over gRPC. + + Propose an account service. + + Returns: + Callable[[~.ProposeAccountServiceRequest], + Awaitable[~.AccountService]]: + 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 'propose_account_service' not in self._stubs: + self._stubs['propose_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/ProposeAccountService', + request_serializer=accountservices.ProposeAccountServiceRequest.serialize, + response_deserializer=accountservices.AccountService.deserialize, + ) + return self._stubs['propose_account_service'] + + @property + def approve_account_service(self) -> Callable[ + [accountservices.ApproveAccountServiceRequest], + Awaitable[accountservices.AccountService]]: + r"""Return a callable for the approve account service method over gRPC. + + Approve an account service proposal. + + Returns: + Callable[[~.ApproveAccountServiceRequest], + Awaitable[~.AccountService]]: + 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 'approve_account_service' not in self._stubs: + self._stubs['approve_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/ApproveAccountService', + request_serializer=accountservices.ApproveAccountServiceRequest.serialize, + response_deserializer=accountservices.AccountService.deserialize, + ) + return self._stubs['approve_account_service'] + + @property + def reject_account_service(self) -> Callable[ + [accountservices.RejectAccountServiceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the reject account service method over gRPC. + + Reject an account service (both proposed and approve + services can be rejected). + + Returns: + Callable[[~.RejectAccountServiceRequest], + 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 'reject_account_service' not in self._stubs: + self._stubs['reject_account_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountServicesService/RejectAccountService', + request_serializer=accountservices.RejectAccountServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['reject_account_service'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account_service: self._wrap_method( + self.get_account_service, + default_timeout=None, + client_info=client_info, + ), + self.list_account_services: self._wrap_method( + self.list_account_services, + default_timeout=None, + client_info=client_info, + ), + self.propose_account_service: self._wrap_method( + self.propose_account_service, + default_timeout=None, + client_info=client_info, + ), + self.approve_account_service: self._wrap_method( + self.approve_account_service, + default_timeout=None, + client_info=client_info, + ), + self.reject_account_service: self._wrap_method( + self.reject_account_service, + 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__ = ( + 'AccountServicesServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py new file mode 100644 index 000000000000..c5fc207721aa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py @@ -0,0 +1,1058 @@ +# -*- 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_accounts_v1.types import accountservices + + +from .rest_base import _BaseAccountServicesServiceRestTransport +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 AccountServicesServiceRestInterceptor: + """Interceptor for AccountServicesService. + + 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 AccountServicesServiceRestTransport. + + .. code-block:: python + class MyCustomAccountServicesServiceInterceptor(AccountServicesServiceRestInterceptor): + def pre_approve_account_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_approve_account_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_account_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_account_services(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_services(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_propose_account_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_propose_account_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reject_account_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + transport = AccountServicesServiceRestTransport(interceptor=MyCustomAccountServicesServiceInterceptor()) + client = AccountServicesServiceClient(transport=transport) + + + """ + def pre_approve_account_service(self, request: accountservices.ApproveAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ApproveAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for approve_account_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountServicesService server. + """ + return request, metadata + + def post_approve_account_service(self, response: accountservices.AccountService) -> accountservices.AccountService: + """Post-rpc interceptor for approve_account_service + + DEPRECATED. Please use the `post_approve_account_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountServicesService server but before + it is returned to user code. This `post_approve_account_service` interceptor runs + before the `post_approve_account_service_with_metadata` interceptor. + """ + return response + + def post_approve_account_service_with_metadata(self, response: accountservices.AccountService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for approve_account_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountServicesService server but before it is returned to user code. + + We recommend only using this `post_approve_account_service_with_metadata` + interceptor in new development instead of the `post_approve_account_service` interceptor. + When both interceptors are used, this `post_approve_account_service_with_metadata` interceptor runs after the + `post_approve_account_service` interceptor. The (possibly modified) response returned by + `post_approve_account_service` will be passed to + `post_approve_account_service_with_metadata`. + """ + return response, metadata + + def pre_get_account_service(self, request: accountservices.GetAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.GetAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_account_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountServicesService server. + """ + return request, metadata + + def post_get_account_service(self, response: accountservices.AccountService) -> accountservices.AccountService: + """Post-rpc interceptor for get_account_service + + DEPRECATED. Please use the `post_get_account_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountServicesService server but before + it is returned to user code. This `post_get_account_service` interceptor runs + before the `post_get_account_service_with_metadata` interceptor. + """ + return response + + def post_get_account_service_with_metadata(self, response: accountservices.AccountService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_account_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountServicesService server but before it is returned to user code. + + We recommend only using this `post_get_account_service_with_metadata` + interceptor in new development instead of the `post_get_account_service` interceptor. + When both interceptors are used, this `post_get_account_service_with_metadata` interceptor runs after the + `post_get_account_service` interceptor. The (possibly modified) response returned by + `post_get_account_service` will be passed to + `post_get_account_service_with_metadata`. + """ + return response, metadata + + def pre_list_account_services(self, request: accountservices.ListAccountServicesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ListAccountServicesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_account_services + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountServicesService server. + """ + return request, metadata + + def post_list_account_services(self, response: accountservices.ListAccountServicesResponse) -> accountservices.ListAccountServicesResponse: + """Post-rpc interceptor for list_account_services + + DEPRECATED. Please use the `post_list_account_services_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountServicesService server but before + it is returned to user code. This `post_list_account_services` interceptor runs + before the `post_list_account_services_with_metadata` interceptor. + """ + return response + + def post_list_account_services_with_metadata(self, response: accountservices.ListAccountServicesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ListAccountServicesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_account_services + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountServicesService server but before it is returned to user code. + + We recommend only using this `post_list_account_services_with_metadata` + interceptor in new development instead of the `post_list_account_services` interceptor. + When both interceptors are used, this `post_list_account_services_with_metadata` interceptor runs after the + `post_list_account_services` interceptor. The (possibly modified) response returned by + `post_list_account_services` will be passed to + `post_list_account_services_with_metadata`. + """ + return response, metadata + + def pre_propose_account_service(self, request: accountservices.ProposeAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ProposeAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for propose_account_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountServicesService server. + """ + return request, metadata + + def post_propose_account_service(self, response: accountservices.AccountService) -> accountservices.AccountService: + """Post-rpc interceptor for propose_account_service + + DEPRECATED. Please use the `post_propose_account_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountServicesService server but before + it is returned to user code. This `post_propose_account_service` interceptor runs + before the `post_propose_account_service_with_metadata` interceptor. + """ + return response + + def post_propose_account_service_with_metadata(self, response: accountservices.AccountService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for propose_account_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountServicesService server but before it is returned to user code. + + We recommend only using this `post_propose_account_service_with_metadata` + interceptor in new development instead of the `post_propose_account_service` interceptor. + When both interceptors are used, this `post_propose_account_service_with_metadata` interceptor runs after the + `post_propose_account_service` interceptor. The (possibly modified) response returned by + `post_propose_account_service` will be passed to + `post_propose_account_service_with_metadata`. + """ + return response, metadata + + def pre_reject_account_service(self, request: accountservices.RejectAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.RejectAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for reject_account_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountServicesService server. + """ + return request, metadata + + +@dataclasses.dataclass +class AccountServicesServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountServicesServiceRestInterceptor + + +class AccountServicesServiceRestTransport(_BaseAccountServicesServiceRestTransport): + """REST backend synchronous transport for AccountServicesService. + + Service to support AccountService API. + + 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[AccountServicesServiceRestInterceptor] = 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 AccountServicesServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ApproveAccountService(_BaseAccountServicesServiceRestTransport._BaseApproveAccountService, AccountServicesServiceRestStub): + def __hash__(self): + return hash("AccountServicesServiceRestTransport.ApproveAccountService") + + @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: accountservices.ApproveAccountServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountservices.AccountService: + r"""Call the approve account service method over HTTP. + + Args: + request (~.accountservices.ApproveAccountServiceRequest): + The request object. Request to approve an account + service. + 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: + ~.accountservices.AccountService: + The ``AccountService`` message represents a specific + service that a provider account offers to a Merchant + Center account. + + ``AccountService`` defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an ``AccountService`` involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts or + rejects it. This handshake mechanism ensures mutual + consent before any access is granted. This mechanism + safeguards both parties by ensuring that access rights + are granted appropriately and that both the business and + provider are aware of the services enabled. In scenarios + where a user is an admin of both accounts, the approval + can happen automatically. + + The mutability of a service is also managed through + ``AccountService``. Some services might be immutable, + for example, if they were established through other + systems or APIs, and you cannot alter them through this + API. + + """ + + http_options = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_http_options() + + request, metadata = self._interceptor.pre_approve_account_service(request, metadata) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_transcoded_request(http_options, request) + + body = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.ApproveAccountService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "ApproveAccountService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountServicesServiceRestTransport._ApproveAccountService._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 = accountservices.AccountService() + pb_resp = accountservices.AccountService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_approve_account_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_approve_account_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountservices.AccountService.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.accounts_v1.AccountServicesServiceClient.approve_account_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "ApproveAccountService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAccountService(_BaseAccountServicesServiceRestTransport._BaseGetAccountService, AccountServicesServiceRestStub): + def __hash__(self): + return hash("AccountServicesServiceRestTransport.GetAccountService") + + @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: accountservices.GetAccountServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountservices.AccountService: + r"""Call the get account service method over HTTP. + + Args: + request (~.accountservices.GetAccountServiceRequest): + The request object. Request to get an account service. + 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: + ~.accountservices.AccountService: + The ``AccountService`` message represents a specific + service that a provider account offers to a Merchant + Center account. + + ``AccountService`` defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an ``AccountService`` involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts or + rejects it. This handshake mechanism ensures mutual + consent before any access is granted. This mechanism + safeguards both parties by ensuring that access rights + are granted appropriately and that both the business and + provider are aware of the services enabled. In scenarios + where a user is an admin of both accounts, the approval + can happen automatically. + + The mutability of a service is also managed through + ``AccountService``. Some services might be immutable, + for example, if they were established through other + systems or APIs, and you cannot alter them through this + API. + + """ + + http_options = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_http_options() + + request, metadata = self._interceptor.pre_get_account_service(request, metadata) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.GetAccountService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "GetAccountService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountServicesServiceRestTransport._GetAccountService._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 = accountservices.AccountService() + pb_resp = accountservices.AccountService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_account_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_account_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountservices.AccountService.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.accounts_v1.AccountServicesServiceClient.get_account_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "GetAccountService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAccountServices(_BaseAccountServicesServiceRestTransport._BaseListAccountServices, AccountServicesServiceRestStub): + def __hash__(self): + return hash("AccountServicesServiceRestTransport.ListAccountServices") + + @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: accountservices.ListAccountServicesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountservices.ListAccountServicesResponse: + r"""Call the list account services method over HTTP. + + Args: + request (~.accountservices.ListAccountServicesRequest): + The request object. Request to list account services. + 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: + ~.accountservices.ListAccountServicesResponse: + Response after trying to list account + services. + + """ + + http_options = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_http_options() + + request, metadata = self._interceptor.pre_list_account_services(request, metadata) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.ListAccountServices", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "ListAccountServices", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountServicesServiceRestTransport._ListAccountServices._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 = accountservices.ListAccountServicesResponse() + pb_resp = accountservices.ListAccountServicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_account_services(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_account_services_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountservices.ListAccountServicesResponse.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.accounts_v1.AccountServicesServiceClient.list_account_services", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "ListAccountServices", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ProposeAccountService(_BaseAccountServicesServiceRestTransport._BaseProposeAccountService, AccountServicesServiceRestStub): + def __hash__(self): + return hash("AccountServicesServiceRestTransport.ProposeAccountService") + + @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: accountservices.ProposeAccountServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountservices.AccountService: + r"""Call the propose account service method over HTTP. + + Args: + request (~.accountservices.ProposeAccountServiceRequest): + The request object. Request to propose an account + service. + 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: + ~.accountservices.AccountService: + The ``AccountService`` message represents a specific + service that a provider account offers to a Merchant + Center account. + + ``AccountService`` defines the permissions and + capabilities granted to the provider, allowing for + operations such as product management or campaign + management. + + The lifecycle of an ``AccountService`` involves a + proposal phase, where one party suggests the service, + and an approval phase, where the other party accepts or + rejects it. This handshake mechanism ensures mutual + consent before any access is granted. This mechanism + safeguards both parties by ensuring that access rights + are granted appropriately and that both the business and + provider are aware of the services enabled. In scenarios + where a user is an admin of both accounts, the approval + can happen automatically. + + The mutability of a service is also managed through + ``AccountService``. Some services might be immutable, + for example, if they were established through other + systems or APIs, and you cannot alter them through this + API. + + """ + + http_options = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_http_options() + + request, metadata = self._interceptor.pre_propose_account_service(request, metadata) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_transcoded_request(http_options, request) + + body = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.ProposeAccountService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "ProposeAccountService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountServicesServiceRestTransport._ProposeAccountService._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 = accountservices.AccountService() + pb_resp = accountservices.AccountService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_propose_account_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_propose_account_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountservices.AccountService.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.accounts_v1.AccountServicesServiceClient.propose_account_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "ProposeAccountService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RejectAccountService(_BaseAccountServicesServiceRestTransport._BaseRejectAccountService, AccountServicesServiceRestStub): + def __hash__(self): + return hash("AccountServicesServiceRestTransport.RejectAccountService") + + @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: accountservices.RejectAccountServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the reject account service method over HTTP. + + Args: + request (~.accountservices.RejectAccountServiceRequest): + The request object. Request to reject an account service. + 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 = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_http_options() + + request, metadata = self._interceptor.pre_reject_account_service(request, metadata) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_transcoded_request(http_options, request) + + body = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.RejectAccountService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "rpcName": "RejectAccountService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountServicesServiceRestTransport._RejectAccountService._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) + + @property + def approve_account_service(self) -> Callable[ + [accountservices.ApproveAccountServiceRequest], + accountservices.AccountService]: + # 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._ApproveAccountService(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_account_service(self) -> Callable[ + [accountservices.GetAccountServiceRequest], + accountservices.AccountService]: + # 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._GetAccountService(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_account_services(self) -> Callable[ + [accountservices.ListAccountServicesRequest], + accountservices.ListAccountServicesResponse]: + # 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._ListAccountServices(self._session, self._host, self._interceptor) # type: ignore + + @property + def propose_account_service(self) -> Callable[ + [accountservices.ProposeAccountServiceRequest], + accountservices.AccountService]: + # 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._ProposeAccountService(self._session, self._host, self._interceptor) # type: ignore + + @property + def reject_account_service(self) -> Callable[ + [accountservices.RejectAccountServiceRequest], + 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._RejectAccountService(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountServicesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py new file mode 100644 index 000000000000..8861b1a075e0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py @@ -0,0 +1,307 @@ +# -*- 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 AccountServicesServiceTransport, 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_accounts_v1.types import accountservices + + +class _BaseAccountServicesServiceRestTransport(AccountServicesServiceTransport): + """Base REST backend transport for AccountServicesService. + + 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 _BaseApproveAccountService: + 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': '/accounts/v1/{name=accounts/*/services/*}:approve', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountservices.ApproveAccountServiceRequest.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(_BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAccountService: + 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': '/accounts/v1/{name=accounts/*/services/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountservices.GetAccountServiceRequest.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(_BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAccountServices: + 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': '/accounts/v1/{parent=accounts/*}/services', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountservices.ListAccountServicesRequest.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(_BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseProposeAccountService: + 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': '/accounts/v1/{parent=accounts/*}/services:propose', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountservices.ProposeAccountServiceRequest.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(_BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRejectAccountService: + 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': '/accounts/v1/{name=accounts/*/services/*}:reject', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountservices.RejectAccountServiceRequest.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(_BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountServicesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py new file mode 100644 index 000000000000..5115ab24752a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_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 AccountsServiceClient +from .async_client import AccountsServiceAsyncClient + +__all__ = ( + 'AccountsServiceClient', + 'AccountsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py new file mode 100644 index 000000000000..137050836009 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py @@ -0,0 +1,947 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.accounts_service import pagers +from google.shopping.merchant_accounts_v1.types import accounts +from google.type import datetime_pb2 # type: ignore +from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport +from .client import AccountsServiceClient + +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 AccountsServiceAsyncClient: + """Service to support Accounts API.""" + + _client: AccountsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AccountsServiceClient.account_path) + parse_account_path = staticmethod(AccountsServiceClient.parse_account_path) + user_path = staticmethod(AccountsServiceClient.user_path) + parse_user_path = staticmethod(AccountsServiceClient.parse_user_path) + common_billing_account_path = staticmethod(AccountsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountsServiceClient.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: + AccountsServiceAsyncClient: The constructed client. + """ + return AccountsServiceClient.from_service_account_info.__func__(AccountsServiceAsyncClient, 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: + AccountsServiceAsyncClient: The constructed client. + """ + return AccountsServiceClient.from_service_account_file.__func__(AccountsServiceAsyncClient, 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 AccountsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountsServiceTransport: 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 = AccountsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the accounts 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,AccountsServiceTransport,Callable[..., AccountsServiceTransport]]]): + 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 AccountsServiceTransport 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 = AccountsServiceClient( + 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.accounts_v1.AccountsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "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.accounts.v1.AccountsService", + "credentialsType": None, + } + ) + + async def get_account(self, + request: Optional[Union[accounts.GetAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + .. 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_accounts_v1 + + async def sample_get_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetAccountRequest, dict]]): + The request object. Request message for the ``GetAccount`` method. + name (:class:`str`): + Required. The name of the account to retrieve. Format: + ``accounts/{account}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Account: + The Account message represents a business's account within Shopping + Ads. It's the primary entity for managing product + data, settings, and interactions with Google's + services and external providers. + + Accounts can operate as standalone entities or be + part of a advanced account structure. In an advanced + account setup the parent account manages multiple + sub-accounts. + + Establishing an account involves configuring + attributes like the account name, time zone, and + language preferences. + + The Account message is the parent entity for many + other resources, for example, AccountRelationship, + Homepage, BusinessInfo and so on. + + """ + # 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, accounts.GetAccountRequest): + request = accounts.GetAccountRequest(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.get_account] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_and_configure_account(self, + request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Creates a Merchant Center account with additional + configuration. Adds the user that makes the request as + an admin for the new 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_accounts_v1 + + async def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = await client.create_and_configure_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.CreateAndConfigureAccountRequest, dict]]): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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_accounts_v1.types.Account: + The Account message represents a business's account within Shopping + Ads. It's the primary entity for managing product + data, settings, and interactions with Google's + services and external providers. + + Accounts can operate as standalone entities or be + part of a advanced account structure. In an advanced + account setup the parent account manages multiple + sub-accounts. + + Establishing an account involves configuring + attributes like the account name, time zone, and + language preferences. + + The Account message is the parent entity for many + other resources, for example, AccountRelationship, + Homepage, BusinessInfo and so on. + + """ + # 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, accounts.CreateAndConfigureAccountRequest): + request = accounts.CreateAndConfigureAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_and_configure_account] + + # 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_account(self, + request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, + *, + name: 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 account regardless of its type: + standalone, advanced account or sub-account. Deleting an + advanced account leads to the deletion of all of its + sub-accounts. Executing this method requires admin access. The + deletion succeeds only if the account does not provide services + to any other account and has no processed offers. You can use + the ``force`` parameter to override this. + + .. 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_accounts_v1 + + async def sample_delete_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_account(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.DeleteAccountRequest, dict]]): + The request object. Request message for the ``DeleteAccount`` method. + name (:class:`str`): + Required. The name of the account to delete. Format: + ``accounts/{account}`` + + 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, accounts.DeleteAccountRequest): + request = accounts.DeleteAccountRequest(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_account] + + # 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 update_account(self, + request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, + *, + account: Optional[accounts.Account] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Updates an account regardless of its type: + standalone, advanced account or sub-account. Executing + this method requires admin access. + + .. 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_accounts_v1 + + async def sample_update_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = await client.update_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateAccountRequest, dict]]): + The request object. Request message for the ``UpdateAccount`` method. + account (:class:`google.shopping.merchant_accounts_v1.types.Account`): + Required. The new version of the + account. + + This corresponds to the ``account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``account_name`` + - ``adult_content`` + - ``language_code`` + - ``time_zone`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.Account: + The Account message represents a business's account within Shopping + Ads. It's the primary entity for managing product + data, settings, and interactions with Google's + services and external providers. + + Accounts can operate as standalone entities or be + part of a advanced account structure. In an advanced + account setup the parent account manages multiple + sub-accounts. + + Establishing an account involves configuring + attributes like the account name, time zone, and + language preferences. + + The Account message is the parent entity for many + other resources, for example, AccountRelationship, + Homepage, BusinessInfo and so on. + + """ + # 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 = [account, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.UpdateAccountRequest): + request = accounts.UpdateAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.name), + )), + ) + + # 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 list_accounts(self, + request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAccountsAsyncPager: + r"""Note: For the ``accounts.list`` method, quota and limits usage + are charged for each user, and not for the Merchant Center ID or + the advanced account ID. To list several sub-accounts, you + should use the ``accounts.listSubaccounts`` method, which is + more suitable for advanced accounts use case. + + .. 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_accounts_v1 + + async def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListAccountsRequest, dict]]): + The request object. Request message for the ``accounts.list`` 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_accounts_v1.services.accounts_service.pagers.ListAccountsAsyncPager: + Response message for the accounts.list method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, accounts.ListAccountsRequest): + request = accounts.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_accounts] + + # 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.ListAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sub_accounts(self, + request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, + *, + provider: 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.ListSubAccountsAsyncPager: + r"""List all sub-accounts for a given advanced account. This is a + convenience wrapper for the more powerful ``accounts.list`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + .. 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_accounts_v1 + + async def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListSubAccountsRequest, dict]]): + The request object. Request message for the ``ListSubAccounts`` method. + provider (:class:`str`): + Required. The aggregation service provider. Format: + ``accounts/{accountId}`` + + This corresponds to the ``provider`` 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_accounts_v1.services.accounts_service.pagers.ListSubAccountsAsyncPager: + Response message for the ListSubAccounts 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 = [provider] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.ListSubAccountsRequest): + request = accounts.ListSubAccountsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if provider is not None: + request.provider = provider + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_sub_accounts] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("provider", request.provider), + )), + ) + + # 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.ListSubAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AccountsServiceAsyncClient": + 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__ = ( + "AccountsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py new file mode 100644 index 000000000000..344dc5ed02d0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py @@ -0,0 +1,1313 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.accounts_service import pagers +from google.shopping.merchant_accounts_v1.types import accounts +from google.type import datetime_pb2 # type: ignore +from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountsServiceGrpcTransport +from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport +from .transports.rest import AccountsServiceRestTransport + + +class AccountsServiceClientMeta(type): + """Metaclass for the AccountsService 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[AccountsServiceTransport]] + _transport_registry["grpc"] = AccountsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountsServiceTransport]: + """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 AccountsServiceClient(metaclass=AccountsServiceClientMeta): + """Service to support Accounts API.""" + + @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: + AccountsServiceClient: 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: + AccountsServiceClient: 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) -> AccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(account: str,email: str,) -> str: + """Returns a fully-qualified user string.""" + return "accounts/{account}/users/{email}".format(account=account, email=email, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/users/(?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 = AccountsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountsServiceClient._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 = AccountsServiceClient._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, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the accounts 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,AccountsServiceTransport,Callable[..., AccountsServiceTransport]]]): + 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 AccountsServiceTransport 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 = AccountsServiceClient._read_environment_variables() + self._client_cert_source = AccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountsServiceClient._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, AccountsServiceTransport) + if transport_provided: + # transport is a AccountsServiceTransport 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(AccountsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountsServiceClient._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[AccountsServiceTransport], Callable[..., AccountsServiceTransport]] = ( + AccountsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountsServiceTransport], 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.accounts_v1.AccountsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "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.accounts.v1.AccountsService", + "credentialsType": None, + } + ) + + def get_account(self, + request: Optional[Union[accounts.GetAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + .. 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_accounts_v1 + + def sample_get_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetAccountRequest, dict]): + The request object. Request message for the ``GetAccount`` method. + name (str): + Required. The name of the account to retrieve. Format: + ``accounts/{account}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Account: + The Account message represents a business's account within Shopping + Ads. It's the primary entity for managing product + data, settings, and interactions with Google's + services and external providers. + + Accounts can operate as standalone entities or be + part of a advanced account structure. In an advanced + account setup the parent account manages multiple + sub-accounts. + + Establishing an account involves configuring + attributes like the account name, time zone, and + language preferences. + + The Account message is the parent entity for many + other resources, for example, AccountRelationship, + Homepage, BusinessInfo and so on. + + """ + # 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, accounts.GetAccountRequest): + request = accounts.GetAccountRequest(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.get_account] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_and_configure_account(self, + request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Creates a Merchant Center account with additional + configuration. Adds the user that makes the request as + an admin for the new 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_accounts_v1 + + def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = client.create_and_configure_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.CreateAndConfigureAccountRequest, dict]): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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_accounts_v1.types.Account: + The Account message represents a business's account within Shopping + Ads. It's the primary entity for managing product + data, settings, and interactions with Google's + services and external providers. + + Accounts can operate as standalone entities or be + part of a advanced account structure. In an advanced + account setup the parent account manages multiple + sub-accounts. + + Establishing an account involves configuring + attributes like the account name, time zone, and + language preferences. + + The Account message is the parent entity for many + other resources, for example, AccountRelationship, + Homepage, BusinessInfo and so on. + + """ + # 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, accounts.CreateAndConfigureAccountRequest): + request = accounts.CreateAndConfigureAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_and_configure_account] + + # 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_account(self, + request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, + *, + name: 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 account regardless of its type: + standalone, advanced account or sub-account. Deleting an + advanced account leads to the deletion of all of its + sub-accounts. Executing this method requires admin access. The + deletion succeeds only if the account does not provide services + to any other account and has no processed offers. You can use + the ``force`` parameter to override this. + + .. 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_accounts_v1 + + def sample_delete_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_account(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.DeleteAccountRequest, dict]): + The request object. Request message for the ``DeleteAccount`` method. + name (str): + Required. The name of the account to delete. Format: + ``accounts/{account}`` + + 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, accounts.DeleteAccountRequest): + request = accounts.DeleteAccountRequest(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_account] + + # 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 update_account(self, + request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, + *, + account: Optional[accounts.Account] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Updates an account regardless of its type: + standalone, advanced account or sub-account. Executing + this method requires admin access. + + .. 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_accounts_v1 + + def sample_update_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = client.update_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateAccountRequest, dict]): + The request object. Request message for the ``UpdateAccount`` method. + account (google.shopping.merchant_accounts_v1.types.Account): + Required. The new version of the + account. + + This corresponds to the ``account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``account_name`` + - ``adult_content`` + - ``language_code`` + - ``time_zone`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.Account: + The Account message represents a business's account within Shopping + Ads. It's the primary entity for managing product + data, settings, and interactions with Google's + services and external providers. + + Accounts can operate as standalone entities or be + part of a advanced account structure. In an advanced + account setup the parent account manages multiple + sub-accounts. + + Establishing an account involves configuring + attributes like the account name, time zone, and + language preferences. + + The Account message is the parent entity for many + other resources, for example, AccountRelationship, + Homepage, BusinessInfo and so on. + + """ + # 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 = [account, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.UpdateAccountRequest): + request = accounts.UpdateAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.name), + )), + ) + + # 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 list_accounts(self, + request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAccountsPager: + r"""Note: For the ``accounts.list`` method, quota and limits usage + are charged for each user, and not for the Merchant Center ID or + the advanced account ID. To list several sub-accounts, you + should use the ``accounts.listSubaccounts`` method, which is + more suitable for advanced accounts use case. + + .. 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_accounts_v1 + + def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListAccountsRequest, dict]): + The request object. Request message for the ``accounts.list`` 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_accounts_v1.services.accounts_service.pagers.ListAccountsPager: + Response message for the accounts.list method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, accounts.ListAccountsRequest): + request = accounts.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_accounts] + + # 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.ListAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sub_accounts(self, + request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, + *, + provider: 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.ListSubAccountsPager: + r"""List all sub-accounts for a given advanced account. This is a + convenience wrapper for the more powerful ``accounts.list`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + .. 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_accounts_v1 + + def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListSubAccountsRequest, dict]): + The request object. Request message for the ``ListSubAccounts`` method. + provider (str): + Required. The aggregation service provider. Format: + ``accounts/{accountId}`` + + This corresponds to the ``provider`` 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_accounts_v1.services.accounts_service.pagers.ListSubAccountsPager: + Response message for the ListSubAccounts 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 = [provider] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.ListSubAccountsRequest): + request = accounts.ListSubAccountsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if provider is not None: + request.provider = provider + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_sub_accounts] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("provider", request.provider), + )), + ) + + # 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.ListSubAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AccountsServiceClient": + 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__ = ( + "AccountsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py new file mode 100644 index 000000000000..b96de6c53897 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py @@ -0,0 +1,305 @@ +# -*- 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_accounts_v1.types import accounts + + +class ListAccountsPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountsResponse` + 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[..., accounts.ListAccountsResponse], + request: accounts.ListAccountsRequest, + response: accounts.ListAccountsResponse, + *, + 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_accounts_v1.types.ListAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountsResponse): + 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 = accounts.ListAccountsRequest(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[accounts.ListAccountsResponse]: + 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[accounts.Account]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountsAsyncPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListAccountsResponse` + 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[accounts.ListAccountsResponse]], + request: accounts.ListAccountsRequest, + response: accounts.ListAccountsResponse, + *, + 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_accounts_v1.types.ListAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListAccountsResponse): + 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 = accounts.ListAccountsRequest(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[accounts.ListAccountsResponse]: + 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[accounts.Account]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubAccountsPager: + """A pager for iterating through ``list_sub_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListSubAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSubAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListSubAccountsResponse` + 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[..., accounts.ListSubAccountsResponse], + request: accounts.ListSubAccountsRequest, + response: accounts.ListSubAccountsResponse, + *, + 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_accounts_v1.types.ListSubAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListSubAccountsResponse): + 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 = accounts.ListSubAccountsRequest(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[accounts.ListSubAccountsResponse]: + 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[accounts.Account]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubAccountsAsyncPager: + """A pager for iterating through ``list_sub_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListSubAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSubAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListSubAccountsResponse` + 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[accounts.ListSubAccountsResponse]], + request: accounts.ListSubAccountsRequest, + response: accounts.ListSubAccountsResponse, + *, + 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_accounts_v1.types.ListSubAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListSubAccountsResponse): + 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 = accounts.ListSubAccountsRequest(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[accounts.ListSubAccountsResponse]: + 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[accounts.Account]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst new file mode 100644 index 000000000000..feb9cc900a04 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountsServiceTransport` is the ABC for all transports. +- public child `AccountsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py new file mode 100644 index 000000000000..36cbcd559b5e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_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 AccountsServiceTransport +from .grpc import AccountsServiceGrpcTransport +from .grpc_asyncio import AccountsServiceGrpcAsyncIOTransport +from .rest import AccountsServiceRestTransport +from .rest import AccountsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountsServiceTransport]] +_transport_registry['grpc'] = AccountsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountsServiceRestTransport + +__all__ = ( + 'AccountsServiceTransport', + 'AccountsServiceGrpcTransport', + 'AccountsServiceGrpcAsyncIOTransport', + 'AccountsServiceRestTransport', + 'AccountsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py new file mode 100644 index 000000000000..2709aec9f8d0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py @@ -0,0 +1,230 @@ +# -*- 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_accounts_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_accounts_v1.types import accounts + +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 AccountsServiceTransport(abc.ABC): + """Abstract transport class for AccountsService.""" + + 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.get_account: gapic_v1.method.wrap_method( + self.get_account, + default_timeout=None, + client_info=client_info, + ), + self.create_and_configure_account: gapic_v1.method.wrap_method( + self.create_and_configure_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_account: gapic_v1.method.wrap_method( + self.delete_account, + default_timeout=None, + client_info=client_info, + ), + self.update_account: gapic_v1.method.wrap_method( + self.update_account, + default_timeout=None, + client_info=client_info, + ), + self.list_accounts: gapic_v1.method.wrap_method( + self.list_accounts, + default_timeout=None, + client_info=client_info, + ), + self.list_sub_accounts: gapic_v1.method.wrap_method( + self.list_sub_accounts, + 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 get_account(self) -> Callable[ + [accounts.GetAccountRequest], + Union[ + accounts.Account, + Awaitable[accounts.Account] + ]]: + raise NotImplementedError() + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + Union[ + accounts.Account, + Awaitable[accounts.Account] + ]]: + raise NotImplementedError() + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + Union[ + accounts.Account, + Awaitable[accounts.Account] + ]]: + raise NotImplementedError() + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + Union[ + accounts.ListAccountsResponse, + Awaitable[accounts.ListAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + Union[ + accounts.ListSubAccountsResponse, + Awaitable[accounts.ListSubAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py new file mode 100644 index 000000000000..47ccf95f96ad --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py @@ -0,0 +1,498 @@ +# -*- 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_accounts_v1.types import accounts +from .base import AccountsServiceTransport, 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.accounts.v1.AccountsService", + "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.accounts.v1.AccountsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountsServiceGrpcTransport(AccountsServiceTransport): + """gRPC backend transport for AccountsService. + + Service to support Accounts API. + + 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 get_account(self) -> Callable[ + [accounts.GetAccountRequest], + accounts.Account]: + r"""Return a callable for the get account method over gRPC. + + Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + Returns: + Callable[[~.GetAccountRequest], + ~.Account]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account' not in self._stubs: + self._stubs['get_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/GetAccount', + request_serializer=accounts.GetAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + accounts.Account]: + r"""Return a callable for the create and configure account method over gRPC. + + Creates a Merchant Center account with additional + configuration. Adds the user that makes the request as + an admin for the new account. + + Returns: + Callable[[~.CreateAndConfigureAccountRequest], + ~.Account]: + 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 'create_and_configure_account' not in self._stubs: + self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/CreateAndConfigureAccount', + request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['create_and_configure_account'] + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete account method over gRPC. + + Deletes the specified account regardless of its type: + standalone, advanced account or sub-account. Deleting an + advanced account leads to the deletion of all of its + sub-accounts. Executing this method requires admin access. The + deletion succeeds only if the account does not provide services + to any other account and has no processed offers. You can use + the ``force`` parameter to override this. + + Returns: + Callable[[~.DeleteAccountRequest], + ~.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_account' not in self._stubs: + self._stubs['delete_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/DeleteAccount', + request_serializer=accounts.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + accounts.Account]: + r"""Return a callable for the update account method over gRPC. + + Updates an account regardless of its type: + standalone, advanced account or sub-account. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateAccountRequest], + ~.Account]: + 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 'update_account' not in self._stubs: + self._stubs['update_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/UpdateAccount', + request_serializer=accounts.UpdateAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + accounts.ListAccountsResponse]: + r"""Return a callable for the list accounts method over gRPC. + + Note: For the ``accounts.list`` method, quota and limits usage + are charged for each user, and not for the Merchant Center ID or + the advanced account ID. To list several sub-accounts, you + should use the ``accounts.listSubaccounts`` method, which is + more suitable for advanced accounts use case. + + Returns: + Callable[[~.ListAccountsRequest], + ~.ListAccountsResponse]: + 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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/ListAccounts', + request_serializer=accounts.ListAccountsRequest.serialize, + response_deserializer=accounts.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + accounts.ListSubAccountsResponse]: + r"""Return a callable for the list sub accounts method over gRPC. + + List all sub-accounts for a given advanced account. This is a + convenience wrapper for the more powerful ``accounts.list`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + Returns: + Callable[[~.ListSubAccountsRequest], + ~.ListSubAccountsResponse]: + 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_sub_accounts' not in self._stubs: + self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/ListSubAccounts', + request_serializer=accounts.ListSubAccountsRequest.serialize, + response_deserializer=accounts.ListSubAccountsResponse.deserialize, + ) + return self._stubs['list_sub_accounts'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e51bdf24f15a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py @@ -0,0 +1,544 @@ +# -*- 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_accounts_v1.types import accounts +from .base import AccountsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountsServiceGrpcTransport + +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.accounts.v1.AccountsService", + "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.accounts.v1.AccountsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountsServiceGrpcAsyncIOTransport(AccountsServiceTransport): + """gRPC AsyncIO backend transport for AccountsService. + + Service to support Accounts API. + + 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 get_account(self) -> Callable[ + [accounts.GetAccountRequest], + Awaitable[accounts.Account]]: + r"""Return a callable for the get account method over gRPC. + + Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + Returns: + Callable[[~.GetAccountRequest], + Awaitable[~.Account]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account' not in self._stubs: + self._stubs['get_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/GetAccount', + request_serializer=accounts.GetAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + Awaitable[accounts.Account]]: + r"""Return a callable for the create and configure account method over gRPC. + + Creates a Merchant Center account with additional + configuration. Adds the user that makes the request as + an admin for the new account. + + Returns: + Callable[[~.CreateAndConfigureAccountRequest], + Awaitable[~.Account]]: + 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 'create_and_configure_account' not in self._stubs: + self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/CreateAndConfigureAccount', + request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['create_and_configure_account'] + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete account method over gRPC. + + Deletes the specified account regardless of its type: + standalone, advanced account or sub-account. Deleting an + advanced account leads to the deletion of all of its + sub-accounts. Executing this method requires admin access. The + deletion succeeds only if the account does not provide services + to any other account and has no processed offers. You can use + the ``force`` parameter to override this. + + Returns: + Callable[[~.DeleteAccountRequest], + 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_account' not in self._stubs: + self._stubs['delete_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/DeleteAccount', + request_serializer=accounts.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + Awaitable[accounts.Account]]: + r"""Return a callable for the update account method over gRPC. + + Updates an account regardless of its type: + standalone, advanced account or sub-account. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateAccountRequest], + Awaitable[~.Account]]: + 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 'update_account' not in self._stubs: + self._stubs['update_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/UpdateAccount', + request_serializer=accounts.UpdateAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + Awaitable[accounts.ListAccountsResponse]]: + r"""Return a callable for the list accounts method over gRPC. + + Note: For the ``accounts.list`` method, quota and limits usage + are charged for each user, and not for the Merchant Center ID or + the advanced account ID. To list several sub-accounts, you + should use the ``accounts.listSubaccounts`` method, which is + more suitable for advanced accounts use case. + + Returns: + Callable[[~.ListAccountsRequest], + Awaitable[~.ListAccountsResponse]]: + 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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/ListAccounts', + request_serializer=accounts.ListAccountsRequest.serialize, + response_deserializer=accounts.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + Awaitable[accounts.ListSubAccountsResponse]]: + r"""Return a callable for the list sub accounts method over gRPC. + + List all sub-accounts for a given advanced account. This is a + convenience wrapper for the more powerful ``accounts.list`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + Returns: + Callable[[~.ListSubAccountsRequest], + Awaitable[~.ListSubAccountsResponse]]: + 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_sub_accounts' not in self._stubs: + self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AccountsService/ListSubAccounts', + request_serializer=accounts.ListSubAccountsRequest.serialize, + response_deserializer=accounts.ListSubAccountsResponse.deserialize, + ) + return self._stubs['list_sub_accounts'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account: self._wrap_method( + self.get_account, + default_timeout=None, + client_info=client_info, + ), + self.create_and_configure_account: self._wrap_method( + self.create_and_configure_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_account: self._wrap_method( + self.delete_account, + default_timeout=None, + client_info=client_info, + ), + self.update_account: self._wrap_method( + self.update_account, + default_timeout=None, + client_info=client_info, + ), + self.list_accounts: self._wrap_method( + self.list_accounts, + default_timeout=None, + client_info=client_info, + ), + self.list_sub_accounts: self._wrap_method( + self.list_sub_accounts, + 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__ = ( + 'AccountsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py new file mode 100644 index 000000000000..16d7ea6a4261 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py @@ -0,0 +1,1197 @@ +# -*- 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_accounts_v1.types import accounts + + +from .rest_base import _BaseAccountsServiceRestTransport +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 AccountsServiceRestInterceptor: + """Interceptor for AccountsService. + + 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 AccountsServiceRestTransport. + + .. code-block:: python + class MyCustomAccountsServiceInterceptor(AccountsServiceRestInterceptor): + def pre_create_and_configure_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_and_configure_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sub_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sub_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_account(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AccountsServiceRestTransport(interceptor=MyCustomAccountsServiceInterceptor()) + client = AccountsServiceClient(transport=transport) + + + """ + def pre_create_and_configure_account(self, request: accounts.CreateAndConfigureAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_and_configure_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_create_and_configure_account(self, response: accounts.Account) -> accounts.Account: + """Post-rpc interceptor for create_and_configure_account + + DEPRECATED. Please use the `post_create_and_configure_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_create_and_configure_account` interceptor runs + before the `post_create_and_configure_account_with_metadata` interceptor. + """ + return response + + def post_create_and_configure_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_and_configure_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_create_and_configure_account_with_metadata` + interceptor in new development instead of the `post_create_and_configure_account` interceptor. + When both interceptors are used, this `post_create_and_configure_account_with_metadata` interceptor runs after the + `post_create_and_configure_account` interceptor. The (possibly modified) response returned by + `post_create_and_configure_account` will be passed to + `post_create_and_configure_account_with_metadata`. + """ + return response, metadata + + def pre_delete_account(self, request: accounts.DeleteAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def pre_get_account(self, request: accounts.GetAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_get_account(self, response: accounts.Account) -> accounts.Account: + """Post-rpc interceptor for get_account + + DEPRECATED. Please use the `post_get_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_get_account` interceptor runs + before the `post_get_account_with_metadata` interceptor. + """ + return response + + def post_get_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_get_account_with_metadata` + interceptor in new development instead of the `post_get_account` interceptor. + When both interceptors are used, this `post_get_account_with_metadata` interceptor runs after the + `post_get_account` interceptor. The (possibly modified) response returned by + `post_get_account` will be passed to + `post_get_account_with_metadata`. + """ + return response, metadata + + def pre_list_accounts(self, request: accounts.ListAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_list_accounts(self, response: accounts.ListAccountsResponse) -> accounts.ListAccountsResponse: + """Post-rpc interceptor for list_accounts + + DEPRECATED. Please use the `post_list_accounts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_list_accounts` interceptor runs + before the `post_list_accounts_with_metadata` interceptor. + """ + return response + + def post_list_accounts_with_metadata(self, response: accounts.ListAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_accounts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_list_accounts_with_metadata` + interceptor in new development instead of the `post_list_accounts` interceptor. + When both interceptors are used, this `post_list_accounts_with_metadata` interceptor runs after the + `post_list_accounts` interceptor. The (possibly modified) response returned by + `post_list_accounts` will be passed to + `post_list_accounts_with_metadata`. + """ + return response, metadata + + def pre_list_sub_accounts(self, request: accounts.ListSubAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_sub_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_list_sub_accounts(self, response: accounts.ListSubAccountsResponse) -> accounts.ListSubAccountsResponse: + """Post-rpc interceptor for list_sub_accounts + + DEPRECATED. Please use the `post_list_sub_accounts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_list_sub_accounts` interceptor runs + before the `post_list_sub_accounts_with_metadata` interceptor. + """ + return response + + def post_list_sub_accounts_with_metadata(self, response: accounts.ListSubAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_sub_accounts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_list_sub_accounts_with_metadata` + interceptor in new development instead of the `post_list_sub_accounts` interceptor. + When both interceptors are used, this `post_list_sub_accounts_with_metadata` interceptor runs after the + `post_list_sub_accounts` interceptor. The (possibly modified) response returned by + `post_list_sub_accounts` will be passed to + `post_list_sub_accounts_with_metadata`. + """ + return response, metadata + + def pre_update_account(self, request: accounts.UpdateAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_update_account(self, response: accounts.Account) -> accounts.Account: + """Post-rpc interceptor for update_account + + DEPRECATED. Please use the `post_update_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_update_account` interceptor runs + before the `post_update_account_with_metadata` interceptor. + """ + return response + + def post_update_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_update_account_with_metadata` + interceptor in new development instead of the `post_update_account` interceptor. + When both interceptors are used, this `post_update_account_with_metadata` interceptor runs after the + `post_update_account` interceptor. The (possibly modified) response returned by + `post_update_account` will be passed to + `post_update_account_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AccountsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountsServiceRestInterceptor + + +class AccountsServiceRestTransport(_BaseAccountsServiceRestTransport): + """REST backend synchronous transport for AccountsService. + + Service to support Accounts API. + + 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[AccountsServiceRestInterceptor] = 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 AccountsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateAndConfigureAccount(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.CreateAndConfigureAccount") + + @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: accounts.CreateAndConfigureAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.Account: + r"""Call the create and configure + account method over HTTP. + + Args: + request (~.accounts.CreateAndConfigureAccountRequest): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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: + ~.accounts.Account: + The ``Account`` message represents a business's account + within Shopping Ads. It's the primary entity for + managing product data, settings, and interactions with + Google's services and external providers. + + Accounts can operate as standalone entities or be part + of a advanced account structure. In an advanced account + setup the parent account manages multiple sub-accounts. + + Establishing an account involves configuring attributes + like the account name, time zone, and language + preferences. + + The ``Account`` message is the parent entity for many + other resources, for example, ``AccountRelationship``, + ``Homepage``, ``BusinessInfo`` and so on. + + """ + + http_options = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_http_options() + + request, metadata = self._interceptor.pre_create_and_configure_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_transcoded_request(http_options, request) + + body = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.CreateAndConfigureAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "CreateAndConfigureAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._CreateAndConfigureAccount._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 = accounts.Account() + pb_resp = accounts.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_and_configure_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_and_configure_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.Account.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.accounts_v1.AccountsServiceClient.create_and_configure_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "CreateAndConfigureAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAccount(_BaseAccountsServiceRestTransport._BaseDeleteAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.DeleteAccount") + + @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: accounts.DeleteAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete account method over HTTP. + + Args: + request (~.accounts.DeleteAccountRequest): + The request object. Request message for the ``DeleteAccount`` 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 = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_http_options() + + request, metadata = self._interceptor.pre_delete_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.DeleteAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "DeleteAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._DeleteAccount._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 _GetAccount(_BaseAccountsServiceRestTransport._BaseGetAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.GetAccount") + + @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: accounts.GetAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.Account: + r"""Call the get account method over HTTP. + + Args: + request (~.accounts.GetAccountRequest): + The request object. Request message for the ``GetAccount`` 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: + ~.accounts.Account: + The ``Account`` message represents a business's account + within Shopping Ads. It's the primary entity for + managing product data, settings, and interactions with + Google's services and external providers. + + Accounts can operate as standalone entities or be part + of a advanced account structure. In an advanced account + setup the parent account manages multiple sub-accounts. + + Establishing an account involves configuring attributes + like the account name, time zone, and language + preferences. + + The ``Account`` message is the parent entity for many + other resources, for example, ``AccountRelationship``, + ``Homepage``, ``BusinessInfo`` and so on. + + """ + + http_options = _BaseAccountsServiceRestTransport._BaseGetAccount._get_http_options() + + request, metadata = self._interceptor.pre_get_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseGetAccount._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseGetAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.GetAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "GetAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._GetAccount._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 = accounts.Account() + pb_resp = accounts.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.Account.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.accounts_v1.AccountsServiceClient.get_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "GetAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAccounts(_BaseAccountsServiceRestTransport._BaseListAccounts, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.ListAccounts") + + @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: accounts.ListAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.ListAccountsResponse: + r"""Call the list accounts method over HTTP. + + Args: + request (~.accounts.ListAccountsRequest): + The request object. Request message for the ``accounts.list`` 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: + ~.accounts.ListAccountsResponse: + Response message for the ``accounts.list`` method. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseListAccounts._get_http_options() + + request, metadata = self._interceptor.pre_list_accounts(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseListAccounts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseListAccounts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.ListAccounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "ListAccounts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._ListAccounts._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 = accounts.ListAccountsResponse() + pb_resp = accounts.ListAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_accounts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_accounts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.ListAccountsResponse.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.accounts_v1.AccountsServiceClient.list_accounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "ListAccounts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSubAccounts(_BaseAccountsServiceRestTransport._BaseListSubAccounts, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.ListSubAccounts") + + @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: accounts.ListSubAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.ListSubAccountsResponse: + r"""Call the list sub accounts method over HTTP. + + Args: + request (~.accounts.ListSubAccountsRequest): + The request object. Request message for the ``ListSubAccounts`` 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: + ~.accounts.ListSubAccountsResponse: + Response message for the ``ListSubAccounts`` method. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_http_options() + + request, metadata = self._interceptor.pre_list_sub_accounts(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.ListSubAccounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "ListSubAccounts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._ListSubAccounts._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 = accounts.ListSubAccountsResponse() + pb_resp = accounts.ListSubAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sub_accounts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sub_accounts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.ListSubAccountsResponse.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.accounts_v1.AccountsServiceClient.list_sub_accounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "ListSubAccounts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAccount(_BaseAccountsServiceRestTransport._BaseUpdateAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.UpdateAccount") + + @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: accounts.UpdateAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.Account: + r"""Call the update account method over HTTP. + + Args: + request (~.accounts.UpdateAccountRequest): + The request object. Request message for the ``UpdateAccount`` 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: + ~.accounts.Account: + The ``Account`` message represents a business's account + within Shopping Ads. It's the primary entity for + managing product data, settings, and interactions with + Google's services and external providers. + + Accounts can operate as standalone entities or be part + of a advanced account structure. In an advanced account + setup the parent account manages multiple sub-accounts. + + Establishing an account involves configuring attributes + like the account name, time zone, and language + preferences. + + The ``Account`` message is the parent entity for many + other resources, for example, ``AccountRelationship``, + ``Homepage``, ``BusinessInfo`` and so on. + + """ + + http_options = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_http_options() + + request, metadata = self._interceptor.pre_update_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_transcoded_request(http_options, request) + + body = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.UpdateAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "UpdateAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._UpdateAccount._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 = accounts.Account() + pb_resp = accounts.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.Account.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.accounts_v1.AccountsServiceClient.update_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", + "rpcName": "UpdateAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + accounts.Account]: + # 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._CreateAndConfigureAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + 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._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_account(self) -> Callable[ + [accounts.GetAccountRequest], + accounts.Account]: + # 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._GetAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + accounts.ListAccountsResponse]: + # 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._ListAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + accounts.ListSubAccountsResponse]: + # 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._ListSubAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + accounts.Account]: + # 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._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py new file mode 100644 index 000000000000..cd4f88fdfc5d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py @@ -0,0 +1,326 @@ +# -*- 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 AccountsServiceTransport, 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_accounts_v1.types import accounts + + +class _BaseAccountsServiceRestTransport(AccountsServiceTransport): + """Base REST backend transport for AccountsService. + + 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 _BaseCreateAndConfigureAccount: + 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': '/accounts/v1/accounts:createAndConfigure', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.CreateAndConfigureAccountRequest.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(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAccount: + 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': '/accounts/v1/{name=accounts/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.DeleteAccountRequest.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(_BaseAccountsServiceRestTransport._BaseDeleteAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAccount: + 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': '/accounts/v1/{name=accounts/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.GetAccountRequest.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(_BaseAccountsServiceRestTransport._BaseGetAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAccounts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/accounts/v1/accounts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.ListAccountsRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSubAccounts: + 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': '/accounts/v1/{provider=accounts/*}:listSubaccounts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.ListSubAccountsRequest.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(_BaseAccountsServiceRestTransport._BaseListSubAccounts._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAccount: + 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': 'patch', + 'uri': '/accounts/v1/{account.name=accounts/*}', + 'body': 'account', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.UpdateAccountRequest.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(_BaseAccountsServiceRestTransport._BaseUpdateAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py new file mode 100644 index 000000000000..9d2f0554ddd6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_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 AutofeedSettingsServiceClient +from .async_client import AutofeedSettingsServiceAsyncClient + +__all__ = ( + 'AutofeedSettingsServiceClient', + 'AutofeedSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py new file mode 100644 index 000000000000..1a2a99f47bcc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py @@ -0,0 +1,493 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import autofeedsettings +from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport +from .client import AutofeedSettingsServiceClient + +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 AutofeedSettingsServiceAsyncClient: + """Service to support + `autofeed `__ + setting. + """ + + _client: AutofeedSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + + autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.autofeed_settings_path) + parse_autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.parse_autofeed_settings_path) + common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AutofeedSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AutofeedSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AutofeedSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AutofeedSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AutofeedSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AutofeedSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AutofeedSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AutofeedSettingsServiceClient.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: + AutofeedSettingsServiceAsyncClient: The constructed client. + """ + return AutofeedSettingsServiceClient.from_service_account_info.__func__(AutofeedSettingsServiceAsyncClient, 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: + AutofeedSettingsServiceAsyncClient: The constructed client. + """ + return AutofeedSettingsServiceClient.from_service_account_file.__func__(AutofeedSettingsServiceAsyncClient, 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 AutofeedSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AutofeedSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutofeedSettingsServiceTransport: 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 = AutofeedSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autofeed settings 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,AutofeedSettingsServiceTransport,Callable[..., AutofeedSettingsServiceTransport]]]): + 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 AutofeedSettingsServiceTransport 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 = AutofeedSettingsServiceClient( + 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.accounts_v1.AutofeedSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "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.accounts.v1.AutofeedSettingsService", + "credentialsType": None, + } + ) + + async def get_autofeed_settings(self, + request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Retrieves the autofeed settings of an 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_accounts_v1 + + async def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetAutofeedSettingsRequest, dict]]): + The request object. Request message for the ``GetAutofeedSettings`` method. + name (:class:`str`): + Required. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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, autofeedsettings.GetAutofeedSettingsRequest): + request = autofeedsettings.GetAutofeedSettingsRequest(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.get_autofeed_settings] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_autofeed_settings(self, + request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, + *, + autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Updates the autofeed settings of an 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_accounts_v1 + + async def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = await client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateAutofeedSettingsRequest, dict]]): + The request object. Request message for the ``UpdateAutofeedSettings`` + method. + autofeed_settings (:class:`google.shopping.merchant_accounts_v1.types.AutofeedSettings`): + Required. The new version of the + autofeed setting. + + This corresponds to the ``autofeed_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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 = [autofeed_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, autofeedsettings.UpdateAutofeedSettingsRequest): + request = autofeedsettings.UpdateAutofeedSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if autofeed_settings is not None: + request.autofeed_settings = autofeed_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_autofeed_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("autofeed_settings.name", request.autofeed_settings.name), + )), + ) + + # 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 __aenter__(self) -> "AutofeedSettingsServiceAsyncClient": + 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__ = ( + "AutofeedSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py new file mode 100644 index 000000000000..afea1b1c7e72 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py @@ -0,0 +1,852 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import autofeedsettings +from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AutofeedSettingsServiceGrpcTransport +from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport +from .transports.rest import AutofeedSettingsServiceRestTransport + + +class AutofeedSettingsServiceClientMeta(type): + """Metaclass for the AutofeedSettingsService 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[AutofeedSettingsServiceTransport]] + _transport_registry["grpc"] = AutofeedSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AutofeedSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AutofeedSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AutofeedSettingsServiceTransport]: + """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 AutofeedSettingsServiceClient(metaclass=AutofeedSettingsServiceClientMeta): + """Service to support + `autofeed `__ + setting. + """ + + @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: + AutofeedSettingsServiceClient: 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: + AutofeedSettingsServiceClient: 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) -> AutofeedSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutofeedSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def autofeed_settings_path(account: str,) -> str: + """Returns a fully-qualified autofeed_settings string.""" + return "accounts/{account}/autofeedSettings".format(account=account, ) + + @staticmethod + def parse_autofeed_settings_path(path: str) -> Dict[str,str]: + """Parses a autofeed_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/autofeedSettings$", 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 = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient._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, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autofeed settings 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,AutofeedSettingsServiceTransport,Callable[..., AutofeedSettingsServiceTransport]]]): + 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 AutofeedSettingsServiceTransport 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 = AutofeedSettingsServiceClient._read_environment_variables() + self._client_cert_source = AutofeedSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AutofeedSettingsServiceClient._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, AutofeedSettingsServiceTransport) + if transport_provided: + # transport is a AutofeedSettingsServiceTransport 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(AutofeedSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AutofeedSettingsServiceClient._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[AutofeedSettingsServiceTransport], Callable[..., AutofeedSettingsServiceTransport]] = ( + AutofeedSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AutofeedSettingsServiceTransport], 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.accounts_v1.AutofeedSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "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.accounts.v1.AutofeedSettingsService", + "credentialsType": None, + } + ) + + def get_autofeed_settings(self, + request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Retrieves the autofeed settings of an 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_accounts_v1 + + def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetAutofeedSettingsRequest, dict]): + The request object. Request message for the ``GetAutofeedSettings`` method. + name (str): + Required. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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, autofeedsettings.GetAutofeedSettingsRequest): + request = autofeedsettings.GetAutofeedSettingsRequest(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.get_autofeed_settings] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_autofeed_settings(self, + request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, + *, + autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Updates the autofeed settings of an 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_accounts_v1 + + def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateAutofeedSettingsRequest, dict]): + The request object. Request message for the ``UpdateAutofeedSettings`` + method. + autofeed_settings (google.shopping.merchant_accounts_v1.types.AutofeedSettings): + Required. The new version of the + autofeed setting. + + This corresponds to the ``autofeed_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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 = [autofeed_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, autofeedsettings.UpdateAutofeedSettingsRequest): + request = autofeedsettings.UpdateAutofeedSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if autofeed_settings is not None: + request.autofeed_settings = autofeed_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_autofeed_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("autofeed_settings.name", request.autofeed_settings.name), + )), + ) + + # 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 __enter__(self) -> "AutofeedSettingsServiceClient": + 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__ = ( + "AutofeedSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst new file mode 100644 index 000000000000..54f64d66d215 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AutofeedSettingsServiceTransport` is the ABC for all transports. +- public child `AutofeedSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AutofeedSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAutofeedSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AutofeedSettingsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py new file mode 100644 index 000000000000..c2ddd49ce02d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_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 AutofeedSettingsServiceTransport +from .grpc import AutofeedSettingsServiceGrpcTransport +from .grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport +from .rest import AutofeedSettingsServiceRestTransport +from .rest import AutofeedSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AutofeedSettingsServiceTransport]] +_transport_registry['grpc'] = AutofeedSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AutofeedSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AutofeedSettingsServiceRestTransport + +__all__ = ( + 'AutofeedSettingsServiceTransport', + 'AutofeedSettingsServiceGrpcTransport', + 'AutofeedSettingsServiceGrpcAsyncIOTransport', + 'AutofeedSettingsServiceRestTransport', + 'AutofeedSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py new file mode 100644 index 000000000000..80bd06ae78d1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import autofeedsettings + +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 AutofeedSettingsServiceTransport(abc.ABC): + """Abstract transport class for AutofeedSettingsService.""" + + 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.get_autofeed_settings: gapic_v1.method.wrap_method( + self.get_autofeed_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_autofeed_settings: gapic_v1.method.wrap_method( + self.update_autofeed_settings, + 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 get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + Union[ + autofeedsettings.AutofeedSettings, + Awaitable[autofeedsettings.AutofeedSettings] + ]]: + raise NotImplementedError() + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + Union[ + autofeedsettings.AutofeedSettings, + Awaitable[autofeedsettings.AutofeedSettings] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AutofeedSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py new file mode 100644 index 000000000000..953f936aba64 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- 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.shopping.merchant_accounts_v1.types import autofeedsettings +from .base import AutofeedSettingsServiceTransport, 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.accounts.v1.AutofeedSettingsService", + "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.accounts.v1.AutofeedSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutofeedSettingsServiceGrpcTransport(AutofeedSettingsServiceTransport): + """gRPC backend transport for AutofeedSettingsService. + + Service to support + `autofeed `__ + setting. + + 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 get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + r"""Return a callable for the get autofeed settings method over gRPC. + + Retrieves the autofeed settings of an account. + + Returns: + Callable[[~.GetAutofeedSettingsRequest], + ~.AutofeedSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_autofeed_settings' not in self._stubs: + self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/GetAutofeedSettings', + request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['get_autofeed_settings'] + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + r"""Return a callable for the update autofeed settings method over gRPC. + + Updates the autofeed settings of an account. + + Returns: + Callable[[~.UpdateAutofeedSettingsRequest], + ~.AutofeedSettings]: + 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 'update_autofeed_settings' not in self._stubs: + self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/UpdateAutofeedSettings', + request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['update_autofeed_settings'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AutofeedSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..79e80efb6ecc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,400 @@ +# -*- 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.shopping.merchant_accounts_v1.types import autofeedsettings +from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AutofeedSettingsServiceGrpcTransport + +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.accounts.v1.AutofeedSettingsService", + "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.accounts.v1.AutofeedSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutofeedSettingsServiceGrpcAsyncIOTransport(AutofeedSettingsServiceTransport): + """gRPC AsyncIO backend transport for AutofeedSettingsService. + + Service to support + `autofeed `__ + setting. + + 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 get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + Awaitable[autofeedsettings.AutofeedSettings]]: + r"""Return a callable for the get autofeed settings method over gRPC. + + Retrieves the autofeed settings of an account. + + Returns: + Callable[[~.GetAutofeedSettingsRequest], + Awaitable[~.AutofeedSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_autofeed_settings' not in self._stubs: + self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/GetAutofeedSettings', + request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['get_autofeed_settings'] + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + Awaitable[autofeedsettings.AutofeedSettings]]: + r"""Return a callable for the update autofeed settings method over gRPC. + + Updates the autofeed settings of an account. + + Returns: + Callable[[~.UpdateAutofeedSettingsRequest], + Awaitable[~.AutofeedSettings]]: + 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 'update_autofeed_settings' not in self._stubs: + self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/UpdateAutofeedSettings', + request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['update_autofeed_settings'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_autofeed_settings: self._wrap_method( + self.get_autofeed_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_autofeed_settings: self._wrap_method( + self.update_autofeed_settings, + 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__ = ( + 'AutofeedSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py new file mode 100644 index 000000000000..0ac0ad13768c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py @@ -0,0 +1,534 @@ +# -*- 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.shopping.merchant_accounts_v1.types import autofeedsettings + + +from .rest_base import _BaseAutofeedSettingsServiceRestTransport +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 AutofeedSettingsServiceRestInterceptor: + """Interceptor for AutofeedSettingsService. + + 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 AutofeedSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomAutofeedSettingsServiceInterceptor(AutofeedSettingsServiceRestInterceptor): + def pre_get_autofeed_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_autofeed_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_autofeed_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_autofeed_settings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AutofeedSettingsServiceRestTransport(interceptor=MyCustomAutofeedSettingsServiceInterceptor()) + client = AutofeedSettingsServiceClient(transport=transport) + + + """ + def pre_get_autofeed_settings(self, request: autofeedsettings.GetAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_autofeed_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutofeedSettingsService server. + """ + return request, metadata + + def post_get_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: + """Post-rpc interceptor for get_autofeed_settings + + DEPRECATED. Please use the `post_get_autofeed_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutofeedSettingsService server but before + it is returned to user code. This `post_get_autofeed_settings` interceptor runs + before the `post_get_autofeed_settings_with_metadata` interceptor. + """ + return response + + def post_get_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_autofeed_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutofeedSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_autofeed_settings_with_metadata` + interceptor in new development instead of the `post_get_autofeed_settings` interceptor. + When both interceptors are used, this `post_get_autofeed_settings_with_metadata` interceptor runs after the + `post_get_autofeed_settings` interceptor. The (possibly modified) response returned by + `post_get_autofeed_settings` will be passed to + `post_get_autofeed_settings_with_metadata`. + """ + return response, metadata + + def pre_update_autofeed_settings(self, request: autofeedsettings.UpdateAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_autofeed_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutofeedSettingsService server. + """ + return request, metadata + + def post_update_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: + """Post-rpc interceptor for update_autofeed_settings + + DEPRECATED. Please use the `post_update_autofeed_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutofeedSettingsService server but before + it is returned to user code. This `post_update_autofeed_settings` interceptor runs + before the `post_update_autofeed_settings_with_metadata` interceptor. + """ + return response + + def post_update_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_autofeed_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutofeedSettingsService server but before it is returned to user code. + + We recommend only using this `post_update_autofeed_settings_with_metadata` + interceptor in new development instead of the `post_update_autofeed_settings` interceptor. + When both interceptors are used, this `post_update_autofeed_settings_with_metadata` interceptor runs after the + `post_update_autofeed_settings` interceptor. The (possibly modified) response returned by + `post_update_autofeed_settings` will be passed to + `post_update_autofeed_settings_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AutofeedSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutofeedSettingsServiceRestInterceptor + + +class AutofeedSettingsServiceRestTransport(_BaseAutofeedSettingsServiceRestTransport): + """REST backend synchronous transport for AutofeedSettingsService. + + Service to support + `autofeed `__ + setting. + + 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[AutofeedSettingsServiceRestInterceptor] = 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 AutofeedSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings, AutofeedSettingsServiceRestStub): + def __hash__(self): + return hash("AutofeedSettingsServiceRestTransport.GetAutofeedSettings") + + @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: autofeedsettings.GetAutofeedSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> autofeedsettings.AutofeedSettings: + r"""Call the get autofeed settings method over HTTP. + + Args: + request (~.autofeedsettings.GetAutofeedSettingsRequest): + The request object. Request message for the ``GetAutofeedSettings`` 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: + ~.autofeedsettings.AutofeedSettings: + Collection of information related to the + `autofeed `__ + settings. + + """ + + http_options = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_http_options() + + request, metadata = self._interceptor.pre_get_autofeed_settings(request, metadata) + transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutofeedSettingsServiceClient.GetAutofeedSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "rpcName": "GetAutofeedSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutofeedSettingsServiceRestTransport._GetAutofeedSettings._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 = autofeedsettings.AutofeedSettings() + pb_resp = autofeedsettings.AutofeedSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_autofeed_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_autofeed_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1.AutofeedSettingsServiceClient.get_autofeed_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "rpcName": "GetAutofeedSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings, AutofeedSettingsServiceRestStub): + def __hash__(self): + return hash("AutofeedSettingsServiceRestTransport.UpdateAutofeedSettings") + + @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: autofeedsettings.UpdateAutofeedSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> autofeedsettings.AutofeedSettings: + r"""Call the update autofeed settings method over HTTP. + + Args: + request (~.autofeedsettings.UpdateAutofeedSettingsRequest): + The request object. Request message for the ``UpdateAutofeedSettings`` + 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: + ~.autofeedsettings.AutofeedSettings: + Collection of information related to the + `autofeed `__ + settings. + + """ + + http_options = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_http_options() + + request, metadata = self._interceptor.pre_update_autofeed_settings(request, metadata) + transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_transcoded_request(http_options, request) + + body = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutofeedSettingsServiceClient.UpdateAutofeedSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "rpcName": "UpdateAutofeedSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutofeedSettingsServiceRestTransport._UpdateAutofeedSettings._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 = autofeedsettings.AutofeedSettings() + pb_resp = autofeedsettings.AutofeedSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_autofeed_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_autofeed_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1.AutofeedSettingsServiceClient.update_autofeed_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "rpcName": "UpdateAutofeedSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + # 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._GetAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + # 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._UpdateAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AutofeedSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..972cfaeac785 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import autofeedsettings + + +class _BaseAutofeedSettingsServiceRestTransport(AutofeedSettingsServiceTransport): + """Base REST backend transport for AutofeedSettingsService. + + 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 _BaseGetAutofeedSettings: + 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': '/accounts/v1/{name=accounts/*/autofeedSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autofeedsettings.GetAutofeedSettingsRequest.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(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAutofeedSettings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1/{autofeed_settings.name=accounts/*/autofeedSettings}', + 'body': 'autofeed_settings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autofeedsettings.UpdateAutofeedSettingsRequest.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(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAutofeedSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py new file mode 100644 index 000000000000..7df59eeedb79 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_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 AutomaticImprovementsServiceClient +from .async_client import AutomaticImprovementsServiceAsyncClient + +__all__ = ( + 'AutomaticImprovementsServiceClient', + 'AutomaticImprovementsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py new file mode 100644 index 000000000000..eb5446f6f1b6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py @@ -0,0 +1,499 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import automaticimprovements +from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport +from .client import AutomaticImprovementsServiceClient + +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 AutomaticImprovementsServiceAsyncClient: + """Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + """ + + _client: AutomaticImprovementsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + + automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.automatic_improvements_path) + parse_automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.parse_automatic_improvements_path) + common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AutomaticImprovementsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AutomaticImprovementsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AutomaticImprovementsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AutomaticImprovementsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AutomaticImprovementsServiceClient.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: + AutomaticImprovementsServiceAsyncClient: The constructed client. + """ + return AutomaticImprovementsServiceClient.from_service_account_info.__func__(AutomaticImprovementsServiceAsyncClient, 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: + AutomaticImprovementsServiceAsyncClient: The constructed client. + """ + return AutomaticImprovementsServiceClient.from_service_account_file.__func__(AutomaticImprovementsServiceAsyncClient, 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 AutomaticImprovementsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AutomaticImprovementsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutomaticImprovementsServiceTransport: 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 = AutomaticImprovementsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the automatic improvements 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,AutomaticImprovementsServiceTransport,Callable[..., AutomaticImprovementsServiceTransport]]]): + 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 AutomaticImprovementsServiceTransport 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 = AutomaticImprovementsServiceClient( + 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.accounts_v1.AutomaticImprovementsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "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.accounts.v1.AutomaticImprovementsService", + "credentialsType": None, + } + ) + + async def get_automatic_improvements(self, + request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Retrieves the automatic improvements of an 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_accounts_v1 + + async def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetAutomaticImprovementsRequest, dict]]): + The request object. Request message for the ``GetAutomaticImprovements`` + method. + name (:class:`str`): + Required. The resource name of the automatic + improvements. Format: + ``accounts/{account}/automaticImprovements`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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, automaticimprovements.GetAutomaticImprovementsRequest): + request = automaticimprovements.GetAutomaticImprovementsRequest(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.get_automatic_improvements] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_automatic_improvements(self, + request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, + *, + automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Updates the automatic improvements of an 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_accounts_v1 + + async def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = await client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateAutomaticImprovementsRequest, dict]]): + The request object. Request message for the ``UpdateAutomaticImprovements`` + method. + automatic_improvements (:class:`google.shopping.merchant_accounts_v1.types.AutomaticImprovements`): + Required. The new version of the + automatic imrovements. + + This corresponds to the ``automatic_improvements`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``item_updates`` + - ``item_updates.account_level_settings`` + - ``image_improvements`` + - ``image_improvements.account_level_settings`` + - ``shipping_improvements`` + - ``shipping_improvements.allow_shipping_improvements`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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 = [automatic_improvements, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, automaticimprovements.UpdateAutomaticImprovementsRequest): + request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if automatic_improvements is not None: + request.automatic_improvements = automatic_improvements + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_automatic_improvements] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("automatic_improvements.name", request.automatic_improvements.name), + )), + ) + + # 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 __aenter__(self) -> "AutomaticImprovementsServiceAsyncClient": + 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__ = ( + "AutomaticImprovementsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py new file mode 100644 index 000000000000..27be6fb27f1e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py @@ -0,0 +1,858 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import automaticimprovements +from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AutomaticImprovementsServiceGrpcTransport +from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport +from .transports.rest import AutomaticImprovementsServiceRestTransport + + +class AutomaticImprovementsServiceClientMeta(type): + """Metaclass for the AutomaticImprovementsService 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[AutomaticImprovementsServiceTransport]] + _transport_registry["grpc"] = AutomaticImprovementsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AutomaticImprovementsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AutomaticImprovementsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AutomaticImprovementsServiceTransport]: + """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 AutomaticImprovementsServiceClient(metaclass=AutomaticImprovementsServiceClientMeta): + """Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + """ + + @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: + AutomaticImprovementsServiceClient: 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: + AutomaticImprovementsServiceClient: 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) -> AutomaticImprovementsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutomaticImprovementsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def automatic_improvements_path(account: str,) -> str: + """Returns a fully-qualified automatic_improvements string.""" + return "accounts/{account}/automaticImprovements".format(account=account, ) + + @staticmethod + def parse_automatic_improvements_path(path: str) -> Dict[str,str]: + """Parses a automatic_improvements path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/automaticImprovements$", 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 = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient._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, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the automatic improvements 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,AutomaticImprovementsServiceTransport,Callable[..., AutomaticImprovementsServiceTransport]]]): + 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 AutomaticImprovementsServiceTransport 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 = AutomaticImprovementsServiceClient._read_environment_variables() + self._client_cert_source = AutomaticImprovementsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AutomaticImprovementsServiceClient._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, AutomaticImprovementsServiceTransport) + if transport_provided: + # transport is a AutomaticImprovementsServiceTransport 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(AutomaticImprovementsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AutomaticImprovementsServiceClient._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[AutomaticImprovementsServiceTransport], Callable[..., AutomaticImprovementsServiceTransport]] = ( + AutomaticImprovementsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AutomaticImprovementsServiceTransport], 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.accounts_v1.AutomaticImprovementsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "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.accounts.v1.AutomaticImprovementsService", + "credentialsType": None, + } + ) + + def get_automatic_improvements(self, + request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Retrieves the automatic improvements of an 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_accounts_v1 + + def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetAutomaticImprovementsRequest, dict]): + The request object. Request message for the ``GetAutomaticImprovements`` + method. + name (str): + Required. The resource name of the automatic + improvements. Format: + ``accounts/{account}/automaticImprovements`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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, automaticimprovements.GetAutomaticImprovementsRequest): + request = automaticimprovements.GetAutomaticImprovementsRequest(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.get_automatic_improvements] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_automatic_improvements(self, + request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, + *, + automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Updates the automatic improvements of an 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_accounts_v1 + + def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateAutomaticImprovementsRequest, dict]): + The request object. Request message for the ``UpdateAutomaticImprovements`` + method. + automatic_improvements (google.shopping.merchant_accounts_v1.types.AutomaticImprovements): + Required. The new version of the + automatic imrovements. + + This corresponds to the ``automatic_improvements`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``item_updates`` + - ``item_updates.account_level_settings`` + - ``image_improvements`` + - ``image_improvements.account_level_settings`` + - ``shipping_improvements`` + - ``shipping_improvements.allow_shipping_improvements`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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 = [automatic_improvements, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, automaticimprovements.UpdateAutomaticImprovementsRequest): + request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if automatic_improvements is not None: + request.automatic_improvements = automatic_improvements + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_automatic_improvements] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("automatic_improvements.name", request.automatic_improvements.name), + )), + ) + + # 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 __enter__(self) -> "AutomaticImprovementsServiceClient": + 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__ = ( + "AutomaticImprovementsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst new file mode 100644 index 000000000000..87e807806d8b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AutomaticImprovementsServiceTransport` is the ABC for all transports. +- public child `AutomaticImprovementsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AutomaticImprovementsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAutomaticImprovementsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AutomaticImprovementsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py new file mode 100644 index 000000000000..815443dffafc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_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 AutomaticImprovementsServiceTransport +from .grpc import AutomaticImprovementsServiceGrpcTransport +from .grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport +from .rest import AutomaticImprovementsServiceRestTransport +from .rest import AutomaticImprovementsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] +_transport_registry['grpc'] = AutomaticImprovementsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AutomaticImprovementsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AutomaticImprovementsServiceRestTransport + +__all__ = ( + 'AutomaticImprovementsServiceTransport', + 'AutomaticImprovementsServiceGrpcTransport', + 'AutomaticImprovementsServiceGrpcAsyncIOTransport', + 'AutomaticImprovementsServiceRestTransport', + 'AutomaticImprovementsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py new file mode 100644 index 000000000000..f26ae7ecb83f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import automaticimprovements + +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 AutomaticImprovementsServiceTransport(abc.ABC): + """Abstract transport class for AutomaticImprovementsService.""" + + 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.get_automatic_improvements: gapic_v1.method.wrap_method( + self.get_automatic_improvements, + default_timeout=None, + client_info=client_info, + ), + self.update_automatic_improvements: gapic_v1.method.wrap_method( + self.update_automatic_improvements, + 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 get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + Union[ + automaticimprovements.AutomaticImprovements, + Awaitable[automaticimprovements.AutomaticImprovements] + ]]: + raise NotImplementedError() + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + Union[ + automaticimprovements.AutomaticImprovements, + Awaitable[automaticimprovements.AutomaticImprovements] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AutomaticImprovementsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py new file mode 100644 index 000000000000..f0e16dc7ca10 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- 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.shopping.merchant_accounts_v1.types import automaticimprovements +from .base import AutomaticImprovementsServiceTransport, 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.accounts.v1.AutomaticImprovementsService", + "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.accounts.v1.AutomaticImprovementsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutomaticImprovementsServiceGrpcTransport(AutomaticImprovementsServiceTransport): + """gRPC backend transport for AutomaticImprovementsService. + + Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + + 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 get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + r"""Return a callable for the get automatic improvements method over gRPC. + + Retrieves the automatic improvements of an account. + + Returns: + Callable[[~.GetAutomaticImprovementsRequest], + ~.AutomaticImprovements]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_automatic_improvements' not in self._stubs: + self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/GetAutomaticImprovements', + request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['get_automatic_improvements'] + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + r"""Return a callable for the update automatic improvements method over gRPC. + + Updates the automatic improvements of an account. + + Returns: + Callable[[~.UpdateAutomaticImprovementsRequest], + ~.AutomaticImprovements]: + 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 'update_automatic_improvements' not in self._stubs: + self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/UpdateAutomaticImprovements', + request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['update_automatic_improvements'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AutomaticImprovementsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..dfc1ccc7465e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py @@ -0,0 +1,400 @@ +# -*- 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.shopping.merchant_accounts_v1.types import automaticimprovements +from .base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AutomaticImprovementsServiceGrpcTransport + +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.accounts.v1.AutomaticImprovementsService", + "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.accounts.v1.AutomaticImprovementsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutomaticImprovementsServiceGrpcAsyncIOTransport(AutomaticImprovementsServiceTransport): + """gRPC AsyncIO backend transport for AutomaticImprovementsService. + + Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + + 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 get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + Awaitable[automaticimprovements.AutomaticImprovements]]: + r"""Return a callable for the get automatic improvements method over gRPC. + + Retrieves the automatic improvements of an account. + + Returns: + Callable[[~.GetAutomaticImprovementsRequest], + Awaitable[~.AutomaticImprovements]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_automatic_improvements' not in self._stubs: + self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/GetAutomaticImprovements', + request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['get_automatic_improvements'] + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + Awaitable[automaticimprovements.AutomaticImprovements]]: + r"""Return a callable for the update automatic improvements method over gRPC. + + Updates the automatic improvements of an account. + + Returns: + Callable[[~.UpdateAutomaticImprovementsRequest], + Awaitable[~.AutomaticImprovements]]: + 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 'update_automatic_improvements' not in self._stubs: + self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/UpdateAutomaticImprovements', + request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['update_automatic_improvements'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_automatic_improvements: self._wrap_method( + self.get_automatic_improvements, + default_timeout=None, + client_info=client_info, + ), + self.update_automatic_improvements: self._wrap_method( + self.update_automatic_improvements, + 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__ = ( + 'AutomaticImprovementsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py new file mode 100644 index 000000000000..ec5a09c351c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py @@ -0,0 +1,537 @@ +# -*- 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.shopping.merchant_accounts_v1.types import automaticimprovements + + +from .rest_base import _BaseAutomaticImprovementsServiceRestTransport +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 AutomaticImprovementsServiceRestInterceptor: + """Interceptor for AutomaticImprovementsService. + + 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 AutomaticImprovementsServiceRestTransport. + + .. code-block:: python + class MyCustomAutomaticImprovementsServiceInterceptor(AutomaticImprovementsServiceRestInterceptor): + def pre_get_automatic_improvements(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_automatic_improvements(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_automatic_improvements(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_automatic_improvements(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AutomaticImprovementsServiceRestTransport(interceptor=MyCustomAutomaticImprovementsServiceInterceptor()) + client = AutomaticImprovementsServiceClient(transport=transport) + + + """ + def pre_get_automatic_improvements(self, request: automaticimprovements.GetAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.GetAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_automatic_improvements + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutomaticImprovementsService server. + """ + return request, metadata + + def post_get_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: + """Post-rpc interceptor for get_automatic_improvements + + DEPRECATED. Please use the `post_get_automatic_improvements_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutomaticImprovementsService server but before + it is returned to user code. This `post_get_automatic_improvements` interceptor runs + before the `post_get_automatic_improvements_with_metadata` interceptor. + """ + return response + + def post_get_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_automatic_improvements + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutomaticImprovementsService server but before it is returned to user code. + + We recommend only using this `post_get_automatic_improvements_with_metadata` + interceptor in new development instead of the `post_get_automatic_improvements` interceptor. + When both interceptors are used, this `post_get_automatic_improvements_with_metadata` interceptor runs after the + `post_get_automatic_improvements` interceptor. The (possibly modified) response returned by + `post_get_automatic_improvements` will be passed to + `post_get_automatic_improvements_with_metadata`. + """ + return response, metadata + + def pre_update_automatic_improvements(self, request: automaticimprovements.UpdateAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.UpdateAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_automatic_improvements + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutomaticImprovementsService server. + """ + return request, metadata + + def post_update_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: + """Post-rpc interceptor for update_automatic_improvements + + DEPRECATED. Please use the `post_update_automatic_improvements_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutomaticImprovementsService server but before + it is returned to user code. This `post_update_automatic_improvements` interceptor runs + before the `post_update_automatic_improvements_with_metadata` interceptor. + """ + return response + + def post_update_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_automatic_improvements + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutomaticImprovementsService server but before it is returned to user code. + + We recommend only using this `post_update_automatic_improvements_with_metadata` + interceptor in new development instead of the `post_update_automatic_improvements` interceptor. + When both interceptors are used, this `post_update_automatic_improvements_with_metadata` interceptor runs after the + `post_update_automatic_improvements` interceptor. The (possibly modified) response returned by + `post_update_automatic_improvements` will be passed to + `post_update_automatic_improvements_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AutomaticImprovementsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutomaticImprovementsServiceRestInterceptor + + +class AutomaticImprovementsServiceRestTransport(_BaseAutomaticImprovementsServiceRestTransport): + """REST backend synchronous transport for AutomaticImprovementsService. + + Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + + 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[AutomaticImprovementsServiceRestInterceptor] = 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 AutomaticImprovementsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements, AutomaticImprovementsServiceRestStub): + def __hash__(self): + return hash("AutomaticImprovementsServiceRestTransport.GetAutomaticImprovements") + + @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: automaticimprovements.GetAutomaticImprovementsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> automaticimprovements.AutomaticImprovements: + r"""Call the get automatic + improvements method over HTTP. + + Args: + request (~.automaticimprovements.GetAutomaticImprovementsRequest): + The request object. Request message for the ``GetAutomaticImprovements`` + 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: + ~.automaticimprovements.AutomaticImprovements: + Collection of information related to the `automatic + improvements `__ + of an account. + + """ + + http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_http_options() + + request, metadata = self._interceptor.pre_get_automatic_improvements(request, metadata) + transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutomaticImprovementsServiceClient.GetAutomaticImprovements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "rpcName": "GetAutomaticImprovements", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutomaticImprovementsServiceRestTransport._GetAutomaticImprovements._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 = automaticimprovements.AutomaticImprovements() + pb_resp = automaticimprovements.AutomaticImprovements.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_automatic_improvements(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_automatic_improvements_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = automaticimprovements.AutomaticImprovements.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.accounts_v1.AutomaticImprovementsServiceClient.get_automatic_improvements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "rpcName": "GetAutomaticImprovements", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements, AutomaticImprovementsServiceRestStub): + def __hash__(self): + return hash("AutomaticImprovementsServiceRestTransport.UpdateAutomaticImprovements") + + @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: automaticimprovements.UpdateAutomaticImprovementsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> automaticimprovements.AutomaticImprovements: + r"""Call the update automatic + improvements method over HTTP. + + Args: + request (~.automaticimprovements.UpdateAutomaticImprovementsRequest): + The request object. Request message for the ``UpdateAutomaticImprovements`` + 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: + ~.automaticimprovements.AutomaticImprovements: + Collection of information related to the `automatic + improvements `__ + of an account. + + """ + + http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_http_options() + + request, metadata = self._interceptor.pre_update_automatic_improvements(request, metadata) + transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_transcoded_request(http_options, request) + + body = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutomaticImprovementsServiceClient.UpdateAutomaticImprovements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "rpcName": "UpdateAutomaticImprovements", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutomaticImprovementsServiceRestTransport._UpdateAutomaticImprovements._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 = automaticimprovements.AutomaticImprovements() + pb_resp = automaticimprovements.AutomaticImprovements.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_automatic_improvements(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_automatic_improvements_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = automaticimprovements.AutomaticImprovements.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.accounts_v1.AutomaticImprovementsServiceClient.update_automatic_improvements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "rpcName": "UpdateAutomaticImprovements", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + # 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._GetAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + # 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._UpdateAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AutomaticImprovementsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py new file mode 100644 index 000000000000..3bb6c7689ef5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import automaticimprovements + + +class _BaseAutomaticImprovementsServiceRestTransport(AutomaticImprovementsServiceTransport): + """Base REST backend transport for AutomaticImprovementsService. + + 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 _BaseGetAutomaticImprovements: + 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': '/accounts/v1/{name=accounts/*/automaticImprovements}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = automaticimprovements.GetAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAutomaticImprovements: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1/{automatic_improvements.name=accounts/*/automaticImprovements}', + 'body': 'automatic_improvements', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = automaticimprovements.UpdateAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAutomaticImprovementsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py new file mode 100644 index 000000000000..f97b26e0a25c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_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 BusinessIdentityServiceClient +from .async_client import BusinessIdentityServiceAsyncClient + +__all__ = ( + 'BusinessIdentityServiceClient', + 'BusinessIdentityServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py new file mode 100644 index 000000000000..c771acbc99d1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py @@ -0,0 +1,502 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import businessidentity +from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport +from .client import BusinessIdentityServiceClient + +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 BusinessIdentityServiceAsyncClient: + """Service to support `business + identity `__ + API. + """ + + _client: BusinessIdentityServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + + business_identity_path = staticmethod(BusinessIdentityServiceClient.business_identity_path) + parse_business_identity_path = staticmethod(BusinessIdentityServiceClient.parse_business_identity_path) + common_billing_account_path = staticmethod(BusinessIdentityServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(BusinessIdentityServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(BusinessIdentityServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(BusinessIdentityServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(BusinessIdentityServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(BusinessIdentityServiceClient.parse_common_organization_path) + common_project_path = staticmethod(BusinessIdentityServiceClient.common_project_path) + parse_common_project_path = staticmethod(BusinessIdentityServiceClient.parse_common_project_path) + common_location_path = staticmethod(BusinessIdentityServiceClient.common_location_path) + parse_common_location_path = staticmethod(BusinessIdentityServiceClient.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: + BusinessIdentityServiceAsyncClient: The constructed client. + """ + return BusinessIdentityServiceClient.from_service_account_info.__func__(BusinessIdentityServiceAsyncClient, 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: + BusinessIdentityServiceAsyncClient: The constructed client. + """ + return BusinessIdentityServiceClient.from_service_account_file.__func__(BusinessIdentityServiceAsyncClient, 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 BusinessIdentityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> BusinessIdentityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessIdentityServiceTransport: 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 = BusinessIdentityServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business identity 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,BusinessIdentityServiceTransport,Callable[..., BusinessIdentityServiceTransport]]]): + 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 BusinessIdentityServiceTransport 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 = BusinessIdentityServiceClient( + 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.accounts_v1.BusinessIdentityServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "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.accounts.v1.BusinessIdentityService", + "credentialsType": None, + } + ) + + async def get_business_identity(self, + request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Retrieves the business identity of an 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_accounts_v1 + + async def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetBusinessIdentityRequest, dict]]): + The request object. Request message for the ``GetBusinessIdentity`` method. + name (:class:`str`): + Required. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity``. For + example, ``accounts/123456/businessIdentity``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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, businessidentity.GetBusinessIdentityRequest): + request = businessidentity.GetBusinessIdentityRequest(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.get_business_identity] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_business_identity(self, + request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, + *, + business_identity: Optional[businessidentity.BusinessIdentity] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Updates the business identity of an account. + Executing this method requires admin access. + + .. 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_accounts_v1 + + async def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + business_identity = merchant_accounts_v1.BusinessIdentity() + business_identity.promotions_consent = "PROMOTIONS_CONSENT_DENIED" + + request = merchant_accounts_v1.UpdateBusinessIdentityRequest( + business_identity=business_identity, + ) + + # Make the request + response = await client.update_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateBusinessIdentityRequest, dict]]): + The request object. Request message for the ``UpdateBusinessIdentity`` + method. + business_identity (:class:`google.shopping.merchant_accounts_v1.types.BusinessIdentity`): + Required. The new version of the + business identity. + + This corresponds to the ``business_identity`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``black_owned`` + - ``latino_owned`` + - ``promotions_consent`` + - ``small_business`` + - ``veteran_owned`` + - ``women_owned`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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 = [business_identity, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessidentity.UpdateBusinessIdentityRequest): + request = businessidentity.UpdateBusinessIdentityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_identity is not None: + request.business_identity = business_identity + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_identity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_identity.name", request.business_identity.name), + )), + ) + + # 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 __aenter__(self) -> "BusinessIdentityServiceAsyncClient": + 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__ = ( + "BusinessIdentityServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py new file mode 100644 index 000000000000..86f8bcba90d3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py @@ -0,0 +1,861 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import businessidentity +from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import BusinessIdentityServiceGrpcTransport +from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport +from .transports.rest import BusinessIdentityServiceRestTransport + + +class BusinessIdentityServiceClientMeta(type): + """Metaclass for the BusinessIdentityService 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[BusinessIdentityServiceTransport]] + _transport_registry["grpc"] = BusinessIdentityServiceGrpcTransport + _transport_registry["grpc_asyncio"] = BusinessIdentityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = BusinessIdentityServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[BusinessIdentityServiceTransport]: + """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 BusinessIdentityServiceClient(metaclass=BusinessIdentityServiceClientMeta): + """Service to support `business + identity `__ + API. + """ + + @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: + BusinessIdentityServiceClient: 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: + BusinessIdentityServiceClient: 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) -> BusinessIdentityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessIdentityServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def business_identity_path(account: str,) -> str: + """Returns a fully-qualified business_identity string.""" + return "accounts/{account}/businessIdentity".format(account=account, ) + + @staticmethod + def parse_business_identity_path(path: str) -> Dict[str,str]: + """Parses a business_identity path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/businessIdentity$", 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 = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient._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, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business identity 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,BusinessIdentityServiceTransport,Callable[..., BusinessIdentityServiceTransport]]]): + 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 BusinessIdentityServiceTransport 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 = BusinessIdentityServiceClient._read_environment_variables() + self._client_cert_source = BusinessIdentityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = BusinessIdentityServiceClient._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, BusinessIdentityServiceTransport) + if transport_provided: + # transport is a BusinessIdentityServiceTransport 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(BusinessIdentityServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + BusinessIdentityServiceClient._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[BusinessIdentityServiceTransport], Callable[..., BusinessIdentityServiceTransport]] = ( + BusinessIdentityServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., BusinessIdentityServiceTransport], 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.accounts_v1.BusinessIdentityServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "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.accounts.v1.BusinessIdentityService", + "credentialsType": None, + } + ) + + def get_business_identity(self, + request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Retrieves the business identity of an 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_accounts_v1 + + def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetBusinessIdentityRequest, dict]): + The request object. Request message for the ``GetBusinessIdentity`` method. + name (str): + Required. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity``. For + example, ``accounts/123456/businessIdentity``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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, businessidentity.GetBusinessIdentityRequest): + request = businessidentity.GetBusinessIdentityRequest(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.get_business_identity] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_business_identity(self, + request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, + *, + business_identity: Optional[businessidentity.BusinessIdentity] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Updates the business identity of an account. + Executing this method requires admin access. + + .. 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_accounts_v1 + + def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceClient() + + # Initialize request argument(s) + business_identity = merchant_accounts_v1.BusinessIdentity() + business_identity.promotions_consent = "PROMOTIONS_CONSENT_DENIED" + + request = merchant_accounts_v1.UpdateBusinessIdentityRequest( + business_identity=business_identity, + ) + + # Make the request + response = client.update_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateBusinessIdentityRequest, dict]): + The request object. Request message for the ``UpdateBusinessIdentity`` + method. + business_identity (google.shopping.merchant_accounts_v1.types.BusinessIdentity): + Required. The new version of the + business identity. + + This corresponds to the ``business_identity`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``black_owned`` + - ``latino_owned`` + - ``promotions_consent`` + - ``small_business`` + - ``veteran_owned`` + - ``women_owned`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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 = [business_identity, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessidentity.UpdateBusinessIdentityRequest): + request = businessidentity.UpdateBusinessIdentityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_identity is not None: + request.business_identity = business_identity + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_business_identity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_identity.name", request.business_identity.name), + )), + ) + + # 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 __enter__(self) -> "BusinessIdentityServiceClient": + 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__ = ( + "BusinessIdentityServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst new file mode 100644 index 000000000000..55db4f093f62 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`BusinessIdentityServiceTransport` is the ABC for all transports. +- public child `BusinessIdentityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `BusinessIdentityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseBusinessIdentityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `BusinessIdentityServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py new file mode 100644 index 000000000000..0f211578bee2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_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 BusinessIdentityServiceTransport +from .grpc import BusinessIdentityServiceGrpcTransport +from .grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport +from .rest import BusinessIdentityServiceRestTransport +from .rest import BusinessIdentityServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessIdentityServiceTransport]] +_transport_registry['grpc'] = BusinessIdentityServiceGrpcTransport +_transport_registry['grpc_asyncio'] = BusinessIdentityServiceGrpcAsyncIOTransport +_transport_registry['rest'] = BusinessIdentityServiceRestTransport + +__all__ = ( + 'BusinessIdentityServiceTransport', + 'BusinessIdentityServiceGrpcTransport', + 'BusinessIdentityServiceGrpcAsyncIOTransport', + 'BusinessIdentityServiceRestTransport', + 'BusinessIdentityServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py new file mode 100644 index 000000000000..971bcbe15a51 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import businessidentity + +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 BusinessIdentityServiceTransport(abc.ABC): + """Abstract transport class for BusinessIdentityService.""" + + 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.get_business_identity: gapic_v1.method.wrap_method( + self.get_business_identity, + default_timeout=None, + client_info=client_info, + ), + self.update_business_identity: gapic_v1.method.wrap_method( + self.update_business_identity, + 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 get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + Union[ + businessidentity.BusinessIdentity, + Awaitable[businessidentity.BusinessIdentity] + ]]: + raise NotImplementedError() + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + Union[ + businessidentity.BusinessIdentity, + Awaitable[businessidentity.BusinessIdentity] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'BusinessIdentityServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py new file mode 100644 index 000000000000..3b03093ac306 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py @@ -0,0 +1,375 @@ +# -*- 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.shopping.merchant_accounts_v1.types import businessidentity +from .base import BusinessIdentityServiceTransport, 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.accounts.v1.BusinessIdentityService", + "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.accounts.v1.BusinessIdentityService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessIdentityServiceGrpcTransport(BusinessIdentityServiceTransport): + """gRPC backend transport for BusinessIdentityService. + + Service to support `business + identity `__ + API. + + 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 get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + r"""Return a callable for the get business identity method over gRPC. + + Retrieves the business identity of an account. + + Returns: + Callable[[~.GetBusinessIdentityRequest], + ~.BusinessIdentity]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_identity' not in self._stubs: + self._stubs['get_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessIdentityService/GetBusinessIdentity', + request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['get_business_identity'] + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + r"""Return a callable for the update business identity method over gRPC. + + Updates the business identity of an account. + Executing this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessIdentityRequest], + ~.BusinessIdentity]: + 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 'update_business_identity' not in self._stubs: + self._stubs['update_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessIdentityService/UpdateBusinessIdentity', + request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['update_business_identity'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'BusinessIdentityServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..05110ef91b55 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py @@ -0,0 +1,401 @@ +# -*- 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.shopping.merchant_accounts_v1.types import businessidentity +from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import BusinessIdentityServiceGrpcTransport + +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.accounts.v1.BusinessIdentityService", + "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.accounts.v1.BusinessIdentityService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessIdentityServiceGrpcAsyncIOTransport(BusinessIdentityServiceTransport): + """gRPC AsyncIO backend transport for BusinessIdentityService. + + Service to support `business + identity `__ + API. + + 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 get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + Awaitable[businessidentity.BusinessIdentity]]: + r"""Return a callable for the get business identity method over gRPC. + + Retrieves the business identity of an account. + + Returns: + Callable[[~.GetBusinessIdentityRequest], + Awaitable[~.BusinessIdentity]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_identity' not in self._stubs: + self._stubs['get_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessIdentityService/GetBusinessIdentity', + request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['get_business_identity'] + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + Awaitable[businessidentity.BusinessIdentity]]: + r"""Return a callable for the update business identity method over gRPC. + + Updates the business identity of an account. + Executing this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessIdentityRequest], + Awaitable[~.BusinessIdentity]]: + 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 'update_business_identity' not in self._stubs: + self._stubs['update_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessIdentityService/UpdateBusinessIdentity', + request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['update_business_identity'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_business_identity: self._wrap_method( + self.get_business_identity, + default_timeout=None, + client_info=client_info, + ), + self.update_business_identity: self._wrap_method( + self.update_business_identity, + 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__ = ( + 'BusinessIdentityServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py new file mode 100644 index 000000000000..c10c0fa1caea --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py @@ -0,0 +1,532 @@ +# -*- 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.shopping.merchant_accounts_v1.types import businessidentity + + +from .rest_base import _BaseBusinessIdentityServiceRestTransport +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 BusinessIdentityServiceRestInterceptor: + """Interceptor for BusinessIdentityService. + + 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 BusinessIdentityServiceRestTransport. + + .. code-block:: python + class MyCustomBusinessIdentityServiceInterceptor(BusinessIdentityServiceRestInterceptor): + def pre_get_business_identity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_business_identity(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_business_identity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_business_identity(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BusinessIdentityServiceRestTransport(interceptor=MyCustomBusinessIdentityServiceInterceptor()) + client = BusinessIdentityServiceClient(transport=transport) + + + """ + def pre_get_business_identity(self, request: businessidentity.GetBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_business_identity + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessIdentityService server. + """ + return request, metadata + + def post_get_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: + """Post-rpc interceptor for get_business_identity + + DEPRECATED. Please use the `post_get_business_identity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessIdentityService server but before + it is returned to user code. This `post_get_business_identity` interceptor runs + before the `post_get_business_identity_with_metadata` interceptor. + """ + return response + + def post_get_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_business_identity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessIdentityService server but before it is returned to user code. + + We recommend only using this `post_get_business_identity_with_metadata` + interceptor in new development instead of the `post_get_business_identity` interceptor. + When both interceptors are used, this `post_get_business_identity_with_metadata` interceptor runs after the + `post_get_business_identity` interceptor. The (possibly modified) response returned by + `post_get_business_identity` will be passed to + `post_get_business_identity_with_metadata`. + """ + return response, metadata + + def pre_update_business_identity(self, request: businessidentity.UpdateBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_business_identity + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessIdentityService server. + """ + return request, metadata + + def post_update_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: + """Post-rpc interceptor for update_business_identity + + DEPRECATED. Please use the `post_update_business_identity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessIdentityService server but before + it is returned to user code. This `post_update_business_identity` interceptor runs + before the `post_update_business_identity_with_metadata` interceptor. + """ + return response + + def post_update_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_business_identity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessIdentityService server but before it is returned to user code. + + We recommend only using this `post_update_business_identity_with_metadata` + interceptor in new development instead of the `post_update_business_identity` interceptor. + When both interceptors are used, this `post_update_business_identity_with_metadata` interceptor runs after the + `post_update_business_identity` interceptor. The (possibly modified) response returned by + `post_update_business_identity` will be passed to + `post_update_business_identity_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class BusinessIdentityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BusinessIdentityServiceRestInterceptor + + +class BusinessIdentityServiceRestTransport(_BaseBusinessIdentityServiceRestTransport): + """REST backend synchronous transport for BusinessIdentityService. + + Service to support `business + identity `__ + API. + + 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[BusinessIdentityServiceRestInterceptor] = 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 BusinessIdentityServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity, BusinessIdentityServiceRestStub): + def __hash__(self): + return hash("BusinessIdentityServiceRestTransport.GetBusinessIdentity") + + @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: businessidentity.GetBusinessIdentityRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessidentity.BusinessIdentity: + r"""Call the get business identity method over HTTP. + + Args: + request (~.businessidentity.GetBusinessIdentityRequest): + The request object. Request message for the ``GetBusinessIdentity`` 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: + ~.businessidentity.BusinessIdentity: + Collection of information related to the `identity of a + business `__. + + """ + + http_options = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_http_options() + + request, metadata = self._interceptor.pre_get_business_identity(request, metadata) + transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessIdentityServiceClient.GetBusinessIdentity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "rpcName": "GetBusinessIdentity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessIdentityServiceRestTransport._GetBusinessIdentity._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 = businessidentity.BusinessIdentity() + pb_resp = businessidentity.BusinessIdentity.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_business_identity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_business_identity_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessidentity.BusinessIdentity.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.accounts_v1.BusinessIdentityServiceClient.get_business_identity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "rpcName": "GetBusinessIdentity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity, BusinessIdentityServiceRestStub): + def __hash__(self): + return hash("BusinessIdentityServiceRestTransport.UpdateBusinessIdentity") + + @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: businessidentity.UpdateBusinessIdentityRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessidentity.BusinessIdentity: + r"""Call the update business identity method over HTTP. + + Args: + request (~.businessidentity.UpdateBusinessIdentityRequest): + The request object. Request message for the ``UpdateBusinessIdentity`` + 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: + ~.businessidentity.BusinessIdentity: + Collection of information related to the `identity of a + business `__. + + """ + + http_options = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_http_options() + + request, metadata = self._interceptor.pre_update_business_identity(request, metadata) + transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_transcoded_request(http_options, request) + + body = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessIdentityServiceClient.UpdateBusinessIdentity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "rpcName": "UpdateBusinessIdentity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessIdentityServiceRestTransport._UpdateBusinessIdentity._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 = businessidentity.BusinessIdentity() + pb_resp = businessidentity.BusinessIdentity.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_business_identity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_business_identity_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessidentity.BusinessIdentity.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.accounts_v1.BusinessIdentityServiceClient.update_business_identity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "rpcName": "UpdateBusinessIdentity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + # 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._GetBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + # 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._UpdateBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'BusinessIdentityServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py new file mode 100644 index 000000000000..cc9e2447fde6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import businessidentity + + +class _BaseBusinessIdentityServiceRestTransport(BusinessIdentityServiceTransport): + """Base REST backend transport for BusinessIdentityService. + + 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 _BaseGetBusinessIdentity: + 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': '/accounts/v1/{name=accounts/*/businessIdentity}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessidentity.GetBusinessIdentityRequest.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(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateBusinessIdentity: + 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': 'patch', + 'uri': '/accounts/v1/{business_identity.name=accounts/*/businessIdentity}', + 'body': 'business_identity', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessidentity.UpdateBusinessIdentityRequest.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(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseBusinessIdentityServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py new file mode 100644 index 000000000000..df547a28f156 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_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 BusinessInfoServiceClient +from .async_client import BusinessInfoServiceAsyncClient + +__all__ = ( + 'BusinessInfoServiceClient', + 'BusinessInfoServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py new file mode 100644 index 000000000000..503f3b57907f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py @@ -0,0 +1,503 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import businessinfo +from google.shopping.merchant_accounts_v1.types import customerservice +from google.shopping.merchant_accounts_v1.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore +from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport +from .client import BusinessInfoServiceClient + +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 BusinessInfoServiceAsyncClient: + """Service to support business info API.""" + + _client: BusinessInfoServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = BusinessInfoServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = BusinessInfoServiceClient._DEFAULT_UNIVERSE + + business_info_path = staticmethod(BusinessInfoServiceClient.business_info_path) + parse_business_info_path = staticmethod(BusinessInfoServiceClient.parse_business_info_path) + common_billing_account_path = staticmethod(BusinessInfoServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(BusinessInfoServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(BusinessInfoServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(BusinessInfoServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(BusinessInfoServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(BusinessInfoServiceClient.parse_common_organization_path) + common_project_path = staticmethod(BusinessInfoServiceClient.common_project_path) + parse_common_project_path = staticmethod(BusinessInfoServiceClient.parse_common_project_path) + common_location_path = staticmethod(BusinessInfoServiceClient.common_location_path) + parse_common_location_path = staticmethod(BusinessInfoServiceClient.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: + BusinessInfoServiceAsyncClient: The constructed client. + """ + return BusinessInfoServiceClient.from_service_account_info.__func__(BusinessInfoServiceAsyncClient, 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: + BusinessInfoServiceAsyncClient: The constructed client. + """ + return BusinessInfoServiceClient.from_service_account_file.__func__(BusinessInfoServiceAsyncClient, 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 BusinessInfoServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> BusinessInfoServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessInfoServiceTransport: 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 = BusinessInfoServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business info 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,BusinessInfoServiceTransport,Callable[..., BusinessInfoServiceTransport]]]): + 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 BusinessInfoServiceTransport 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 = BusinessInfoServiceClient( + 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.accounts_v1.BusinessInfoServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "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.accounts.v1.BusinessInfoService", + "credentialsType": None, + } + ) + + async def get_business_info(self, + request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Retrieves the business info of an 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_accounts_v1 + + async def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetBusinessInfoRequest, dict]]): + The request object. Request message for the ``GetBusinessInfo`` method. + name (:class:`str`): + Required. The resource name of the business info. + Format: ``accounts/{account}/businessInfo``. For + example, ``accounts/123456/businessInfo``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.BusinessInfo: + The BusinessInfo message contains essential information about a + business. + + This message captures key business details such as + physical address, customer service contacts, and + region-specific identifiers. + + """ + # 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, businessinfo.GetBusinessInfoRequest): + request = businessinfo.GetBusinessInfoRequest(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.get_business_info] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_business_info(self, + request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, + *, + business_info: Optional[businessinfo.BusinessInfo] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Updates the business info of an account. Executing + this method requires admin access. + + .. 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_accounts_v1 + + async def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateBusinessInfoRequest( + ) + + # Make the request + response = await client.update_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateBusinessInfoRequest, dict]]): + The request object. Request message for the ``UpdateBusinessInfo`` method. + business_info (:class:`google.shopping.merchant_accounts_v1.types.BusinessInfo`): + Required. The new version of the + business info. + + This corresponds to the ``business_info`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``address`` + - ``customer_service`` + - ``korean_business_registration_number`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.BusinessInfo: + The BusinessInfo message contains essential information about a + business. + + This message captures key business details such as + physical address, customer service contacts, and + region-specific identifiers. + + """ + # 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 = [business_info, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessinfo.UpdateBusinessInfoRequest): + request = businessinfo.UpdateBusinessInfoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_info is not None: + request.business_info = business_info + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_info] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_info.name", request.business_info.name), + )), + ) + + # 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 __aenter__(self) -> "BusinessInfoServiceAsyncClient": + 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__ = ( + "BusinessInfoServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py new file mode 100644 index 000000000000..481fc3b7bedc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py @@ -0,0 +1,862 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import businessinfo +from google.shopping.merchant_accounts_v1.types import customerservice +from google.shopping.merchant_accounts_v1.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore +from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import BusinessInfoServiceGrpcTransport +from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport +from .transports.rest import BusinessInfoServiceRestTransport + + +class BusinessInfoServiceClientMeta(type): + """Metaclass for the BusinessInfoService 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[BusinessInfoServiceTransport]] + _transport_registry["grpc"] = BusinessInfoServiceGrpcTransport + _transport_registry["grpc_asyncio"] = BusinessInfoServiceGrpcAsyncIOTransport + _transport_registry["rest"] = BusinessInfoServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[BusinessInfoServiceTransport]: + """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 BusinessInfoServiceClient(metaclass=BusinessInfoServiceClientMeta): + """Service to support business info API.""" + + @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: + BusinessInfoServiceClient: 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: + BusinessInfoServiceClient: 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) -> BusinessInfoServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessInfoServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def business_info_path(account: str,) -> str: + """Returns a fully-qualified business_info string.""" + return "accounts/{account}/businessInfo".format(account=account, ) + + @staticmethod + def parse_business_info_path(path: str) -> Dict[str,str]: + """Parses a business_info path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/businessInfo$", 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 = BusinessInfoServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = BusinessInfoServiceClient._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 = BusinessInfoServiceClient._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, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business info 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,BusinessInfoServiceTransport,Callable[..., BusinessInfoServiceTransport]]]): + 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 BusinessInfoServiceTransport 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 = BusinessInfoServiceClient._read_environment_variables() + self._client_cert_source = BusinessInfoServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = BusinessInfoServiceClient._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, BusinessInfoServiceTransport) + if transport_provided: + # transport is a BusinessInfoServiceTransport 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(BusinessInfoServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + BusinessInfoServiceClient._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[BusinessInfoServiceTransport], Callable[..., BusinessInfoServiceTransport]] = ( + BusinessInfoServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., BusinessInfoServiceTransport], 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.accounts_v1.BusinessInfoServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "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.accounts.v1.BusinessInfoService", + "credentialsType": None, + } + ) + + def get_business_info(self, + request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Retrieves the business info of an 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_accounts_v1 + + def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetBusinessInfoRequest, dict]): + The request object. Request message for the ``GetBusinessInfo`` method. + name (str): + Required. The resource name of the business info. + Format: ``accounts/{account}/businessInfo``. For + example, ``accounts/123456/businessInfo``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.BusinessInfo: + The BusinessInfo message contains essential information about a + business. + + This message captures key business details such as + physical address, customer service contacts, and + region-specific identifiers. + + """ + # 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, businessinfo.GetBusinessInfoRequest): + request = businessinfo.GetBusinessInfoRequest(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.get_business_info] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_business_info(self, + request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, + *, + business_info: Optional[businessinfo.BusinessInfo] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Updates the business info of an account. Executing + this method requires admin access. + + .. 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_accounts_v1 + + def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateBusinessInfoRequest( + ) + + # Make the request + response = client.update_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateBusinessInfoRequest, dict]): + The request object. Request message for the ``UpdateBusinessInfo`` method. + business_info (google.shopping.merchant_accounts_v1.types.BusinessInfo): + Required. The new version of the + business info. + + This corresponds to the ``business_info`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``address`` + - ``customer_service`` + - ``korean_business_registration_number`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.BusinessInfo: + The BusinessInfo message contains essential information about a + business. + + This message captures key business details such as + physical address, customer service contacts, and + region-specific identifiers. + + """ + # 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 = [business_info, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessinfo.UpdateBusinessInfoRequest): + request = businessinfo.UpdateBusinessInfoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_info is not None: + request.business_info = business_info + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_business_info] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_info.name", request.business_info.name), + )), + ) + + # 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 __enter__(self) -> "BusinessInfoServiceClient": + 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__ = ( + "BusinessInfoServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst new file mode 100644 index 000000000000..1024050406f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`BusinessInfoServiceTransport` is the ABC for all transports. +- public child `BusinessInfoServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `BusinessInfoServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseBusinessInfoServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `BusinessInfoServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py new file mode 100644 index 000000000000..cd3235917a9f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_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 BusinessInfoServiceTransport +from .grpc import BusinessInfoServiceGrpcTransport +from .grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport +from .rest import BusinessInfoServiceRestTransport +from .rest import BusinessInfoServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessInfoServiceTransport]] +_transport_registry['grpc'] = BusinessInfoServiceGrpcTransport +_transport_registry['grpc_asyncio'] = BusinessInfoServiceGrpcAsyncIOTransport +_transport_registry['rest'] = BusinessInfoServiceRestTransport + +__all__ = ( + 'BusinessInfoServiceTransport', + 'BusinessInfoServiceGrpcTransport', + 'BusinessInfoServiceGrpcAsyncIOTransport', + 'BusinessInfoServiceRestTransport', + 'BusinessInfoServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py new file mode 100644 index 000000000000..0644a964efe5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import businessinfo + +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 BusinessInfoServiceTransport(abc.ABC): + """Abstract transport class for BusinessInfoService.""" + + 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.get_business_info: gapic_v1.method.wrap_method( + self.get_business_info, + default_timeout=None, + client_info=client_info, + ), + self.update_business_info: gapic_v1.method.wrap_method( + self.update_business_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! + """ + raise NotImplementedError() + + @property + def get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + Union[ + businessinfo.BusinessInfo, + Awaitable[businessinfo.BusinessInfo] + ]]: + raise NotImplementedError() + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + Union[ + businessinfo.BusinessInfo, + Awaitable[businessinfo.BusinessInfo] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'BusinessInfoServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py new file mode 100644 index 000000000000..b37d363e12a9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py @@ -0,0 +1,373 @@ +# -*- 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.shopping.merchant_accounts_v1.types import businessinfo +from .base import BusinessInfoServiceTransport, 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.accounts.v1.BusinessInfoService", + "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.accounts.v1.BusinessInfoService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessInfoServiceGrpcTransport(BusinessInfoServiceTransport): + """gRPC backend transport for BusinessInfoService. + + Service to support business info API. + + 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 get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + businessinfo.BusinessInfo]: + r"""Return a callable for the get business info method over gRPC. + + Retrieves the business info of an account. + + Returns: + Callable[[~.GetBusinessInfoRequest], + ~.BusinessInfo]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_info' not in self._stubs: + self._stubs['get_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessInfoService/GetBusinessInfo', + request_serializer=businessinfo.GetBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['get_business_info'] + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + businessinfo.BusinessInfo]: + r"""Return a callable for the update business info method over gRPC. + + Updates the business info of an account. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessInfoRequest], + ~.BusinessInfo]: + 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 'update_business_info' not in self._stubs: + self._stubs['update_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessInfoService/UpdateBusinessInfo', + request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['update_business_info'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'BusinessInfoServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..86f371dc6443 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py @@ -0,0 +1,399 @@ +# -*- 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.shopping.merchant_accounts_v1.types import businessinfo +from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import BusinessInfoServiceGrpcTransport + +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.accounts.v1.BusinessInfoService", + "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.accounts.v1.BusinessInfoService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessInfoServiceGrpcAsyncIOTransport(BusinessInfoServiceTransport): + """gRPC AsyncIO backend transport for BusinessInfoService. + + Service to support business info API. + + 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 get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + Awaitable[businessinfo.BusinessInfo]]: + r"""Return a callable for the get business info method over gRPC. + + Retrieves the business info of an account. + + Returns: + Callable[[~.GetBusinessInfoRequest], + Awaitable[~.BusinessInfo]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_info' not in self._stubs: + self._stubs['get_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessInfoService/GetBusinessInfo', + request_serializer=businessinfo.GetBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['get_business_info'] + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + Awaitable[businessinfo.BusinessInfo]]: + r"""Return a callable for the update business info method over gRPC. + + Updates the business info of an account. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessInfoRequest], + Awaitable[~.BusinessInfo]]: + 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 'update_business_info' not in self._stubs: + self._stubs['update_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.BusinessInfoService/UpdateBusinessInfo', + request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['update_business_info'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_business_info: self._wrap_method( + self.get_business_info, + default_timeout=None, + client_info=client_info, + ), + self.update_business_info: self._wrap_method( + self.update_business_info, + 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__ = ( + 'BusinessInfoServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py new file mode 100644 index 000000000000..b6403bcd3356 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py @@ -0,0 +1,537 @@ +# -*- 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.shopping.merchant_accounts_v1.types import businessinfo + + +from .rest_base import _BaseBusinessInfoServiceRestTransport +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 BusinessInfoServiceRestInterceptor: + """Interceptor for BusinessInfoService. + + 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 BusinessInfoServiceRestTransport. + + .. code-block:: python + class MyCustomBusinessInfoServiceInterceptor(BusinessInfoServiceRestInterceptor): + def pre_get_business_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_business_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_business_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_business_info(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BusinessInfoServiceRestTransport(interceptor=MyCustomBusinessInfoServiceInterceptor()) + client = BusinessInfoServiceClient(transport=transport) + + + """ + def pre_get_business_info(self, request: businessinfo.GetBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_business_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessInfoService server. + """ + return request, metadata + + def post_get_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: + """Post-rpc interceptor for get_business_info + + DEPRECATED. Please use the `post_get_business_info_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessInfoService server but before + it is returned to user code. This `post_get_business_info` interceptor runs + before the `post_get_business_info_with_metadata` interceptor. + """ + return response + + def post_get_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_business_info + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessInfoService server but before it is returned to user code. + + We recommend only using this `post_get_business_info_with_metadata` + interceptor in new development instead of the `post_get_business_info` interceptor. + When both interceptors are used, this `post_get_business_info_with_metadata` interceptor runs after the + `post_get_business_info` interceptor. The (possibly modified) response returned by + `post_get_business_info` will be passed to + `post_get_business_info_with_metadata`. + """ + return response, metadata + + def pre_update_business_info(self, request: businessinfo.UpdateBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_business_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessInfoService server. + """ + return request, metadata + + def post_update_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: + """Post-rpc interceptor for update_business_info + + DEPRECATED. Please use the `post_update_business_info_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessInfoService server but before + it is returned to user code. This `post_update_business_info` interceptor runs + before the `post_update_business_info_with_metadata` interceptor. + """ + return response + + def post_update_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_business_info + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessInfoService server but before it is returned to user code. + + We recommend only using this `post_update_business_info_with_metadata` + interceptor in new development instead of the `post_update_business_info` interceptor. + When both interceptors are used, this `post_update_business_info_with_metadata` interceptor runs after the + `post_update_business_info` interceptor. The (possibly modified) response returned by + `post_update_business_info` will be passed to + `post_update_business_info_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class BusinessInfoServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BusinessInfoServiceRestInterceptor + + +class BusinessInfoServiceRestTransport(_BaseBusinessInfoServiceRestTransport): + """REST backend synchronous transport for BusinessInfoService. + + Service to support business info API. + + 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[BusinessInfoServiceRestInterceptor] = 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 BusinessInfoServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo, BusinessInfoServiceRestStub): + def __hash__(self): + return hash("BusinessInfoServiceRestTransport.GetBusinessInfo") + + @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: businessinfo.GetBusinessInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessinfo.BusinessInfo: + r"""Call the get business info method over HTTP. + + Args: + request (~.businessinfo.GetBusinessInfoRequest): + The request object. Request message for the ``GetBusinessInfo`` 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: + ~.businessinfo.BusinessInfo: + The ``BusinessInfo`` message contains essential + information about a business. + + This message captures key business details such as + physical address, customer service contacts, and + region-specific identifiers. + + """ + + http_options = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_http_options() + + request, metadata = self._interceptor.pre_get_business_info(request, metadata) + transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessInfoServiceClient.GetBusinessInfo", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "rpcName": "GetBusinessInfo", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessInfoServiceRestTransport._GetBusinessInfo._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 = businessinfo.BusinessInfo() + pb_resp = businessinfo.BusinessInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_business_info(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_business_info_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessinfo.BusinessInfo.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.accounts_v1.BusinessInfoServiceClient.get_business_info", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "rpcName": "GetBusinessInfo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo, BusinessInfoServiceRestStub): + def __hash__(self): + return hash("BusinessInfoServiceRestTransport.UpdateBusinessInfo") + + @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: businessinfo.UpdateBusinessInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessinfo.BusinessInfo: + r"""Call the update business info method over HTTP. + + Args: + request (~.businessinfo.UpdateBusinessInfoRequest): + The request object. Request message for the ``UpdateBusinessInfo`` 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: + ~.businessinfo.BusinessInfo: + The ``BusinessInfo`` message contains essential + information about a business. + + This message captures key business details such as + physical address, customer service contacts, and + region-specific identifiers. + + """ + + http_options = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_http_options() + + request, metadata = self._interceptor.pre_update_business_info(request, metadata) + transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_transcoded_request(http_options, request) + + body = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessInfoServiceClient.UpdateBusinessInfo", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "rpcName": "UpdateBusinessInfo", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessInfoServiceRestTransport._UpdateBusinessInfo._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 = businessinfo.BusinessInfo() + pb_resp = businessinfo.BusinessInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_business_info(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_business_info_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessinfo.BusinessInfo.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.accounts_v1.BusinessInfoServiceClient.update_business_info", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "rpcName": "UpdateBusinessInfo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + businessinfo.BusinessInfo]: + # 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._GetBusinessInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + businessinfo.BusinessInfo]: + # 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._UpdateBusinessInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'BusinessInfoServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py new file mode 100644 index 000000000000..200b5f0fbbe2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import businessinfo + + +class _BaseBusinessInfoServiceRestTransport(BusinessInfoServiceTransport): + """Base REST backend transport for BusinessInfoService. + + 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 _BaseGetBusinessInfo: + 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': '/accounts/v1/{name=accounts/*/businessInfo}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessinfo.GetBusinessInfoRequest.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(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateBusinessInfo: + 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': 'patch', + 'uri': '/accounts/v1/{business_info.name=accounts/*/businessInfo}', + 'body': 'business_info', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessinfo.UpdateBusinessInfoRequest.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(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseBusinessInfoServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py new file mode 100644 index 000000000000..d3119c55bf22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_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 CheckoutSettingsServiceClient +from .async_client import CheckoutSettingsServiceAsyncClient + +__all__ = ( + 'CheckoutSettingsServiceClient', + 'CheckoutSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py new file mode 100644 index 000000000000..445312673570 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py @@ -0,0 +1,706 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import checkoutsettings +from google.shopping.type.types import types +from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport +from .client import CheckoutSettingsServiceClient + +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 CheckoutSettingsServiceAsyncClient: + """Service for supporting `checkout + settings `__. + """ + + _client: CheckoutSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + + checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.checkout_settings_path) + parse_checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.parse_checkout_settings_path) + common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CheckoutSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CheckoutSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CheckoutSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CheckoutSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CheckoutSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(CheckoutSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(CheckoutSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(CheckoutSettingsServiceClient.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: + CheckoutSettingsServiceAsyncClient: The constructed client. + """ + return CheckoutSettingsServiceClient.from_service_account_info.__func__(CheckoutSettingsServiceAsyncClient, 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: + CheckoutSettingsServiceAsyncClient: The constructed client. + """ + return CheckoutSettingsServiceClient.from_service_account_file.__func__(CheckoutSettingsServiceAsyncClient, 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 CheckoutSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CheckoutSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CheckoutSettingsServiceTransport: 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 = CheckoutSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the checkout settings 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,CheckoutSettingsServiceTransport,Callable[..., CheckoutSettingsServiceTransport]]]): + 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 CheckoutSettingsServiceTransport 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 = CheckoutSettingsServiceClient( + 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.accounts_v1.CheckoutSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "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.accounts.v1.CheckoutSettingsService", + "credentialsType": None, + } + ) + + async def get_checkout_settings(self, + request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + .. 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_accounts_v1 + + async def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetCheckoutSettingsRequest, dict]]): + The request object. Request message for ``GetCheckoutSettings`` method. + name (:class:`str`): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkoutsettings.GetCheckoutSettingsRequest): + request = checkoutsettings.GetCheckoutSettingsRequest(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.get_checkout_settings] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_checkout_settings(self, + request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Creates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1 + + async def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.CreateCheckoutSettingsRequest, dict]]): + The request object. Request message for the ``CreateCheckoutSettings`` + method. + parent (:class:`str`): + Required. The merchant account for which the + ``CheckoutSettings`` will be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + checkout_settings (:class:`google.shopping.merchant_accounts_v1.types.CheckoutSettings`): + Required. The ``CheckoutSettings`` object to create. + This corresponds to the ``checkout_settings`` 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_accounts_v1.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkout_settings] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.CreateCheckoutSettingsRequest): + request = checkoutsettings.CreateCheckoutSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if checkout_settings is not None: + request.checkout_settings = checkout_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_checkout_settings] + + # 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 update_checkout_settings(self, + request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, + *, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Updates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1 + + async def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = await client.update_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateCheckoutSettingsRequest, dict]]): + The request object. Request message for the ``UpdateCheckoutSettings`` + method. + checkout_settings (:class:`google.shopping.merchant_accounts_v1.types.CheckoutSettings`): + Required. The updated version of the + ``CheckoutSettings``. The ``name`` field is used to + identify the ``CheckoutSettings``. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + This corresponds to the ``checkout_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``eligible_destinations`` + - ``uri_settings`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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 = [checkout_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.UpdateCheckoutSettingsRequest): + request = checkoutsettings.UpdateCheckoutSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if checkout_settings is not None: + request.checkout_settings = checkout_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_checkout_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("checkout_settings.name", request.checkout_settings.name), + )), + ) + + # 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_checkout_settings(self, + request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, + *, + name: 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 ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + .. 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_accounts_v1 + + async def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + await client.delete_checkout_settings(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.DeleteCheckoutSettingsRequest, dict]]): + The request object. Request message for the ``DeleteCheckoutSettings`` + method. + name (:class:`str`): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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, checkoutsettings.DeleteCheckoutSettingsRequest): + request = checkoutsettings.DeleteCheckoutSettingsRequest(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_checkout_settings] + + # 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) -> "CheckoutSettingsServiceAsyncClient": + 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__ = ( + "CheckoutSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py new file mode 100644 index 000000000000..f89fd85cd42a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py @@ -0,0 +1,1063 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import checkoutsettings +from google.shopping.type.types import types +from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CheckoutSettingsServiceGrpcTransport +from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport +from .transports.rest import CheckoutSettingsServiceRestTransport + + +class CheckoutSettingsServiceClientMeta(type): + """Metaclass for the CheckoutSettingsService 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[CheckoutSettingsServiceTransport]] + _transport_registry["grpc"] = CheckoutSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CheckoutSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CheckoutSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CheckoutSettingsServiceTransport]: + """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 CheckoutSettingsServiceClient(metaclass=CheckoutSettingsServiceClientMeta): + """Service for supporting `checkout + settings `__. + """ + + @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: + CheckoutSettingsServiceClient: 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: + CheckoutSettingsServiceClient: 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) -> CheckoutSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CheckoutSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def checkout_settings_path(account: str,program: str,) -> str: + """Returns a fully-qualified checkout_settings string.""" + return "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) + + @staticmethod + def parse_checkout_settings_path(path: str) -> Dict[str,str]: + """Parses a checkout_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/programs/(?P.+?)/checkoutSettings$", 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 = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient._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, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the checkout settings 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,CheckoutSettingsServiceTransport,Callable[..., CheckoutSettingsServiceTransport]]]): + 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 CheckoutSettingsServiceTransport 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 = CheckoutSettingsServiceClient._read_environment_variables() + self._client_cert_source = CheckoutSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = CheckoutSettingsServiceClient._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, CheckoutSettingsServiceTransport) + if transport_provided: + # transport is a CheckoutSettingsServiceTransport 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(CheckoutSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + CheckoutSettingsServiceClient._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[CheckoutSettingsServiceTransport], Callable[..., CheckoutSettingsServiceTransport]] = ( + CheckoutSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., CheckoutSettingsServiceTransport], 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.accounts_v1.CheckoutSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "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.accounts.v1.CheckoutSettingsService", + "credentialsType": None, + } + ) + + def get_checkout_settings(self, + request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + .. 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_accounts_v1 + + def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetCheckoutSettingsRequest, dict]): + The request object. Request message for ``GetCheckoutSettings`` method. + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkoutsettings.GetCheckoutSettingsRequest): + request = checkoutsettings.GetCheckoutSettingsRequest(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.get_checkout_settings] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_checkout_settings(self, + request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Creates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1 + + def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.CreateCheckoutSettingsRequest, dict]): + The request object. Request message for the ``CreateCheckoutSettings`` + method. + parent (str): + Required. The merchant account for which the + ``CheckoutSettings`` will be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + checkout_settings (google.shopping.merchant_accounts_v1.types.CheckoutSettings): + Required. The ``CheckoutSettings`` object to create. + This corresponds to the ``checkout_settings`` 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_accounts_v1.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkout_settings] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.CreateCheckoutSettingsRequest): + request = checkoutsettings.CreateCheckoutSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if checkout_settings is not None: + request.checkout_settings = checkout_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_checkout_settings] + + # 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 update_checkout_settings(self, + request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, + *, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Updates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1 + + def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = client.update_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateCheckoutSettingsRequest, dict]): + The request object. Request message for the ``UpdateCheckoutSettings`` + method. + checkout_settings (google.shopping.merchant_accounts_v1.types.CheckoutSettings): + Required. The updated version of the + ``CheckoutSettings``. The ``name`` field is used to + identify the ``CheckoutSettings``. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + This corresponds to the ``checkout_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``eligible_destinations`` + - ``uri_settings`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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 = [checkout_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.UpdateCheckoutSettingsRequest): + request = checkoutsettings.UpdateCheckoutSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if checkout_settings is not None: + request.checkout_settings = checkout_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_checkout_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("checkout_settings.name", request.checkout_settings.name), + )), + ) + + # 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_checkout_settings(self, + request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, + *, + name: 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 ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + .. 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_accounts_v1 + + def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + client.delete_checkout_settings(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.DeleteCheckoutSettingsRequest, dict]): + The request object. Request message for the ``DeleteCheckoutSettings`` + method. + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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, checkoutsettings.DeleteCheckoutSettingsRequest): + request = checkoutsettings.DeleteCheckoutSettingsRequest(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_checkout_settings] + + # 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) -> "CheckoutSettingsServiceClient": + 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__ = ( + "CheckoutSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst new file mode 100644 index 000000000000..95c14e3fa6f8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CheckoutSettingsServiceTransport` is the ABC for all transports. +- public child `CheckoutSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CheckoutSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCheckoutSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CheckoutSettingsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py new file mode 100644 index 000000000000..e319afd3cf0a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_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 CheckoutSettingsServiceTransport +from .grpc import CheckoutSettingsServiceGrpcTransport +from .grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport +from .rest import CheckoutSettingsServiceRestTransport +from .rest import CheckoutSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CheckoutSettingsServiceTransport]] +_transport_registry['grpc'] = CheckoutSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CheckoutSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = CheckoutSettingsServiceRestTransport + +__all__ = ( + 'CheckoutSettingsServiceTransport', + 'CheckoutSettingsServiceGrpcTransport', + 'CheckoutSettingsServiceGrpcAsyncIOTransport', + 'CheckoutSettingsServiceRestTransport', + 'CheckoutSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py new file mode 100644 index 000000000000..4b512fc233f2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py @@ -0,0 +1,202 @@ +# -*- 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_accounts_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_accounts_v1.types import checkoutsettings + +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 CheckoutSettingsServiceTransport(abc.ABC): + """Abstract transport class for CheckoutSettingsService.""" + + 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.get_checkout_settings: gapic_v1.method.wrap_method( + self.get_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_checkout_settings: gapic_v1.method.wrap_method( + self.create_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_checkout_settings: gapic_v1.method.wrap_method( + self.update_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_checkout_settings: gapic_v1.method.wrap_method( + self.delete_checkout_settings, + 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 get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings] + ]]: + raise NotImplementedError() + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings] + ]]: + raise NotImplementedError() + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings] + ]]: + raise NotImplementedError() + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CheckoutSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py new file mode 100644 index 000000000000..c7b4de46ebd4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py @@ -0,0 +1,429 @@ +# -*- 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_accounts_v1.types import checkoutsettings +from .base import CheckoutSettingsServiceTransport, 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.accounts.v1.CheckoutSettingsService", + "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.accounts.v1.CheckoutSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class CheckoutSettingsServiceGrpcTransport(CheckoutSettingsServiceTransport): + """gRPC backend transport for CheckoutSettingsService. + + Service for supporting `checkout + settings `__. + + 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 get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + r"""Return a callable for the get checkout settings method over gRPC. + + Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + Returns: + Callable[[~.GetCheckoutSettingsRequest], + ~.CheckoutSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_checkout_settings' not in self._stubs: + self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/GetCheckoutSettings', + request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['get_checkout_settings'] + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + r"""Return a callable for the create checkout settings method over gRPC. + + Creates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.CreateCheckoutSettingsRequest], + ~.CheckoutSettings]: + 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 'create_checkout_settings' not in self._stubs: + self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/CreateCheckoutSettings', + request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['create_checkout_settings'] + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + r"""Return a callable for the update checkout settings method over gRPC. + + Updates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.UpdateCheckoutSettingsRequest], + ~.CheckoutSettings]: + 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 'update_checkout_settings' not in self._stubs: + self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/UpdateCheckoutSettings', + request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['update_checkout_settings'] + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete checkout settings method over gRPC. + + Deletes ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + Returns: + Callable[[~.DeleteCheckoutSettingsRequest], + ~.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_checkout_settings' not in self._stubs: + self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/DeleteCheckoutSettings', + request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_checkout_settings'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CheckoutSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..a7ff8012c889 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,465 @@ +# -*- 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_accounts_v1.types import checkoutsettings +from .base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CheckoutSettingsServiceGrpcTransport + +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.accounts.v1.CheckoutSettingsService", + "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.accounts.v1.CheckoutSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class CheckoutSettingsServiceGrpcAsyncIOTransport(CheckoutSettingsServiceTransport): + """gRPC AsyncIO backend transport for CheckoutSettingsService. + + Service for supporting `checkout + settings `__. + + 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 get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings]]: + r"""Return a callable for the get checkout settings method over gRPC. + + Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + Returns: + Callable[[~.GetCheckoutSettingsRequest], + Awaitable[~.CheckoutSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_checkout_settings' not in self._stubs: + self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/GetCheckoutSettings', + request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['get_checkout_settings'] + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings]]: + r"""Return a callable for the create checkout settings method over gRPC. + + Creates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.CreateCheckoutSettingsRequest], + Awaitable[~.CheckoutSettings]]: + 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 'create_checkout_settings' not in self._stubs: + self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/CreateCheckoutSettings', + request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['create_checkout_settings'] + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings]]: + r"""Return a callable for the update checkout settings method over gRPC. + + Updates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.UpdateCheckoutSettingsRequest], + Awaitable[~.CheckoutSettings]]: + 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 'update_checkout_settings' not in self._stubs: + self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/UpdateCheckoutSettings', + request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['update_checkout_settings'] + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete checkout settings method over gRPC. + + Deletes ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + Returns: + Callable[[~.DeleteCheckoutSettingsRequest], + 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_checkout_settings' not in self._stubs: + self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/DeleteCheckoutSettings', + request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_checkout_settings'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_checkout_settings: self._wrap_method( + self.get_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_checkout_settings: self._wrap_method( + self.create_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_checkout_settings: self._wrap_method( + self.update_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_checkout_settings: self._wrap_method( + self.delete_checkout_settings, + 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__ = ( + 'CheckoutSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py new file mode 100644 index 000000000000..fb7a3b6b9e44 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py @@ -0,0 +1,815 @@ +# -*- 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_accounts_v1.types import checkoutsettings + + +from .rest_base import _BaseCheckoutSettingsServiceRestTransport +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 CheckoutSettingsServiceRestInterceptor: + """Interceptor for CheckoutSettingsService. + + 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 CheckoutSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomCheckoutSettingsServiceInterceptor(CheckoutSettingsServiceRestInterceptor): + def pre_create_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_checkout_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_checkout_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_checkout_settings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CheckoutSettingsServiceRestTransport(interceptor=MyCustomCheckoutSettingsServiceInterceptor()) + client = CheckoutSettingsServiceClient(transport=transport) + + + """ + def pre_create_checkout_settings(self, request: checkoutsettings.CreateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CreateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def post_create_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + """Post-rpc interceptor for create_checkout_settings + + DEPRECATED. Please use the `post_create_checkout_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CheckoutSettingsService server but before + it is returned to user code. This `post_create_checkout_settings` interceptor runs + before the `post_create_checkout_settings_with_metadata` interceptor. + """ + return response + + def post_create_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_checkout_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CheckoutSettingsService server but before it is returned to user code. + + We recommend only using this `post_create_checkout_settings_with_metadata` + interceptor in new development instead of the `post_create_checkout_settings` interceptor. + When both interceptors are used, this `post_create_checkout_settings_with_metadata` interceptor runs after the + `post_create_checkout_settings` interceptor. The (possibly modified) response returned by + `post_create_checkout_settings` will be passed to + `post_create_checkout_settings_with_metadata`. + """ + return response, metadata + + def pre_delete_checkout_settings(self, request: checkoutsettings.DeleteCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.DeleteCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def pre_get_checkout_settings(self, request: checkoutsettings.GetCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.GetCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def post_get_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + """Post-rpc interceptor for get_checkout_settings + + DEPRECATED. Please use the `post_get_checkout_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CheckoutSettingsService server but before + it is returned to user code. This `post_get_checkout_settings` interceptor runs + before the `post_get_checkout_settings_with_metadata` interceptor. + """ + return response + + def post_get_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_checkout_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CheckoutSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_checkout_settings_with_metadata` + interceptor in new development instead of the `post_get_checkout_settings` interceptor. + When both interceptors are used, this `post_get_checkout_settings_with_metadata` interceptor runs after the + `post_get_checkout_settings` interceptor. The (possibly modified) response returned by + `post_get_checkout_settings` will be passed to + `post_get_checkout_settings_with_metadata`. + """ + return response, metadata + + def pre_update_checkout_settings(self, request: checkoutsettings.UpdateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.UpdateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def post_update_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + """Post-rpc interceptor for update_checkout_settings + + DEPRECATED. Please use the `post_update_checkout_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CheckoutSettingsService server but before + it is returned to user code. This `post_update_checkout_settings` interceptor runs + before the `post_update_checkout_settings_with_metadata` interceptor. + """ + return response + + def post_update_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_checkout_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CheckoutSettingsService server but before it is returned to user code. + + We recommend only using this `post_update_checkout_settings_with_metadata` + interceptor in new development instead of the `post_update_checkout_settings` interceptor. + When both interceptors are used, this `post_update_checkout_settings_with_metadata` interceptor runs after the + `post_update_checkout_settings` interceptor. The (possibly modified) response returned by + `post_update_checkout_settings` will be passed to + `post_update_checkout_settings_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class CheckoutSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CheckoutSettingsServiceRestInterceptor + + +class CheckoutSettingsServiceRestTransport(_BaseCheckoutSettingsServiceRestTransport): + """REST backend synchronous transport for CheckoutSettingsService. + + Service for supporting `checkout + settings `__. + + 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[CheckoutSettingsServiceRestInterceptor] = 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 CheckoutSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.CreateCheckoutSettings") + + @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: checkoutsettings.CreateCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> checkoutsettings.CheckoutSettings: + r"""Call the create checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.CreateCheckoutSettingsRequest): + The request object. Request message for the ``CreateCheckoutSettings`` + 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: + ~.checkoutsettings.CheckoutSettings: + `CheckoutSettings `__ + for a specific merchant. + + """ + + http_options = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_create_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_transcoded_request(http_options, request) + + body = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.CreateCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "CreateCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._CreateCheckoutSettings._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 = checkoutsettings.CheckoutSettings() + pb_resp = checkoutsettings.CheckoutSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_checkout_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_checkout_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1.CheckoutSettingsServiceClient.create_checkout_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "CreateCheckoutSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.DeleteCheckoutSettings") + + @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: checkoutsettings.DeleteCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.DeleteCheckoutSettingsRequest): + The request object. Request message for the ``DeleteCheckoutSettings`` + 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 = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_delete_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.DeleteCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "DeleteCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._DeleteCheckoutSettings._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 _GetCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.GetCheckoutSettings") + + @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: checkoutsettings.GetCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> checkoutsettings.CheckoutSettings: + r"""Call the get checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.GetCheckoutSettingsRequest): + The request object. Request message for ``GetCheckoutSettings`` 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: + ~.checkoutsettings.CheckoutSettings: + `CheckoutSettings `__ + for a specific merchant. + + """ + + http_options = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_get_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.GetCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "GetCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._GetCheckoutSettings._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 = checkoutsettings.CheckoutSettings() + pb_resp = checkoutsettings.CheckoutSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_checkout_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_checkout_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1.CheckoutSettingsServiceClient.get_checkout_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "GetCheckoutSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.UpdateCheckoutSettings") + + @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: checkoutsettings.UpdateCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> checkoutsettings.CheckoutSettings: + r"""Call the update checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.UpdateCheckoutSettingsRequest): + The request object. Request message for the ``UpdateCheckoutSettings`` + 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: + ~.checkoutsettings.CheckoutSettings: + `CheckoutSettings `__ + for a specific merchant. + + """ + + http_options = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_update_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_transcoded_request(http_options, request) + + body = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.UpdateCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "UpdateCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._UpdateCheckoutSettings._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 = checkoutsettings.CheckoutSettings() + pb_resp = checkoutsettings.CheckoutSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_checkout_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_checkout_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1.CheckoutSettingsServiceClient.update_checkout_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "rpcName": "UpdateCheckoutSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + # 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._CreateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + 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._DeleteCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + # 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._GetCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + # 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._UpdateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'CheckoutSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..1add45fb12e2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py @@ -0,0 +1,260 @@ +# -*- 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 CheckoutSettingsServiceTransport, 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_accounts_v1.types import checkoutsettings + + +class _BaseCheckoutSettingsServiceRestTransport(CheckoutSettingsServiceTransport): + """Base REST backend transport for CheckoutSettingsService. + + 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 _BaseCreateCheckoutSettings: + 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': '/accounts/v1/{parent=accounts/*/programs/*}/checkoutSettings', + 'body': 'checkout_settings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.CreateCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCheckoutSettings: + 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': '/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.DeleteCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCheckoutSettings: + 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': '/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.GetCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCheckoutSettings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}', + 'body': 'checkout_settings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.UpdateCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseCheckoutSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py new file mode 100644 index 000000000000..ccbe5e8935bc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_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 DeveloperRegistrationServiceClient +from .async_client import DeveloperRegistrationServiceAsyncClient + +__all__ = ( + 'DeveloperRegistrationServiceClient', + 'DeveloperRegistrationServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py new file mode 100644 index 000000000000..408ff307a080 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py @@ -0,0 +1,533 @@ +# -*- 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_accounts_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_accounts_v1.types import developerregistration +from .transports.base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport +from .client import DeveloperRegistrationServiceClient + +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 DeveloperRegistrationServiceAsyncClient: + """Service to access Developer Registration.""" + + _client: DeveloperRegistrationServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = DeveloperRegistrationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + + developer_registration_path = staticmethod(DeveloperRegistrationServiceClient.developer_registration_path) + parse_developer_registration_path = staticmethod(DeveloperRegistrationServiceClient.parse_developer_registration_path) + common_billing_account_path = staticmethod(DeveloperRegistrationServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DeveloperRegistrationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DeveloperRegistrationServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DeveloperRegistrationServiceClient.common_project_path) + parse_common_project_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_project_path) + common_location_path = staticmethod(DeveloperRegistrationServiceClient.common_location_path) + parse_common_location_path = staticmethod(DeveloperRegistrationServiceClient.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: + DeveloperRegistrationServiceAsyncClient: The constructed client. + """ + return DeveloperRegistrationServiceClient.from_service_account_info.__func__(DeveloperRegistrationServiceAsyncClient, 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: + DeveloperRegistrationServiceAsyncClient: The constructed client. + """ + return DeveloperRegistrationServiceClient.from_service_account_file.__func__(DeveloperRegistrationServiceAsyncClient, 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 DeveloperRegistrationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DeveloperRegistrationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DeveloperRegistrationServiceTransport: 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 = DeveloperRegistrationServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DeveloperRegistrationServiceTransport, Callable[..., DeveloperRegistrationServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the developer registration 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,DeveloperRegistrationServiceTransport,Callable[..., DeveloperRegistrationServiceTransport]]]): + 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 DeveloperRegistrationServiceTransport 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 = DeveloperRegistrationServiceClient( + 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.accounts_v1.DeveloperRegistrationServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "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.accounts.v1.DeveloperRegistrationService", + "credentialsType": None, + } + ) + + async def register_gcp(self, + request: Optional[Union[developerregistration.RegisterGcpRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: + r"""Registers the GCP used for the API call to the shopping account + passed in the request. Will create a user with an "API + developer" and add the "developer_email" as a contact with "API + notifications" email preference on. + + .. 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_accounts_v1 + + async def sample_register_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RegisterGcpRequest( + name="name_value", + ) + + # Make the request + response = await client.register_gcp(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.RegisterGcpRequest, dict]]): + The request object. Request message for the RegisterGCP + 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_accounts_v1.types.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. + + """ + # 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, developerregistration.RegisterGcpRequest): + request = developerregistration.RegisterGcpRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.register_gcp] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_developer_registration(self, + request: Optional[Union[developerregistration.GetDeveloperRegistrationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: + r"""Retrieves a developer registration for a merchant. + + .. 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_accounts_v1 + + async def sample_get_developer_registration(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetDeveloperRegistrationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_developer_registration(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetDeveloperRegistrationRequest, dict]]): + The request object. Request message for the + GetDeveloperRegistration method. + name (:class:`str`): + Required. The ``name`` (ID) of the developer + registration. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. + + """ + # 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, developerregistration.GetDeveloperRegistrationRequest): + request = developerregistration.GetDeveloperRegistrationRequest(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.get_developer_registration] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def unregister_gcp(self, + request: Optional[Union[developerregistration.UnregisterGcpRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Unregister the calling GCP from the calling shopping + account. Note that the GCP will still be able to access + the API for at most 1 day from the unregister succussful + call. + + .. 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_accounts_v1 + + async def sample_unregister_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnregisterGcpRequest( + name="name_value", + ) + + # Make the request + await client.unregister_gcp(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UnregisterGcpRequest, dict]]): + The request object. Request message for the UnregisterGCP + 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`. + """ + # 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, developerregistration.UnregisterGcpRequest): + request = developerregistration.UnregisterGcpRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.unregister_gcp] + + # 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) -> "DeveloperRegistrationServiceAsyncClient": + 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__ = ( + "DeveloperRegistrationServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py new file mode 100644 index 000000000000..5ae1c105c7a1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py @@ -0,0 +1,893 @@ +# -*- 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_accounts_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_accounts_v1.types import developerregistration +from .transports.base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DeveloperRegistrationServiceGrpcTransport +from .transports.grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport +from .transports.rest import DeveloperRegistrationServiceRestTransport + + +class DeveloperRegistrationServiceClientMeta(type): + """Metaclass for the DeveloperRegistrationService 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[DeveloperRegistrationServiceTransport]] + _transport_registry["grpc"] = DeveloperRegistrationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DeveloperRegistrationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DeveloperRegistrationServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DeveloperRegistrationServiceTransport]: + """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 DeveloperRegistrationServiceClient(metaclass=DeveloperRegistrationServiceClientMeta): + """Service to access Developer Registration.""" + + @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: + DeveloperRegistrationServiceClient: 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: + DeveloperRegistrationServiceClient: 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) -> DeveloperRegistrationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DeveloperRegistrationServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def developer_registration_path(account: str,) -> str: + """Returns a fully-qualified developer_registration string.""" + return "accounts/{account}/developerRegistration".format(account=account, ) + + @staticmethod + def parse_developer_registration_path(path: str) -> Dict[str,str]: + """Parses a developer_registration path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/developerRegistration$", 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 = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = DeveloperRegistrationServiceClient._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 = DeveloperRegistrationServiceClient._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, DeveloperRegistrationServiceTransport, Callable[..., DeveloperRegistrationServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the developer registration 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,DeveloperRegistrationServiceTransport,Callable[..., DeveloperRegistrationServiceTransport]]]): + 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 DeveloperRegistrationServiceTransport 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 = DeveloperRegistrationServiceClient._read_environment_variables() + self._client_cert_source = DeveloperRegistrationServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = DeveloperRegistrationServiceClient._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, DeveloperRegistrationServiceTransport) + if transport_provided: + # transport is a DeveloperRegistrationServiceTransport 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(DeveloperRegistrationServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + DeveloperRegistrationServiceClient._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[DeveloperRegistrationServiceTransport], Callable[..., DeveloperRegistrationServiceTransport]] = ( + DeveloperRegistrationServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DeveloperRegistrationServiceTransport], 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.accounts_v1.DeveloperRegistrationServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "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.accounts.v1.DeveloperRegistrationService", + "credentialsType": None, + } + ) + + def register_gcp(self, + request: Optional[Union[developerregistration.RegisterGcpRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: + r"""Registers the GCP used for the API call to the shopping account + passed in the request. Will create a user with an "API + developer" and add the "developer_email" as a contact with "API + notifications" email preference on. + + .. 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_accounts_v1 + + def sample_register_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RegisterGcpRequest( + name="name_value", + ) + + # Make the request + response = client.register_gcp(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.RegisterGcpRequest, dict]): + The request object. Request message for the RegisterGCP + 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_accounts_v1.types.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. + + """ + # 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, developerregistration.RegisterGcpRequest): + request = developerregistration.RegisterGcpRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.register_gcp] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_developer_registration(self, + request: Optional[Union[developerregistration.GetDeveloperRegistrationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: + r"""Retrieves a developer registration for a merchant. + + .. 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_accounts_v1 + + def sample_get_developer_registration(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetDeveloperRegistrationRequest( + name="name_value", + ) + + # Make the request + response = client.get_developer_registration(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetDeveloperRegistrationRequest, dict]): + The request object. Request message for the + GetDeveloperRegistration method. + name (str): + Required. The ``name`` (ID) of the developer + registration. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. + + """ + # 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, developerregistration.GetDeveloperRegistrationRequest): + request = developerregistration.GetDeveloperRegistrationRequest(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.get_developer_registration] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def unregister_gcp(self, + request: Optional[Union[developerregistration.UnregisterGcpRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Unregister the calling GCP from the calling shopping + account. Note that the GCP will still be able to access + the API for at most 1 day from the unregister succussful + call. + + .. 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_accounts_v1 + + def sample_unregister_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnregisterGcpRequest( + name="name_value", + ) + + # Make the request + client.unregister_gcp(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UnregisterGcpRequest, dict]): + The request object. Request message for the UnregisterGCP + 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`. + """ + # 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, developerregistration.UnregisterGcpRequest): + request = developerregistration.UnregisterGcpRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.unregister_gcp] + + # 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) -> "DeveloperRegistrationServiceClient": + 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__ = ( + "DeveloperRegistrationServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst new file mode 100644 index 000000000000..12a092f156bb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`DeveloperRegistrationServiceTransport` is the ABC for all transports. +- public child `DeveloperRegistrationServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `DeveloperRegistrationServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseDeveloperRegistrationServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `DeveloperRegistrationServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py new file mode 100644 index 000000000000..d6f2a783cf1f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_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 DeveloperRegistrationServiceTransport +from .grpc import DeveloperRegistrationServiceGrpcTransport +from .grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport +from .rest import DeveloperRegistrationServiceRestTransport +from .rest import DeveloperRegistrationServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DeveloperRegistrationServiceTransport]] +_transport_registry['grpc'] = DeveloperRegistrationServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DeveloperRegistrationServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DeveloperRegistrationServiceRestTransport + +__all__ = ( + 'DeveloperRegistrationServiceTransport', + 'DeveloperRegistrationServiceGrpcTransport', + 'DeveloperRegistrationServiceGrpcAsyncIOTransport', + 'DeveloperRegistrationServiceRestTransport', + 'DeveloperRegistrationServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py new file mode 100644 index 000000000000..ac935c33c08f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_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_accounts_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_accounts_v1.types import developerregistration + +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 DeveloperRegistrationServiceTransport(abc.ABC): + """Abstract transport class for DeveloperRegistrationService.""" + + 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.register_gcp: gapic_v1.method.wrap_method( + self.register_gcp, + default_timeout=None, + client_info=client_info, + ), + self.get_developer_registration: gapic_v1.method.wrap_method( + self.get_developer_registration, + default_timeout=None, + client_info=client_info, + ), + self.unregister_gcp: gapic_v1.method.wrap_method( + self.unregister_gcp, + 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 register_gcp(self) -> Callable[ + [developerregistration.RegisterGcpRequest], + Union[ + developerregistration.DeveloperRegistration, + Awaitable[developerregistration.DeveloperRegistration] + ]]: + raise NotImplementedError() + + @property + def get_developer_registration(self) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + Union[ + developerregistration.DeveloperRegistration, + Awaitable[developerregistration.DeveloperRegistration] + ]]: + raise NotImplementedError() + + @property + def unregister_gcp(self) -> Callable[ + [developerregistration.UnregisterGcpRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DeveloperRegistrationServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py new file mode 100644 index 000000000000..4816cd413bfd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py @@ -0,0 +1,405 @@ +# -*- 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_accounts_v1.types import developerregistration +from .base import DeveloperRegistrationServiceTransport, 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.accounts.v1.DeveloperRegistrationService", + "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.accounts.v1.DeveloperRegistrationService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DeveloperRegistrationServiceGrpcTransport(DeveloperRegistrationServiceTransport): + """gRPC backend transport for DeveloperRegistrationService. + + Service to access Developer Registration. + + 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 register_gcp(self) -> Callable[ + [developerregistration.RegisterGcpRequest], + developerregistration.DeveloperRegistration]: + r"""Return a callable for the register gcp method over gRPC. + + Registers the GCP used for the API call to the shopping account + passed in the request. Will create a user with an "API + developer" and add the "developer_email" as a contact with "API + notifications" email preference on. + + Returns: + Callable[[~.RegisterGcpRequest], + ~.DeveloperRegistration]: + 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 'register_gcp' not in self._stubs: + self._stubs['register_gcp'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/RegisterGcp', + request_serializer=developerregistration.RegisterGcpRequest.serialize, + response_deserializer=developerregistration.DeveloperRegistration.deserialize, + ) + return self._stubs['register_gcp'] + + @property + def get_developer_registration(self) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + developerregistration.DeveloperRegistration]: + r"""Return a callable for the get developer registration method over gRPC. + + Retrieves a developer registration for a merchant. + + Returns: + Callable[[~.GetDeveloperRegistrationRequest], + ~.DeveloperRegistration]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_developer_registration' not in self._stubs: + self._stubs['get_developer_registration'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/GetDeveloperRegistration', + request_serializer=developerregistration.GetDeveloperRegistrationRequest.serialize, + response_deserializer=developerregistration.DeveloperRegistration.deserialize, + ) + return self._stubs['get_developer_registration'] + + @property + def unregister_gcp(self) -> Callable[ + [developerregistration.UnregisterGcpRequest], + empty_pb2.Empty]: + r"""Return a callable for the unregister gcp method over gRPC. + + Unregister the calling GCP from the calling shopping + account. Note that the GCP will still be able to access + the API for at most 1 day from the unregister succussful + call. + + Returns: + Callable[[~.UnregisterGcpRequest], + ~.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 'unregister_gcp' not in self._stubs: + self._stubs['unregister_gcp'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/UnregisterGcp', + request_serializer=developerregistration.UnregisterGcpRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['unregister_gcp'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DeveloperRegistrationServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..807deb598ada --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py @@ -0,0 +1,436 @@ +# -*- 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_accounts_v1.types import developerregistration +from .base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DeveloperRegistrationServiceGrpcTransport + +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.accounts.v1.DeveloperRegistrationService", + "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.accounts.v1.DeveloperRegistrationService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class DeveloperRegistrationServiceGrpcAsyncIOTransport(DeveloperRegistrationServiceTransport): + """gRPC AsyncIO backend transport for DeveloperRegistrationService. + + Service to access Developer Registration. + + 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 register_gcp(self) -> Callable[ + [developerregistration.RegisterGcpRequest], + Awaitable[developerregistration.DeveloperRegistration]]: + r"""Return a callable for the register gcp method over gRPC. + + Registers the GCP used for the API call to the shopping account + passed in the request. Will create a user with an "API + developer" and add the "developer_email" as a contact with "API + notifications" email preference on. + + Returns: + Callable[[~.RegisterGcpRequest], + Awaitable[~.DeveloperRegistration]]: + 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 'register_gcp' not in self._stubs: + self._stubs['register_gcp'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/RegisterGcp', + request_serializer=developerregistration.RegisterGcpRequest.serialize, + response_deserializer=developerregistration.DeveloperRegistration.deserialize, + ) + return self._stubs['register_gcp'] + + @property + def get_developer_registration(self) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + Awaitable[developerregistration.DeveloperRegistration]]: + r"""Return a callable for the get developer registration method over gRPC. + + Retrieves a developer registration for a merchant. + + Returns: + Callable[[~.GetDeveloperRegistrationRequest], + Awaitable[~.DeveloperRegistration]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_developer_registration' not in self._stubs: + self._stubs['get_developer_registration'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/GetDeveloperRegistration', + request_serializer=developerregistration.GetDeveloperRegistrationRequest.serialize, + response_deserializer=developerregistration.DeveloperRegistration.deserialize, + ) + return self._stubs['get_developer_registration'] + + @property + def unregister_gcp(self) -> Callable[ + [developerregistration.UnregisterGcpRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the unregister gcp method over gRPC. + + Unregister the calling GCP from the calling shopping + account. Note that the GCP will still be able to access + the API for at most 1 day from the unregister succussful + call. + + Returns: + Callable[[~.UnregisterGcpRequest], + 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 'unregister_gcp' not in self._stubs: + self._stubs['unregister_gcp'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/UnregisterGcp', + request_serializer=developerregistration.UnregisterGcpRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['unregister_gcp'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.register_gcp: self._wrap_method( + self.register_gcp, + default_timeout=None, + client_info=client_info, + ), + self.get_developer_registration: self._wrap_method( + self.get_developer_registration, + default_timeout=None, + client_info=client_info, + ), + self.unregister_gcp: self._wrap_method( + self.unregister_gcp, + 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__ = ( + 'DeveloperRegistrationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py new file mode 100644 index 000000000000..652e8e0bc6dd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py @@ -0,0 +1,642 @@ +# -*- 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_accounts_v1.types import developerregistration + + +from .rest_base import _BaseDeveloperRegistrationServiceRestTransport +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 DeveloperRegistrationServiceRestInterceptor: + """Interceptor for DeveloperRegistrationService. + + 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 DeveloperRegistrationServiceRestTransport. + + .. code-block:: python + class MyCustomDeveloperRegistrationServiceInterceptor(DeveloperRegistrationServiceRestInterceptor): + def pre_get_developer_registration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_developer_registration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_register_gcp(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_register_gcp(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_unregister_gcp(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + transport = DeveloperRegistrationServiceRestTransport(interceptor=MyCustomDeveloperRegistrationServiceInterceptor()) + client = DeveloperRegistrationServiceClient(transport=transport) + + + """ + def pre_get_developer_registration(self, request: developerregistration.GetDeveloperRegistrationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.GetDeveloperRegistrationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_developer_registration + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperRegistrationService server. + """ + return request, metadata + + def post_get_developer_registration(self, response: developerregistration.DeveloperRegistration) -> developerregistration.DeveloperRegistration: + """Post-rpc interceptor for get_developer_registration + + DEPRECATED. Please use the `post_get_developer_registration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperRegistrationService server but before + it is returned to user code. This `post_get_developer_registration` interceptor runs + before the `post_get_developer_registration_with_metadata` interceptor. + """ + return response + + def post_get_developer_registration_with_metadata(self, response: developerregistration.DeveloperRegistration, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.DeveloperRegistration, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_developer_registration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperRegistrationService server but before it is returned to user code. + + We recommend only using this `post_get_developer_registration_with_metadata` + interceptor in new development instead of the `post_get_developer_registration` interceptor. + When both interceptors are used, this `post_get_developer_registration_with_metadata` interceptor runs after the + `post_get_developer_registration` interceptor. The (possibly modified) response returned by + `post_get_developer_registration` will be passed to + `post_get_developer_registration_with_metadata`. + """ + return response, metadata + + def pre_register_gcp(self, request: developerregistration.RegisterGcpRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.RegisterGcpRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for register_gcp + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperRegistrationService server. + """ + return request, metadata + + def post_register_gcp(self, response: developerregistration.DeveloperRegistration) -> developerregistration.DeveloperRegistration: + """Post-rpc interceptor for register_gcp + + DEPRECATED. Please use the `post_register_gcp_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperRegistrationService server but before + it is returned to user code. This `post_register_gcp` interceptor runs + before the `post_register_gcp_with_metadata` interceptor. + """ + return response + + def post_register_gcp_with_metadata(self, response: developerregistration.DeveloperRegistration, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.DeveloperRegistration, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for register_gcp + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperRegistrationService server but before it is returned to user code. + + We recommend only using this `post_register_gcp_with_metadata` + interceptor in new development instead of the `post_register_gcp` interceptor. + When both interceptors are used, this `post_register_gcp_with_metadata` interceptor runs after the + `post_register_gcp` interceptor. The (possibly modified) response returned by + `post_register_gcp` will be passed to + `post_register_gcp_with_metadata`. + """ + return response, metadata + + def pre_unregister_gcp(self, request: developerregistration.UnregisterGcpRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.UnregisterGcpRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for unregister_gcp + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperRegistrationService server. + """ + return request, metadata + + +@dataclasses.dataclass +class DeveloperRegistrationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DeveloperRegistrationServiceRestInterceptor + + +class DeveloperRegistrationServiceRestTransport(_BaseDeveloperRegistrationServiceRestTransport): + """REST backend synchronous transport for DeveloperRegistrationService. + + Service to access Developer Registration. + + 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[DeveloperRegistrationServiceRestInterceptor] = 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 DeveloperRegistrationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetDeveloperRegistration(_BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration, DeveloperRegistrationServiceRestStub): + def __hash__(self): + return hash("DeveloperRegistrationServiceRestTransport.GetDeveloperRegistration") + + @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: developerregistration.GetDeveloperRegistrationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> developerregistration.DeveloperRegistration: + r"""Call the get developer + registration method over HTTP. + + Args: + request (~.developerregistration.GetDeveloperRegistrationRequest): + The request object. Request message for the + GetDeveloperRegistration 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: + ~.developerregistration.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. + + """ + + http_options = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_http_options() + + request, metadata = self._interceptor.pre_get_developer_registration(request, metadata) + transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.DeveloperRegistrationServiceClient.GetDeveloperRegistration", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "rpcName": "GetDeveloperRegistration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperRegistrationServiceRestTransport._GetDeveloperRegistration._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 = developerregistration.DeveloperRegistration() + pb_resp = developerregistration.DeveloperRegistration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_developer_registration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_developer_registration_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = developerregistration.DeveloperRegistration.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.accounts_v1.DeveloperRegistrationServiceClient.get_developer_registration", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "rpcName": "GetDeveloperRegistration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RegisterGcp(_BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp, DeveloperRegistrationServiceRestStub): + def __hash__(self): + return hash("DeveloperRegistrationServiceRestTransport.RegisterGcp") + + @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: developerregistration.RegisterGcpRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> developerregistration.DeveloperRegistration: + r"""Call the register gcp method over HTTP. + + Args: + request (~.developerregistration.RegisterGcpRequest): + The request object. Request message for the RegisterGCP + 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: + ~.developerregistration.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. + + """ + + http_options = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_http_options() + + request, metadata = self._interceptor.pre_register_gcp(request, metadata) + transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_transcoded_request(http_options, request) + + body = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.DeveloperRegistrationServiceClient.RegisterGcp", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "rpcName": "RegisterGcp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperRegistrationServiceRestTransport._RegisterGcp._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 = developerregistration.DeveloperRegistration() + pb_resp = developerregistration.DeveloperRegistration.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_register_gcp(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_register_gcp_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = developerregistration.DeveloperRegistration.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.accounts_v1.DeveloperRegistrationServiceClient.register_gcp", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "rpcName": "RegisterGcp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UnregisterGcp(_BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp, DeveloperRegistrationServiceRestStub): + def __hash__(self): + return hash("DeveloperRegistrationServiceRestTransport.UnregisterGcp") + + @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: developerregistration.UnregisterGcpRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the unregister gcp method over HTTP. + + Args: + request (~.developerregistration.UnregisterGcpRequest): + The request object. Request message for the UnregisterGCP + 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 = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_http_options() + + request, metadata = self._interceptor.pre_unregister_gcp(request, metadata) + transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_transcoded_request(http_options, request) + + body = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.DeveloperRegistrationServiceClient.UnregisterGcp", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "rpcName": "UnregisterGcp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperRegistrationServiceRestTransport._UnregisterGcp._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) + + @property + def get_developer_registration(self) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + developerregistration.DeveloperRegistration]: + # 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._GetDeveloperRegistration(self._session, self._host, self._interceptor) # type: ignore + + @property + def register_gcp(self) -> Callable[ + [developerregistration.RegisterGcpRequest], + developerregistration.DeveloperRegistration]: + # 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._RegisterGcp(self._session, self._host, self._interceptor) # type: ignore + + @property + def unregister_gcp(self) -> Callable[ + [developerregistration.UnregisterGcpRequest], + 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._UnregisterGcp(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DeveloperRegistrationServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py new file mode 100644 index 000000000000..5cf6937a4b0e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py @@ -0,0 +1,223 @@ +# -*- 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 DeveloperRegistrationServiceTransport, 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_accounts_v1.types import developerregistration + + +class _BaseDeveloperRegistrationServiceRestTransport(DeveloperRegistrationServiceTransport): + """Base REST backend transport for DeveloperRegistrationService. + + 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 _BaseGetDeveloperRegistration: + 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': '/accounts/v1/{name=accounts/*/developerRegistration}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = developerregistration.GetDeveloperRegistrationRequest.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(_BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRegisterGcp: + 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': '/accounts/v1/{name=accounts/*/developerRegistration}:registerGcp', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = developerregistration.RegisterGcpRequest.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(_BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUnregisterGcp: + 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': '/accounts/v1/{name=accounts/*/developerRegistration}:unregisterGcp', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = developerregistration.UnregisterGcpRequest.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(_BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseDeveloperRegistrationServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py new file mode 100644 index 000000000000..d5ee3fce97c1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_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 EmailPreferencesServiceClient +from .async_client import EmailPreferencesServiceAsyncClient + +__all__ = ( + 'EmailPreferencesServiceClient', + 'EmailPreferencesServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py new file mode 100644 index 000000000000..bba2855beda3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py @@ -0,0 +1,511 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import emailpreferences +from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport +from .client import EmailPreferencesServiceClient + +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 EmailPreferencesServiceAsyncClient: + """Service to support the ``EmailPreferences`` API.""" + + _client: EmailPreferencesServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + + email_preferences_path = staticmethod(EmailPreferencesServiceClient.email_preferences_path) + parse_email_preferences_path = staticmethod(EmailPreferencesServiceClient.parse_email_preferences_path) + common_billing_account_path = staticmethod(EmailPreferencesServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EmailPreferencesServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EmailPreferencesServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(EmailPreferencesServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(EmailPreferencesServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(EmailPreferencesServiceClient.parse_common_organization_path) + common_project_path = staticmethod(EmailPreferencesServiceClient.common_project_path) + parse_common_project_path = staticmethod(EmailPreferencesServiceClient.parse_common_project_path) + common_location_path = staticmethod(EmailPreferencesServiceClient.common_location_path) + parse_common_location_path = staticmethod(EmailPreferencesServiceClient.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: + EmailPreferencesServiceAsyncClient: The constructed client. + """ + return EmailPreferencesServiceClient.from_service_account_info.__func__(EmailPreferencesServiceAsyncClient, 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: + EmailPreferencesServiceAsyncClient: The constructed client. + """ + return EmailPreferencesServiceClient.from_service_account_file.__func__(EmailPreferencesServiceAsyncClient, 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 EmailPreferencesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EmailPreferencesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EmailPreferencesServiceTransport: 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 = EmailPreferencesServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the email preferences 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,EmailPreferencesServiceTransport,Callable[..., EmailPreferencesServiceTransport]]]): + 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 EmailPreferencesServiceTransport 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 = EmailPreferencesServiceClient( + 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.accounts_v1.EmailPreferencesServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "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.accounts.v1.EmailPreferencesService", + "credentialsType": None, + } + ) + + async def get_email_preferences(self, + request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Returns the email preferences for a Merchant Center account + user. This service only permits retrieving and updating email + preferences for the authenticated user. Use the + name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + .. 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_accounts_v1 + + async def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetEmailPreferencesRequest, dict]]): + The request object. Request message for + GetEmailPreferences method. + name (:class:`str`): + Required. The name of the ``EmailPreferences`` resource. + Format: + ``accounts/{account}/users/{email}/emailPreferences`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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, emailpreferences.GetEmailPreferencesRequest): + request = emailpreferences.GetEmailPreferencesRequest(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.get_email_preferences] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_email_preferences(self, + request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, + *, + email_preferences: Optional[emailpreferences.EmailPreferences] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Updates the email preferences for a Merchant Center account + user. Advanced account users should specify the advanced account + rather than a sub-account of the advanced account. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + .. 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_accounts_v1 + + async def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = await client.update_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateEmailPreferencesRequest, dict]]): + The request object. Request message for + UpdateEmailPreferences method. + email_preferences (:class:`google.shopping.merchant_accounts_v1.types.EmailPreferences`): + Required. Email Preferences to be + updated. + + This corresponds to the ``email_preferences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``news_and_tips`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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 = [email_preferences, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, emailpreferences.UpdateEmailPreferencesRequest): + request = emailpreferences.UpdateEmailPreferencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if email_preferences is not None: + request.email_preferences = email_preferences + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_email_preferences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("email_preferences.name", request.email_preferences.name), + )), + ) + + # 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 __aenter__(self) -> "EmailPreferencesServiceAsyncClient": + 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__ = ( + "EmailPreferencesServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py new file mode 100644 index 000000000000..cd208c085680 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py @@ -0,0 +1,870 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import emailpreferences +from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EmailPreferencesServiceGrpcTransport +from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport +from .transports.rest import EmailPreferencesServiceRestTransport + + +class EmailPreferencesServiceClientMeta(type): + """Metaclass for the EmailPreferencesService 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[EmailPreferencesServiceTransport]] + _transport_registry["grpc"] = EmailPreferencesServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EmailPreferencesServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EmailPreferencesServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EmailPreferencesServiceTransport]: + """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 EmailPreferencesServiceClient(metaclass=EmailPreferencesServiceClientMeta): + """Service to support the ``EmailPreferences`` API.""" + + @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: + EmailPreferencesServiceClient: 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: + EmailPreferencesServiceClient: 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) -> EmailPreferencesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EmailPreferencesServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def email_preferences_path(account: str,email: str,) -> str: + """Returns a fully-qualified email_preferences string.""" + return "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) + + @staticmethod + def parse_email_preferences_path(path: str) -> Dict[str,str]: + """Parses a email_preferences path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/users/(?P.+?)/emailPreferences$", 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 = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient._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, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the email preferences 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,EmailPreferencesServiceTransport,Callable[..., EmailPreferencesServiceTransport]]]): + 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 EmailPreferencesServiceTransport 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 = EmailPreferencesServiceClient._read_environment_variables() + self._client_cert_source = EmailPreferencesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EmailPreferencesServiceClient._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, EmailPreferencesServiceTransport) + if transport_provided: + # transport is a EmailPreferencesServiceTransport 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(EmailPreferencesServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EmailPreferencesServiceClient._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[EmailPreferencesServiceTransport], Callable[..., EmailPreferencesServiceTransport]] = ( + EmailPreferencesServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EmailPreferencesServiceTransport], 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.accounts_v1.EmailPreferencesServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "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.accounts.v1.EmailPreferencesService", + "credentialsType": None, + } + ) + + def get_email_preferences(self, + request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Returns the email preferences for a Merchant Center account + user. This service only permits retrieving and updating email + preferences for the authenticated user. Use the + name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + .. 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_accounts_v1 + + def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = client.get_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetEmailPreferencesRequest, dict]): + The request object. Request message for + GetEmailPreferences method. + name (str): + Required. The name of the ``EmailPreferences`` resource. + Format: + ``accounts/{account}/users/{email}/emailPreferences`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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, emailpreferences.GetEmailPreferencesRequest): + request = emailpreferences.GetEmailPreferencesRequest(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.get_email_preferences] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_email_preferences(self, + request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, + *, + email_preferences: Optional[emailpreferences.EmailPreferences] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Updates the email preferences for a Merchant Center account + user. Advanced account users should specify the advanced account + rather than a sub-account of the advanced account. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + .. 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_accounts_v1 + + def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = client.update_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateEmailPreferencesRequest, dict]): + The request object. Request message for + UpdateEmailPreferences method. + email_preferences (google.shopping.merchant_accounts_v1.types.EmailPreferences): + Required. Email Preferences to be + updated. + + This corresponds to the ``email_preferences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``news_and_tips`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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 = [email_preferences, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, emailpreferences.UpdateEmailPreferencesRequest): + request = emailpreferences.UpdateEmailPreferencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if email_preferences is not None: + request.email_preferences = email_preferences + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_email_preferences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("email_preferences.name", request.email_preferences.name), + )), + ) + + # 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 __enter__(self) -> "EmailPreferencesServiceClient": + 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__ = ( + "EmailPreferencesServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst new file mode 100644 index 000000000000..210db60dee0d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EmailPreferencesServiceTransport` is the ABC for all transports. +- public child `EmailPreferencesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EmailPreferencesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEmailPreferencesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EmailPreferencesServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py new file mode 100644 index 000000000000..3bfd9590e738 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_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 EmailPreferencesServiceTransport +from .grpc import EmailPreferencesServiceGrpcTransport +from .grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport +from .rest import EmailPreferencesServiceRestTransport +from .rest import EmailPreferencesServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EmailPreferencesServiceTransport]] +_transport_registry['grpc'] = EmailPreferencesServiceGrpcTransport +_transport_registry['grpc_asyncio'] = EmailPreferencesServiceGrpcAsyncIOTransport +_transport_registry['rest'] = EmailPreferencesServiceRestTransport + +__all__ = ( + 'EmailPreferencesServiceTransport', + 'EmailPreferencesServiceGrpcTransport', + 'EmailPreferencesServiceGrpcAsyncIOTransport', + 'EmailPreferencesServiceRestTransport', + 'EmailPreferencesServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py new file mode 100644 index 000000000000..0a3c86442a93 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import emailpreferences + +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 EmailPreferencesServiceTransport(abc.ABC): + """Abstract transport class for EmailPreferencesService.""" + + 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.get_email_preferences: gapic_v1.method.wrap_method( + self.get_email_preferences, + default_timeout=None, + client_info=client_info, + ), + self.update_email_preferences: gapic_v1.method.wrap_method( + self.update_email_preferences, + 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 get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + Union[ + emailpreferences.EmailPreferences, + Awaitable[emailpreferences.EmailPreferences] + ]]: + raise NotImplementedError() + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + Union[ + emailpreferences.EmailPreferences, + Awaitable[emailpreferences.EmailPreferences] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'EmailPreferencesServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py new file mode 100644 index 000000000000..0cde092fb452 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py @@ -0,0 +1,387 @@ +# -*- 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.shopping.merchant_accounts_v1.types import emailpreferences +from .base import EmailPreferencesServiceTransport, 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.accounts.v1.EmailPreferencesService", + "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.accounts.v1.EmailPreferencesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EmailPreferencesServiceGrpcTransport(EmailPreferencesServiceTransport): + """gRPC backend transport for EmailPreferencesService. + + Service to support the ``EmailPreferences`` API. + + 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 get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + r"""Return a callable for the get email preferences method over gRPC. + + Returns the email preferences for a Merchant Center account + user. This service only permits retrieving and updating email + preferences for the authenticated user. Use the + name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + Returns: + Callable[[~.GetEmailPreferencesRequest], + ~.EmailPreferences]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_email_preferences' not in self._stubs: + self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.EmailPreferencesService/GetEmailPreferences', + request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['get_email_preferences'] + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + r"""Return a callable for the update email preferences method over gRPC. + + Updates the email preferences for a Merchant Center account + user. Advanced account users should specify the advanced account + rather than a sub-account of the advanced account. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + Returns: + Callable[[~.UpdateEmailPreferencesRequest], + ~.EmailPreferences]: + 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 'update_email_preferences' not in self._stubs: + self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.EmailPreferencesService/UpdateEmailPreferences', + request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['update_email_preferences'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'EmailPreferencesServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..31d51f56cf1f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py @@ -0,0 +1,413 @@ +# -*- 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.shopping.merchant_accounts_v1.types import emailpreferences +from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import EmailPreferencesServiceGrpcTransport + +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.accounts.v1.EmailPreferencesService", + "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.accounts.v1.EmailPreferencesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EmailPreferencesServiceGrpcAsyncIOTransport(EmailPreferencesServiceTransport): + """gRPC AsyncIO backend transport for EmailPreferencesService. + + Service to support the ``EmailPreferences`` API. + + 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 get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + Awaitable[emailpreferences.EmailPreferences]]: + r"""Return a callable for the get email preferences method over gRPC. + + Returns the email preferences for a Merchant Center account + user. This service only permits retrieving and updating email + preferences for the authenticated user. Use the + name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + Returns: + Callable[[~.GetEmailPreferencesRequest], + Awaitable[~.EmailPreferences]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_email_preferences' not in self._stubs: + self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.EmailPreferencesService/GetEmailPreferences', + request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['get_email_preferences'] + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + Awaitable[emailpreferences.EmailPreferences]]: + r"""Return a callable for the update email preferences method over gRPC. + + Updates the email preferences for a Merchant Center account + user. Advanced account users should specify the advanced account + rather than a sub-account of the advanced account. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + Returns: + Callable[[~.UpdateEmailPreferencesRequest], + Awaitable[~.EmailPreferences]]: + 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 'update_email_preferences' not in self._stubs: + self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.EmailPreferencesService/UpdateEmailPreferences', + request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['update_email_preferences'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_email_preferences: self._wrap_method( + self.get_email_preferences, + default_timeout=None, + client_info=client_info, + ), + self.update_email_preferences: self._wrap_method( + self.update_email_preferences, + 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__ = ( + 'EmailPreferencesServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py new file mode 100644 index 000000000000..ca3c521edd9d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py @@ -0,0 +1,537 @@ +# -*- 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.shopping.merchant_accounts_v1.types import emailpreferences + + +from .rest_base import _BaseEmailPreferencesServiceRestTransport +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 EmailPreferencesServiceRestInterceptor: + """Interceptor for EmailPreferencesService. + + 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 EmailPreferencesServiceRestTransport. + + .. code-block:: python + class MyCustomEmailPreferencesServiceInterceptor(EmailPreferencesServiceRestInterceptor): + def pre_get_email_preferences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_email_preferences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_email_preferences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_email_preferences(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EmailPreferencesServiceRestTransport(interceptor=MyCustomEmailPreferencesServiceInterceptor()) + client = EmailPreferencesServiceClient(transport=transport) + + + """ + def pre_get_email_preferences(self, request: emailpreferences.GetEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_email_preferences + + Override in a subclass to manipulate the request or metadata + before they are sent to the EmailPreferencesService server. + """ + return request, metadata + + def post_get_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: + """Post-rpc interceptor for get_email_preferences + + DEPRECATED. Please use the `post_get_email_preferences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EmailPreferencesService server but before + it is returned to user code. This `post_get_email_preferences` interceptor runs + before the `post_get_email_preferences_with_metadata` interceptor. + """ + return response + + def post_get_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_email_preferences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EmailPreferencesService server but before it is returned to user code. + + We recommend only using this `post_get_email_preferences_with_metadata` + interceptor in new development instead of the `post_get_email_preferences` interceptor. + When both interceptors are used, this `post_get_email_preferences_with_metadata` interceptor runs after the + `post_get_email_preferences` interceptor. The (possibly modified) response returned by + `post_get_email_preferences` will be passed to + `post_get_email_preferences_with_metadata`. + """ + return response, metadata + + def pre_update_email_preferences(self, request: emailpreferences.UpdateEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_email_preferences + + Override in a subclass to manipulate the request or metadata + before they are sent to the EmailPreferencesService server. + """ + return request, metadata + + def post_update_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: + """Post-rpc interceptor for update_email_preferences + + DEPRECATED. Please use the `post_update_email_preferences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EmailPreferencesService server but before + it is returned to user code. This `post_update_email_preferences` interceptor runs + before the `post_update_email_preferences_with_metadata` interceptor. + """ + return response + + def post_update_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_email_preferences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EmailPreferencesService server but before it is returned to user code. + + We recommend only using this `post_update_email_preferences_with_metadata` + interceptor in new development instead of the `post_update_email_preferences` interceptor. + When both interceptors are used, this `post_update_email_preferences_with_metadata` interceptor runs after the + `post_update_email_preferences` interceptor. The (possibly modified) response returned by + `post_update_email_preferences` will be passed to + `post_update_email_preferences_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class EmailPreferencesServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EmailPreferencesServiceRestInterceptor + + +class EmailPreferencesServiceRestTransport(_BaseEmailPreferencesServiceRestTransport): + """REST backend synchronous transport for EmailPreferencesService. + + Service to support the ``EmailPreferences`` API. + + 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[EmailPreferencesServiceRestInterceptor] = 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 EmailPreferencesServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences, EmailPreferencesServiceRestStub): + def __hash__(self): + return hash("EmailPreferencesServiceRestTransport.GetEmailPreferences") + + @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: emailpreferences.GetEmailPreferencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> emailpreferences.EmailPreferences: + r"""Call the get email preferences method over HTTP. + + Args: + request (~.emailpreferences.GetEmailPreferencesRequest): + The request object. Request message for + GetEmailPreferences 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: + ~.emailpreferences.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + + http_options = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_http_options() + + request, metadata = self._interceptor.pre_get_email_preferences(request, metadata) + transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.EmailPreferencesServiceClient.GetEmailPreferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "rpcName": "GetEmailPreferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EmailPreferencesServiceRestTransport._GetEmailPreferences._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 = emailpreferences.EmailPreferences() + pb_resp = emailpreferences.EmailPreferences.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_email_preferences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_email_preferences_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = emailpreferences.EmailPreferences.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.accounts_v1.EmailPreferencesServiceClient.get_email_preferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "rpcName": "GetEmailPreferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences, EmailPreferencesServiceRestStub): + def __hash__(self): + return hash("EmailPreferencesServiceRestTransport.UpdateEmailPreferences") + + @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: emailpreferences.UpdateEmailPreferencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> emailpreferences.EmailPreferences: + r"""Call the update email preferences method over HTTP. + + Args: + request (~.emailpreferences.UpdateEmailPreferencesRequest): + The request object. Request message for + UpdateEmailPreferences 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: + ~.emailpreferences.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + + http_options = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_http_options() + + request, metadata = self._interceptor.pre_update_email_preferences(request, metadata) + transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_transcoded_request(http_options, request) + + body = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.EmailPreferencesServiceClient.UpdateEmailPreferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "rpcName": "UpdateEmailPreferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EmailPreferencesServiceRestTransport._UpdateEmailPreferences._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 = emailpreferences.EmailPreferences() + pb_resp = emailpreferences.EmailPreferences.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_email_preferences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_email_preferences_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = emailpreferences.EmailPreferences.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.accounts_v1.EmailPreferencesServiceClient.update_email_preferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "rpcName": "UpdateEmailPreferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + # 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._GetEmailPreferences(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + # 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._UpdateEmailPreferences(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EmailPreferencesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py new file mode 100644 index 000000000000..89575492b481 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import emailpreferences + + +class _BaseEmailPreferencesServiceRestTransport(EmailPreferencesServiceTransport): + """Base REST backend transport for EmailPreferencesService. + + 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 _BaseGetEmailPreferences: + 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': '/accounts/v1/{name=accounts/*/users/*/emailPreferences}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = emailpreferences.GetEmailPreferencesRequest.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(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEmailPreferences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1/{email_preferences.name=accounts/*/users/*/emailPreferences}', + 'body': 'email_preferences', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = emailpreferences.UpdateEmailPreferencesRequest.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(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseEmailPreferencesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py new file mode 100644 index 000000000000..38f66e5e7f00 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_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 GbpAccountsServiceClient +from .async_client import GbpAccountsServiceAsyncClient + +__all__ = ( + 'GbpAccountsServiceClient', + 'GbpAccountsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py new file mode 100644 index 000000000000..f6b60872b221 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py @@ -0,0 +1,506 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import pagers +from google.shopping.merchant_accounts_v1.types import gbpaccounts +from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport +from .client import GbpAccountsServiceClient + +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 GbpAccountsServiceAsyncClient: + """The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + """ + + _client: GbpAccountsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = GbpAccountsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = GbpAccountsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(GbpAccountsServiceClient.account_path) + parse_account_path = staticmethod(GbpAccountsServiceClient.parse_account_path) + gbp_account_path = staticmethod(GbpAccountsServiceClient.gbp_account_path) + parse_gbp_account_path = staticmethod(GbpAccountsServiceClient.parse_gbp_account_path) + common_billing_account_path = staticmethod(GbpAccountsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(GbpAccountsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(GbpAccountsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(GbpAccountsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(GbpAccountsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(GbpAccountsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(GbpAccountsServiceClient.common_project_path) + parse_common_project_path = staticmethod(GbpAccountsServiceClient.parse_common_project_path) + common_location_path = staticmethod(GbpAccountsServiceClient.common_location_path) + parse_common_location_path = staticmethod(GbpAccountsServiceClient.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: + GbpAccountsServiceAsyncClient: The constructed client. + """ + return GbpAccountsServiceClient.from_service_account_info.__func__(GbpAccountsServiceAsyncClient, 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: + GbpAccountsServiceAsyncClient: The constructed client. + """ + return GbpAccountsServiceClient.from_service_account_file.__func__(GbpAccountsServiceAsyncClient, 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 GbpAccountsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GbpAccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GbpAccountsServiceTransport: 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 = GbpAccountsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gbp accounts 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,GbpAccountsServiceTransport,Callable[..., GbpAccountsServiceTransport]]]): + 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 GbpAccountsServiceTransport 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 = GbpAccountsServiceClient( + 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.accounts_v1.GbpAccountsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "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.accounts.v1.GbpAccountsService", + "credentialsType": None, + } + ) + + async def list_gbp_accounts(self, + request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsAsyncPager: + r"""List the GBP accounts for a given merchant. + + .. 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_accounts_v1 + + async def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListGbpAccountsRequest, dict]]): + The request object. Request message for the + ListGbpAccounts method. + parent (:class:`str`): + Required. The name of the parent resource under which + the GBP accounts are listed. Format: + ``accounts/{account}``. + + 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_accounts_v1.services.gbp_accounts_service.pagers.ListGbpAccountsAsyncPager: + Response message for the + ListGbpAccounts 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, gbpaccounts.ListGbpAccountsRequest): + request = gbpaccounts.ListGbpAccountsRequest(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_gbp_accounts] + + # 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.ListGbpAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def link_gbp_account(self, + request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: + r"""Link the specified merchant to a GBP account for all countries. + + To run this method, you must have admin access to the Merchant + Center account. If you don't have admin access, the request + fails with the error message + ``User is not an administrator of account {ACCOUNT_ID}``. + + .. 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_accounts_v1 + + async def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = await client.link_gbp_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.LinkGbpAccountRequest, dict]]): + The request object. Request message for the + LinkGbpAccount method. + parent (:class:`str`): + Required. The name of the parent resource to which the + GBP account is linked. Format: ``accounts/{account}``. + + 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_accounts_v1.types.LinkGbpAccountResponse: + Response message for the + LinkGbpAccount method. + + """ + # 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, gbpaccounts.LinkGbpAccountRequest): + request = gbpaccounts.LinkGbpAccountRequest(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.link_gbp_account] + + # 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 __aenter__(self) -> "GbpAccountsServiceAsyncClient": + 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__ = ( + "GbpAccountsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py new file mode 100644 index 000000000000..9e573d3a5f79 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py @@ -0,0 +1,874 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import pagers +from google.shopping.merchant_accounts_v1.types import gbpaccounts +from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import GbpAccountsServiceGrpcTransport +from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport +from .transports.rest import GbpAccountsServiceRestTransport + + +class GbpAccountsServiceClientMeta(type): + """Metaclass for the GbpAccountsService 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[GbpAccountsServiceTransport]] + _transport_registry["grpc"] = GbpAccountsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = GbpAccountsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = GbpAccountsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[GbpAccountsServiceTransport]: + """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 GbpAccountsServiceClient(metaclass=GbpAccountsServiceClientMeta): + """The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + """ + + @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: + GbpAccountsServiceClient: 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: + GbpAccountsServiceClient: 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) -> GbpAccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GbpAccountsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def gbp_account_path(account: str,gbp_account: str,) -> str: + """Returns a fully-qualified gbp_account string.""" + return "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) + + @staticmethod + def parse_gbp_account_path(path: str) -> Dict[str,str]: + """Parses a gbp_account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/gbpAccounts/(?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 = GbpAccountsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = GbpAccountsServiceClient._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 = GbpAccountsServiceClient._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, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gbp accounts 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,GbpAccountsServiceTransport,Callable[..., GbpAccountsServiceTransport]]]): + 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 GbpAccountsServiceTransport 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 = GbpAccountsServiceClient._read_environment_variables() + self._client_cert_source = GbpAccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = GbpAccountsServiceClient._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, GbpAccountsServiceTransport) + if transport_provided: + # transport is a GbpAccountsServiceTransport 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(GbpAccountsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + GbpAccountsServiceClient._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[GbpAccountsServiceTransport], Callable[..., GbpAccountsServiceTransport]] = ( + GbpAccountsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., GbpAccountsServiceTransport], 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.accounts_v1.GbpAccountsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "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.accounts.v1.GbpAccountsService", + "credentialsType": None, + } + ) + + def list_gbp_accounts(self, + request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsPager: + r"""List the GBP accounts for a given merchant. + + .. 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_accounts_v1 + + def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListGbpAccountsRequest, dict]): + The request object. Request message for the + ListGbpAccounts method. + parent (str): + Required. The name of the parent resource under which + the GBP accounts are listed. Format: + ``accounts/{account}``. + + 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_accounts_v1.services.gbp_accounts_service.pagers.ListGbpAccountsPager: + Response message for the + ListGbpAccounts 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, gbpaccounts.ListGbpAccountsRequest): + request = gbpaccounts.ListGbpAccountsRequest(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_gbp_accounts] + + # 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.ListGbpAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def link_gbp_account(self, + request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: + r"""Link the specified merchant to a GBP account for all countries. + + To run this method, you must have admin access to the Merchant + Center account. If you don't have admin access, the request + fails with the error message + ``User is not an administrator of account {ACCOUNT_ID}``. + + .. 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_accounts_v1 + + def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = client.link_gbp_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.LinkGbpAccountRequest, dict]): + The request object. Request message for the + LinkGbpAccount method. + parent (str): + Required. The name of the parent resource to which the + GBP account is linked. Format: ``accounts/{account}``. + + 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_accounts_v1.types.LinkGbpAccountResponse: + Response message for the + LinkGbpAccount method. + + """ + # 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, gbpaccounts.LinkGbpAccountRequest): + request = gbpaccounts.LinkGbpAccountRequest(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.link_gbp_account] + + # 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 __enter__(self) -> "GbpAccountsServiceClient": + 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__ = ( + "GbpAccountsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py new file mode 100644 index 000000000000..53128ed34e45 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_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_accounts_v1.types import gbpaccounts + + +class ListGbpAccountsPager: + """A pager for iterating through ``list_gbp_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListGbpAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``gbp_accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGbpAccounts`` requests and continue to iterate + through the ``gbp_accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListGbpAccountsResponse` + 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[..., gbpaccounts.ListGbpAccountsResponse], + request: gbpaccounts.ListGbpAccountsRequest, + response: gbpaccounts.ListGbpAccountsResponse, + *, + 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_accounts_v1.types.ListGbpAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListGbpAccountsResponse): + 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 = gbpaccounts.ListGbpAccountsRequest(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[gbpaccounts.ListGbpAccountsResponse]: + 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[gbpaccounts.GbpAccount]: + for page in self.pages: + yield from page.gbp_accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGbpAccountsAsyncPager: + """A pager for iterating through ``list_gbp_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListGbpAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``gbp_accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGbpAccounts`` requests and continue to iterate + through the ``gbp_accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListGbpAccountsResponse` + 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[gbpaccounts.ListGbpAccountsResponse]], + request: gbpaccounts.ListGbpAccountsRequest, + response: gbpaccounts.ListGbpAccountsResponse, + *, + 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_accounts_v1.types.ListGbpAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListGbpAccountsResponse): + 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 = gbpaccounts.ListGbpAccountsRequest(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[gbpaccounts.ListGbpAccountsResponse]: + 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[gbpaccounts.GbpAccount]: + async def async_generator(): + async for page in self.pages: + for response in page.gbp_accounts: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst new file mode 100644 index 000000000000..a6f7710d74a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GbpAccountsServiceTransport` is the ABC for all transports. +- public child `GbpAccountsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GbpAccountsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGbpAccountsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GbpAccountsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py new file mode 100644 index 000000000000..6576bf17bbcf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_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 GbpAccountsServiceTransport +from .grpc import GbpAccountsServiceGrpcTransport +from .grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport +from .rest import GbpAccountsServiceRestTransport +from .rest import GbpAccountsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GbpAccountsServiceTransport]] +_transport_registry['grpc'] = GbpAccountsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = GbpAccountsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = GbpAccountsServiceRestTransport + +__all__ = ( + 'GbpAccountsServiceTransport', + 'GbpAccountsServiceGrpcTransport', + 'GbpAccountsServiceGrpcAsyncIOTransport', + 'GbpAccountsServiceRestTransport', + 'GbpAccountsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py new file mode 100644 index 000000000000..e2cfc1cb53de --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import gbpaccounts + +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 GbpAccountsServiceTransport(abc.ABC): + """Abstract transport class for GbpAccountsService.""" + + 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_gbp_accounts: gapic_v1.method.wrap_method( + self.list_gbp_accounts, + default_timeout=None, + client_info=client_info, + ), + self.link_gbp_account: gapic_v1.method.wrap_method( + self.link_gbp_account, + 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_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + Union[ + gbpaccounts.ListGbpAccountsResponse, + Awaitable[gbpaccounts.ListGbpAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + Union[ + gbpaccounts.LinkGbpAccountResponse, + Awaitable[gbpaccounts.LinkGbpAccountResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'GbpAccountsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py new file mode 100644 index 000000000000..1ea218d00ddd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py @@ -0,0 +1,381 @@ +# -*- 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.shopping.merchant_accounts_v1.types import gbpaccounts +from .base import GbpAccountsServiceTransport, 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.accounts.v1.GbpAccountsService", + "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.accounts.v1.GbpAccountsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GbpAccountsServiceGrpcTransport(GbpAccountsServiceTransport): + """gRPC backend transport for GbpAccountsService. + + The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + + 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_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + gbpaccounts.ListGbpAccountsResponse]: + r"""Return a callable for the list gbp accounts method over gRPC. + + List the GBP accounts for a given merchant. + + Returns: + Callable[[~.ListGbpAccountsRequest], + ~.ListGbpAccountsResponse]: + 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_gbp_accounts' not in self._stubs: + self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.GbpAccountsService/ListGbpAccounts', + request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, + response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, + ) + return self._stubs['list_gbp_accounts'] + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + gbpaccounts.LinkGbpAccountResponse]: + r"""Return a callable for the link gbp account method over gRPC. + + Link the specified merchant to a GBP account for all countries. + + To run this method, you must have admin access to the Merchant + Center account. If you don't have admin access, the request + fails with the error message + ``User is not an administrator of account {ACCOUNT_ID}``. + + Returns: + Callable[[~.LinkGbpAccountRequest], + ~.LinkGbpAccountResponse]: + 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 'link_gbp_account' not in self._stubs: + self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.GbpAccountsService/LinkGbpAccount', + request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, + response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, + ) + return self._stubs['link_gbp_account'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'GbpAccountsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..f13033cb46c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py @@ -0,0 +1,407 @@ +# -*- 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.shopping.merchant_accounts_v1.types import gbpaccounts +from .base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import GbpAccountsServiceGrpcTransport + +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.accounts.v1.GbpAccountsService", + "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.accounts.v1.GbpAccountsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GbpAccountsServiceGrpcAsyncIOTransport(GbpAccountsServiceTransport): + """gRPC AsyncIO backend transport for GbpAccountsService. + + The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + + 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_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + Awaitable[gbpaccounts.ListGbpAccountsResponse]]: + r"""Return a callable for the list gbp accounts method over gRPC. + + List the GBP accounts for a given merchant. + + Returns: + Callable[[~.ListGbpAccountsRequest], + Awaitable[~.ListGbpAccountsResponse]]: + 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_gbp_accounts' not in self._stubs: + self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.GbpAccountsService/ListGbpAccounts', + request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, + response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, + ) + return self._stubs['list_gbp_accounts'] + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + Awaitable[gbpaccounts.LinkGbpAccountResponse]]: + r"""Return a callable for the link gbp account method over gRPC. + + Link the specified merchant to a GBP account for all countries. + + To run this method, you must have admin access to the Merchant + Center account. If you don't have admin access, the request + fails with the error message + ``User is not an administrator of account {ACCOUNT_ID}``. + + Returns: + Callable[[~.LinkGbpAccountRequest], + Awaitable[~.LinkGbpAccountResponse]]: + 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 'link_gbp_account' not in self._stubs: + self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.GbpAccountsService/LinkGbpAccount', + request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, + response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, + ) + return self._stubs['link_gbp_account'] + + 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_gbp_accounts: self._wrap_method( + self.list_gbp_accounts, + default_timeout=None, + client_info=client_info, + ), + self.link_gbp_account: self._wrap_method( + self.link_gbp_account, + 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__ = ( + 'GbpAccountsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py new file mode 100644 index 000000000000..f616ee81f402 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py @@ -0,0 +1,535 @@ +# -*- 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.shopping.merchant_accounts_v1.types import gbpaccounts + + +from .rest_base import _BaseGbpAccountsServiceRestTransport +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 GbpAccountsServiceRestInterceptor: + """Interceptor for GbpAccountsService. + + 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 GbpAccountsServiceRestTransport. + + .. code-block:: python + class MyCustomGbpAccountsServiceInterceptor(GbpAccountsServiceRestInterceptor): + def pre_link_gbp_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_link_gbp_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_gbp_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_gbp_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GbpAccountsServiceRestTransport(interceptor=MyCustomGbpAccountsServiceInterceptor()) + client = GbpAccountsServiceClient(transport=transport) + + + """ + def pre_link_gbp_account(self, request: gbpaccounts.LinkGbpAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for link_gbp_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the GbpAccountsService server. + """ + return request, metadata + + def post_link_gbp_account(self, response: gbpaccounts.LinkGbpAccountResponse) -> gbpaccounts.LinkGbpAccountResponse: + """Post-rpc interceptor for link_gbp_account + + DEPRECATED. Please use the `post_link_gbp_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GbpAccountsService server but before + it is returned to user code. This `post_link_gbp_account` interceptor runs + before the `post_link_gbp_account_with_metadata` interceptor. + """ + return response + + def post_link_gbp_account_with_metadata(self, response: gbpaccounts.LinkGbpAccountResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for link_gbp_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GbpAccountsService server but before it is returned to user code. + + We recommend only using this `post_link_gbp_account_with_metadata` + interceptor in new development instead of the `post_link_gbp_account` interceptor. + When both interceptors are used, this `post_link_gbp_account_with_metadata` interceptor runs after the + `post_link_gbp_account` interceptor. The (possibly modified) response returned by + `post_link_gbp_account` will be passed to + `post_link_gbp_account_with_metadata`. + """ + return response, metadata + + def pre_list_gbp_accounts(self, request: gbpaccounts.ListGbpAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_gbp_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the GbpAccountsService server. + """ + return request, metadata + + def post_list_gbp_accounts(self, response: gbpaccounts.ListGbpAccountsResponse) -> gbpaccounts.ListGbpAccountsResponse: + """Post-rpc interceptor for list_gbp_accounts + + DEPRECATED. Please use the `post_list_gbp_accounts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GbpAccountsService server but before + it is returned to user code. This `post_list_gbp_accounts` interceptor runs + before the `post_list_gbp_accounts_with_metadata` interceptor. + """ + return response + + def post_list_gbp_accounts_with_metadata(self, response: gbpaccounts.ListGbpAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_gbp_accounts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GbpAccountsService server but before it is returned to user code. + + We recommend only using this `post_list_gbp_accounts_with_metadata` + interceptor in new development instead of the `post_list_gbp_accounts` interceptor. + When both interceptors are used, this `post_list_gbp_accounts_with_metadata` interceptor runs after the + `post_list_gbp_accounts` interceptor. The (possibly modified) response returned by + `post_list_gbp_accounts` will be passed to + `post_list_gbp_accounts_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class GbpAccountsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GbpAccountsServiceRestInterceptor + + +class GbpAccountsServiceRestTransport(_BaseGbpAccountsServiceRestTransport): + """REST backend synchronous transport for GbpAccountsService. + + The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + + 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[GbpAccountsServiceRestInterceptor] = 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 GbpAccountsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _LinkGbpAccount(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount, GbpAccountsServiceRestStub): + def __hash__(self): + return hash("GbpAccountsServiceRestTransport.LinkGbpAccount") + + @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: gbpaccounts.LinkGbpAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gbpaccounts.LinkGbpAccountResponse: + r"""Call the link gbp account method over HTTP. + + Args: + request (~.gbpaccounts.LinkGbpAccountRequest): + The request object. Request message for the + LinkGbpAccount 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: + ~.gbpaccounts.LinkGbpAccountResponse: + Response message for the + LinkGbpAccount method. + + """ + + http_options = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_http_options() + + request, metadata = self._interceptor.pre_link_gbp_account(request, metadata) + transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_transcoded_request(http_options, request) + + body = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.GbpAccountsServiceClient.LinkGbpAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "rpcName": "LinkGbpAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GbpAccountsServiceRestTransport._LinkGbpAccount._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 = gbpaccounts.LinkGbpAccountResponse() + pb_resp = gbpaccounts.LinkGbpAccountResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_link_gbp_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_link_gbp_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gbpaccounts.LinkGbpAccountResponse.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.accounts_v1.GbpAccountsServiceClient.link_gbp_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "rpcName": "LinkGbpAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListGbpAccounts(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts, GbpAccountsServiceRestStub): + def __hash__(self): + return hash("GbpAccountsServiceRestTransport.ListGbpAccounts") + + @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: gbpaccounts.ListGbpAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gbpaccounts.ListGbpAccountsResponse: + r"""Call the list gbp accounts method over HTTP. + + Args: + request (~.gbpaccounts.ListGbpAccountsRequest): + The request object. Request message for the + ListGbpAccounts 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: + ~.gbpaccounts.ListGbpAccountsResponse: + Response message for the + ListGbpAccounts method. + + """ + + http_options = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_http_options() + + request, metadata = self._interceptor.pre_list_gbp_accounts(request, metadata) + transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.GbpAccountsServiceClient.ListGbpAccounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "rpcName": "ListGbpAccounts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GbpAccountsServiceRestTransport._ListGbpAccounts._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 = gbpaccounts.ListGbpAccountsResponse() + pb_resp = gbpaccounts.ListGbpAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_gbp_accounts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_gbp_accounts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gbpaccounts.ListGbpAccountsResponse.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.accounts_v1.GbpAccountsServiceClient.list_gbp_accounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "rpcName": "ListGbpAccounts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + gbpaccounts.LinkGbpAccountResponse]: + # 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._LinkGbpAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + gbpaccounts.ListGbpAccountsResponse]: + # 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._ListGbpAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'GbpAccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py new file mode 100644 index 000000000000..be9f189e498a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import gbpaccounts + + +class _BaseGbpAccountsServiceRestTransport(GbpAccountsServiceTransport): + """Base REST backend transport for GbpAccountsService. + + 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 _BaseLinkGbpAccount: + 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': '/accounts/v1/{parent=accounts/*}/gbpAccounts:linkGbpAccount', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gbpaccounts.LinkGbpAccountRequest.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(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGbpAccounts: + 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': '/accounts/v1/{parent=accounts/*}/gbpAccounts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gbpaccounts.ListGbpAccountsRequest.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(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseGbpAccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py new file mode 100644 index 000000000000..96d41fc82ad2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_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 HomepageServiceClient +from .async_client import HomepageServiceAsyncClient + +__all__ = ( + 'HomepageServiceClient', + 'HomepageServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py new file mode 100644 index 000000000000..64e59d797ca1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py @@ -0,0 +1,717 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from .client import HomepageServiceClient + +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 HomepageServiceAsyncClient: + """Service to support an API for a store's homepage.""" + + _client: HomepageServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = HomepageServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = HomepageServiceClient._DEFAULT_UNIVERSE + + homepage_path = staticmethod(HomepageServiceClient.homepage_path) + parse_homepage_path = staticmethod(HomepageServiceClient.parse_homepage_path) + common_billing_account_path = staticmethod(HomepageServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(HomepageServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(HomepageServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(HomepageServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(HomepageServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(HomepageServiceClient.parse_common_organization_path) + common_project_path = staticmethod(HomepageServiceClient.common_project_path) + parse_common_project_path = staticmethod(HomepageServiceClient.parse_common_project_path) + common_location_path = staticmethod(HomepageServiceClient.common_location_path) + parse_common_location_path = staticmethod(HomepageServiceClient.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: + HomepageServiceAsyncClient: The constructed client. + """ + return HomepageServiceClient.from_service_account_info.__func__(HomepageServiceAsyncClient, 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: + HomepageServiceAsyncClient: The constructed client. + """ + return HomepageServiceClient.from_service_account_file.__func__(HomepageServiceAsyncClient, 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 HomepageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> HomepageServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HomepageServiceTransport: 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 = HomepageServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the homepage 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,HomepageServiceTransport,Callable[..., HomepageServiceTransport]]]): + 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 HomepageServiceTransport 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 = HomepageServiceClient( + 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.accounts_v1.HomepageServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "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.accounts.v1.HomepageService", + "credentialsType": None, + } + ) + + async def get_homepage(self, + request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Retrieves a store's homepage. + + .. 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_accounts_v1 + + async def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetHomepageRequest, dict]]): + The request object. Request message for the ``GetHomepage`` method. + name (:class:`str`): + Required. The name of the homepage to retrieve. Format: + ``accounts/{account}/homepage`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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, homepage.GetHomepageRequest): + request = homepage.GetHomepageRequest(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.get_homepage] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_homepage(self, + request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, + *, + homepage: Optional[gsma_homepage.Homepage] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: + r"""Updates a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1 + + async def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateHomepageRequest( + ) + + # Make the request + response = await client.update_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateHomepageRequest, dict]]): + The request object. Request message for the ``UpdateHomepage`` method. + homepage (:class:`google.shopping.merchant_accounts_v1.types.Homepage`): + Required. The new version of the + homepage. + + This corresponds to the ``homepage`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``uri`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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 = [homepage, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_homepage.UpdateHomepageRequest): + request = gsma_homepage.UpdateHomepageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if homepage is not None: + request.homepage = homepage + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_homepage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("homepage.name", request.homepage.name), + )), + ) + + # 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 claim_homepage(self, + request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the business is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. + + In case of failure, a canonical error message is returned: + + :: + + * PERMISSION_DENIED: User doesn't have the necessary permissions on this + Merchant Center account. + + * FAILED_PRECONDITION: + + - The account is not a Merchant Center account. + + - Merchant Center account doesn't have a homepage. + + - Claiming failed (in this case the error message contains more + details). + + .. 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_accounts_v1 + + async def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.claim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ClaimHomepageRequest, dict]]): + The request object. Request message for the ``ClaimHomepage`` 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_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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, homepage.ClaimHomepageRequest): + request = homepage.ClaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.claim_homepage] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def unclaim_homepage(self, + request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Unclaims a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1 + + async def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.unclaim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UnclaimHomepageRequest, dict]]): + The request object. Request message for the ``UnclaimHomepage`` 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_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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, homepage.UnclaimHomepageRequest): + request = homepage.UnclaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.unclaim_homepage] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "HomepageServiceAsyncClient": + 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__ = ( + "HomepageServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py new file mode 100644 index 000000000000..8cbb69d643b9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py @@ -0,0 +1,1076 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import HomepageServiceGrpcTransport +from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from .transports.rest import HomepageServiceRestTransport + + +class HomepageServiceClientMeta(type): + """Metaclass for the HomepageService 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[HomepageServiceTransport]] + _transport_registry["grpc"] = HomepageServiceGrpcTransport + _transport_registry["grpc_asyncio"] = HomepageServiceGrpcAsyncIOTransport + _transport_registry["rest"] = HomepageServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[HomepageServiceTransport]: + """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 HomepageServiceClient(metaclass=HomepageServiceClientMeta): + """Service to support an API for a store's homepage.""" + + @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: + HomepageServiceClient: 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: + HomepageServiceClient: 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) -> HomepageServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HomepageServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def homepage_path(account: str,) -> str: + """Returns a fully-qualified homepage string.""" + return "accounts/{account}/homepage".format(account=account, ) + + @staticmethod + def parse_homepage_path(path: str) -> Dict[str,str]: + """Parses a homepage path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/homepage$", 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 = HomepageServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = HomepageServiceClient._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 = HomepageServiceClient._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, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the homepage 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,HomepageServiceTransport,Callable[..., HomepageServiceTransport]]]): + 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 HomepageServiceTransport 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 = HomepageServiceClient._read_environment_variables() + self._client_cert_source = HomepageServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = HomepageServiceClient._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, HomepageServiceTransport) + if transport_provided: + # transport is a HomepageServiceTransport 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(HomepageServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + HomepageServiceClient._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[HomepageServiceTransport], Callable[..., HomepageServiceTransport]] = ( + HomepageServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., HomepageServiceTransport], 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.accounts_v1.HomepageServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "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.accounts.v1.HomepageService", + "credentialsType": None, + } + ) + + def get_homepage(self, + request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Retrieves a store's homepage. + + .. 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_accounts_v1 + + def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.get_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetHomepageRequest, dict]): + The request object. Request message for the ``GetHomepage`` method. + name (str): + Required. The name of the homepage to retrieve. Format: + ``accounts/{account}/homepage`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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, homepage.GetHomepageRequest): + request = homepage.GetHomepageRequest(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.get_homepage] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_homepage(self, + request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, + *, + homepage: Optional[gsma_homepage.Homepage] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: + r"""Updates a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1 + + def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateHomepageRequest( + ) + + # Make the request + response = client.update_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateHomepageRequest, dict]): + The request object. Request message for the ``UpdateHomepage`` method. + homepage (google.shopping.merchant_accounts_v1.types.Homepage): + Required. The new version of the + homepage. + + This corresponds to the ``homepage`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``uri`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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 = [homepage, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_homepage.UpdateHomepageRequest): + request = gsma_homepage.UpdateHomepageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if homepage is not None: + request.homepage = homepage + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_homepage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("homepage.name", request.homepage.name), + )), + ) + + # 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 claim_homepage(self, + request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the business is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. + + In case of failure, a canonical error message is returned: + + :: + + * PERMISSION_DENIED: User doesn't have the necessary permissions on this + Merchant Center account. + + * FAILED_PRECONDITION: + + - The account is not a Merchant Center account. + + - Merchant Center account doesn't have a homepage. + + - Claiming failed (in this case the error message contains more + details). + + .. 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_accounts_v1 + + def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.claim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ClaimHomepageRequest, dict]): + The request object. Request message for the ``ClaimHomepage`` 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_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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, homepage.ClaimHomepageRequest): + request = homepage.ClaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.claim_homepage] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def unclaim_homepage(self, + request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Unclaims a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1 + + def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.unclaim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UnclaimHomepageRequest, dict]): + The request object. Request message for the ``UnclaimHomepage`` 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_accounts_v1.types.Homepage: + The Homepage message represents a business's store homepage within the + system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof + of ownership and allows the business to unlock + features that require a verified website. For more + information, see [Understanding online store URL + verification](//support.google.com/merchants/answer/176793). + + """ + # 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, homepage.UnclaimHomepageRequest): + request = homepage.UnclaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.unclaim_homepage] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "HomepageServiceClient": + 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__ = ( + "HomepageServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst new file mode 100644 index 000000000000..8c0def729b79 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`HomepageServiceTransport` is the ABC for all transports. +- public child `HomepageServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `HomepageServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseHomepageServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `HomepageServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py new file mode 100644 index 000000000000..e935fb45c364 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_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 HomepageServiceTransport +from .grpc import HomepageServiceGrpcTransport +from .grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from .rest import HomepageServiceRestTransport +from .rest import HomepageServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[HomepageServiceTransport]] +_transport_registry['grpc'] = HomepageServiceGrpcTransport +_transport_registry['grpc_asyncio'] = HomepageServiceGrpcAsyncIOTransport +_transport_registry['rest'] = HomepageServiceRestTransport + +__all__ = ( + 'HomepageServiceTransport', + 'HomepageServiceGrpcTransport', + 'HomepageServiceGrpcAsyncIOTransport', + 'HomepageServiceRestTransport', + 'HomepageServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py new file mode 100644 index 000000000000..6e27e1763dd5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py @@ -0,0 +1,202 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage + +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 HomepageServiceTransport(abc.ABC): + """Abstract transport class for HomepageService.""" + + 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.get_homepage: gapic_v1.method.wrap_method( + self.get_homepage, + default_timeout=None, + client_info=client_info, + ), + self.update_homepage: gapic_v1.method.wrap_method( + self.update_homepage, + default_timeout=None, + client_info=client_info, + ), + self.claim_homepage: gapic_v1.method.wrap_method( + self.claim_homepage, + default_timeout=None, + client_info=client_info, + ), + self.unclaim_homepage: gapic_v1.method.wrap_method( + self.unclaim_homepage, + 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 get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + Union[ + homepage.Homepage, + Awaitable[homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + Union[ + gsma_homepage.Homepage, + Awaitable[gsma_homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + Union[ + homepage.Homepage, + Awaitable[homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + Union[ + homepage.Homepage, + Awaitable[homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'HomepageServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py new file mode 100644 index 000000000000..7fc6a4728c81 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.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 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.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from .base import HomepageServiceTransport, 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.accounts.v1.HomepageService", + "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.accounts.v1.HomepageService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HomepageServiceGrpcTransport(HomepageServiceTransport): + """gRPC backend transport for HomepageService. + + Service to support an API for a store's homepage. + + 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 get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + homepage.Homepage]: + r"""Return a callable for the get homepage method over gRPC. + + Retrieves a store's homepage. + + Returns: + Callable[[~.GetHomepageRequest], + ~.Homepage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_homepage' not in self._stubs: + self._stubs['get_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/GetHomepage', + request_serializer=homepage.GetHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['get_homepage'] + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + gsma_homepage.Homepage]: + r"""Return a callable for the update homepage method over gRPC. + + Updates a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UpdateHomepageRequest], + ~.Homepage]: + 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 'update_homepage' not in self._stubs: + self._stubs['update_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/UpdateHomepage', + request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, + response_deserializer=gsma_homepage.Homepage.deserialize, + ) + return self._stubs['update_homepage'] + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + homepage.Homepage]: + r"""Return a callable for the claim homepage method over gRPC. + + Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the business is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. + + In case of failure, a canonical error message is returned: + + :: + + * PERMISSION_DENIED: User doesn't have the necessary permissions on this + Merchant Center account. + + * FAILED_PRECONDITION: + + - The account is not a Merchant Center account. + + - Merchant Center account doesn't have a homepage. + + - Claiming failed (in this case the error message contains more + details). + + Returns: + Callable[[~.ClaimHomepageRequest], + ~.Homepage]: + 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 'claim_homepage' not in self._stubs: + self._stubs['claim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/ClaimHomepage', + request_serializer=homepage.ClaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['claim_homepage'] + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + homepage.Homepage]: + r"""Return a callable for the unclaim homepage method over gRPC. + + Unclaims a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UnclaimHomepageRequest], + ~.Homepage]: + 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 'unclaim_homepage' not in self._stubs: + self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/UnclaimHomepage', + request_serializer=homepage.UnclaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['unclaim_homepage'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'HomepageServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..aa284e548951 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py @@ -0,0 +1,486 @@ +# -*- 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.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from .base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import HomepageServiceGrpcTransport + +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.accounts.v1.HomepageService", + "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.accounts.v1.HomepageService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HomepageServiceGrpcAsyncIOTransport(HomepageServiceTransport): + """gRPC AsyncIO backend transport for HomepageService. + + Service to support an API for a store's homepage. + + 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 get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + Awaitable[homepage.Homepage]]: + r"""Return a callable for the get homepage method over gRPC. + + Retrieves a store's homepage. + + Returns: + Callable[[~.GetHomepageRequest], + Awaitable[~.Homepage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_homepage' not in self._stubs: + self._stubs['get_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/GetHomepage', + request_serializer=homepage.GetHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['get_homepage'] + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + Awaitable[gsma_homepage.Homepage]]: + r"""Return a callable for the update homepage method over gRPC. + + Updates a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UpdateHomepageRequest], + Awaitable[~.Homepage]]: + 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 'update_homepage' not in self._stubs: + self._stubs['update_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/UpdateHomepage', + request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, + response_deserializer=gsma_homepage.Homepage.deserialize, + ) + return self._stubs['update_homepage'] + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + Awaitable[homepage.Homepage]]: + r"""Return a callable for the claim homepage method over gRPC. + + Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the business is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. + + In case of failure, a canonical error message is returned: + + :: + + * PERMISSION_DENIED: User doesn't have the necessary permissions on this + Merchant Center account. + + * FAILED_PRECONDITION: + + - The account is not a Merchant Center account. + + - Merchant Center account doesn't have a homepage. + + - Claiming failed (in this case the error message contains more + details). + + Returns: + Callable[[~.ClaimHomepageRequest], + Awaitable[~.Homepage]]: + 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 'claim_homepage' not in self._stubs: + self._stubs['claim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/ClaimHomepage', + request_serializer=homepage.ClaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['claim_homepage'] + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + Awaitable[homepage.Homepage]]: + r"""Return a callable for the unclaim homepage method over gRPC. + + Unclaims a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UnclaimHomepageRequest], + Awaitable[~.Homepage]]: + 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 'unclaim_homepage' not in self._stubs: + self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.HomepageService/UnclaimHomepage', + request_serializer=homepage.UnclaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['unclaim_homepage'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_homepage: self._wrap_method( + self.get_homepage, + default_timeout=None, + client_info=client_info, + ), + self.update_homepage: self._wrap_method( + self.update_homepage, + default_timeout=None, + client_info=client_info, + ), + self.claim_homepage: self._wrap_method( + self.claim_homepage, + default_timeout=None, + client_info=client_info, + ), + self.unclaim_homepage: self._wrap_method( + self.unclaim_homepage, + 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__ = ( + 'HomepageServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py new file mode 100644 index 000000000000..ac3d6aafaed9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py @@ -0,0 +1,918 @@ +# -*- 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.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage + + +from .rest_base import _BaseHomepageServiceRestTransport +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 HomepageServiceRestInterceptor: + """Interceptor for HomepageService. + + 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 HomepageServiceRestTransport. + + .. code-block:: python + class MyCustomHomepageServiceInterceptor(HomepageServiceRestInterceptor): + def pre_claim_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_claim_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_unclaim_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_unclaim_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + transport = HomepageServiceRestTransport(interceptor=MyCustomHomepageServiceInterceptor()) + client = HomepageServiceClient(transport=transport) + + + """ + def pre_claim_homepage(self, request: homepage.ClaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for claim_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_claim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: + """Post-rpc interceptor for claim_homepage + + DEPRECATED. Please use the `post_claim_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_claim_homepage` interceptor runs + before the `post_claim_homepage_with_metadata` interceptor. + """ + return response + + def post_claim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for claim_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_claim_homepage_with_metadata` + interceptor in new development instead of the `post_claim_homepage` interceptor. + When both interceptors are used, this `post_claim_homepage_with_metadata` interceptor runs after the + `post_claim_homepage` interceptor. The (possibly modified) response returned by + `post_claim_homepage` will be passed to + `post_claim_homepage_with_metadata`. + """ + return response, metadata + + def pre_get_homepage(self, request: homepage.GetHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_get_homepage(self, response: homepage.Homepage) -> homepage.Homepage: + """Post-rpc interceptor for get_homepage + + DEPRECATED. Please use the `post_get_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_get_homepage` interceptor runs + before the `post_get_homepage_with_metadata` interceptor. + """ + return response + + def post_get_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_get_homepage_with_metadata` + interceptor in new development instead of the `post_get_homepage` interceptor. + When both interceptors are used, this `post_get_homepage_with_metadata` interceptor runs after the + `post_get_homepage` interceptor. The (possibly modified) response returned by + `post_get_homepage` will be passed to + `post_get_homepage_with_metadata`. + """ + return response, metadata + + def pre_unclaim_homepage(self, request: homepage.UnclaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for unclaim_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_unclaim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: + """Post-rpc interceptor for unclaim_homepage + + DEPRECATED. Please use the `post_unclaim_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_unclaim_homepage` interceptor runs + before the `post_unclaim_homepage_with_metadata` interceptor. + """ + return response + + def post_unclaim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for unclaim_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_unclaim_homepage_with_metadata` + interceptor in new development instead of the `post_unclaim_homepage` interceptor. + When both interceptors are used, this `post_unclaim_homepage_with_metadata` interceptor runs after the + `post_unclaim_homepage` interceptor. The (possibly modified) response returned by + `post_unclaim_homepage` will be passed to + `post_unclaim_homepage_with_metadata`. + """ + return response, metadata + + def pre_update_homepage(self, request: gsma_homepage.UpdateHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_update_homepage(self, response: gsma_homepage.Homepage) -> gsma_homepage.Homepage: + """Post-rpc interceptor for update_homepage + + DEPRECATED. Please use the `post_update_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_update_homepage` interceptor runs + before the `post_update_homepage_with_metadata` interceptor. + """ + return response + + def post_update_homepage_with_metadata(self, response: gsma_homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_update_homepage_with_metadata` + interceptor in new development instead of the `post_update_homepage` interceptor. + When both interceptors are used, this `post_update_homepage_with_metadata` interceptor runs after the + `post_update_homepage` interceptor. The (possibly modified) response returned by + `post_update_homepage` will be passed to + `post_update_homepage_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class HomepageServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: HomepageServiceRestInterceptor + + +class HomepageServiceRestTransport(_BaseHomepageServiceRestTransport): + """REST backend synchronous transport for HomepageService. + + Service to support an API for a store's homepage. + + 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[HomepageServiceRestInterceptor] = 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 HomepageServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ClaimHomepage(_BaseHomepageServiceRestTransport._BaseClaimHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.ClaimHomepage") + + @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: homepage.ClaimHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> homepage.Homepage: + r"""Call the claim homepage method over HTTP. + + Args: + request (~.homepage.ClaimHomepageRequest): + The request object. Request message for the ``ClaimHomepage`` 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: + ~.homepage.Homepage: + The ``Homepage`` message represents a business's store + homepage within the system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof of + ownership and allows the business to unlock features + that require a verified website. For more information, + see `Understanding online store URL + verification `__. + + """ + + http_options = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_http_options() + + request, metadata = self._interceptor.pre_claim_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_transcoded_request(http_options, request) + + body = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.ClaimHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "ClaimHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._ClaimHomepage._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 = homepage.Homepage() + pb_resp = homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_claim_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_claim_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = homepage.Homepage.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.accounts_v1.HomepageServiceClient.claim_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "ClaimHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetHomepage(_BaseHomepageServiceRestTransport._BaseGetHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.GetHomepage") + + @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: homepage.GetHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> homepage.Homepage: + r"""Call the get homepage method over HTTP. + + Args: + request (~.homepage.GetHomepageRequest): + The request object. Request message for the ``GetHomepage`` 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: + ~.homepage.Homepage: + The ``Homepage`` message represents a business's store + homepage within the system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof of + ownership and allows the business to unlock features + that require a verified website. For more information, + see `Understanding online store URL + verification `__. + + """ + + http_options = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_http_options() + + request, metadata = self._interceptor.pre_get_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.GetHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "GetHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._GetHomepage._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 = homepage.Homepage() + pb_resp = homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = homepage.Homepage.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.accounts_v1.HomepageServiceClient.get_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "GetHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UnclaimHomepage(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.UnclaimHomepage") + + @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: homepage.UnclaimHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> homepage.Homepage: + r"""Call the unclaim homepage method over HTTP. + + Args: + request (~.homepage.UnclaimHomepageRequest): + The request object. Request message for the ``UnclaimHomepage`` 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: + ~.homepage.Homepage: + The ``Homepage`` message represents a business's store + homepage within the system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof of + ownership and allows the business to unlock features + that require a verified website. For more information, + see `Understanding online store URL + verification `__. + + """ + + http_options = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_http_options() + + request, metadata = self._interceptor.pre_unclaim_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_transcoded_request(http_options, request) + + body = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.UnclaimHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "UnclaimHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._UnclaimHomepage._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 = homepage.Homepage() + pb_resp = homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_unclaim_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_unclaim_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = homepage.Homepage.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.accounts_v1.HomepageServiceClient.unclaim_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "UnclaimHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateHomepage(_BaseHomepageServiceRestTransport._BaseUpdateHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.UpdateHomepage") + + @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: gsma_homepage.UpdateHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_homepage.Homepage: + r"""Call the update homepage method over HTTP. + + Args: + request (~.gsma_homepage.UpdateHomepageRequest): + The request object. Request message for the ``UpdateHomepage`` 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: + ~.gsma_homepage.Homepage: + The ``Homepage`` message represents a business's store + homepage within the system. + + A business's homepage is the primary domain where + customers interact with their store. + + The homepage can be claimed and verified as a proof of + ownership and allows the business to unlock features + that require a verified website. For more information, + see `Understanding online store URL + verification `__. + + """ + + http_options = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_http_options() + + request, metadata = self._interceptor.pre_update_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_transcoded_request(http_options, request) + + body = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.UpdateHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "UpdateHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._UpdateHomepage._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 = gsma_homepage.Homepage() + pb_resp = gsma_homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_homepage.Homepage.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.accounts_v1.HomepageServiceClient.update_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", + "rpcName": "UpdateHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + homepage.Homepage]: + # 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._ClaimHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + homepage.Homepage]: + # 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._GetHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + homepage.Homepage]: + # 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._UnclaimHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + gsma_homepage.Homepage]: + # 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._UpdateHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'HomepageServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py new file mode 100644 index 000000000000..5dde88abe3b1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py @@ -0,0 +1,270 @@ +# -*- 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 HomepageServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage + + +class _BaseHomepageServiceRestTransport(HomepageServiceTransport): + """Base REST backend transport for HomepageService. + + 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 _BaseClaimHomepage: + 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': '/accounts/v1/{name=accounts/*/homepage}:claim', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = homepage.ClaimHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseClaimHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetHomepage: + 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': '/accounts/v1/{name=accounts/*/homepage}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = homepage.GetHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseGetHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUnclaimHomepage: + 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': '/accounts/v1/{name=accounts/*/homepage}:unclaim', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = homepage.UnclaimHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateHomepage: + 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': 'patch', + 'uri': '/accounts/v1/{homepage.name=accounts/*/homepage}', + 'body': 'homepage', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_homepage.UpdateHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseHomepageServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py new file mode 100644 index 000000000000..bdfa6c11d195 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_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 LfpProvidersServiceClient +from .async_client import LfpProvidersServiceAsyncClient + +__all__ = ( + 'LfpProvidersServiceClient', + 'LfpProvidersServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py new file mode 100644 index 000000000000..d85ddd3eb7f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py @@ -0,0 +1,503 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import pagers +from google.shopping.merchant_accounts_v1.types import lfpproviders +from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport +from .client import LfpProvidersServiceClient + +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 LfpProvidersServiceAsyncClient: + """The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + """ + + _client: LfpProvidersServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LfpProvidersServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LfpProvidersServiceClient._DEFAULT_UNIVERSE + + lfp_provider_path = staticmethod(LfpProvidersServiceClient.lfp_provider_path) + parse_lfp_provider_path = staticmethod(LfpProvidersServiceClient.parse_lfp_provider_path) + omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.omnichannel_setting_path) + parse_omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.parse_omnichannel_setting_path) + common_billing_account_path = staticmethod(LfpProvidersServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LfpProvidersServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LfpProvidersServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LfpProvidersServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LfpProvidersServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LfpProvidersServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LfpProvidersServiceClient.common_project_path) + parse_common_project_path = staticmethod(LfpProvidersServiceClient.parse_common_project_path) + common_location_path = staticmethod(LfpProvidersServiceClient.common_location_path) + parse_common_location_path = staticmethod(LfpProvidersServiceClient.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: + LfpProvidersServiceAsyncClient: The constructed client. + """ + return LfpProvidersServiceClient.from_service_account_info.__func__(LfpProvidersServiceAsyncClient, 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: + LfpProvidersServiceAsyncClient: The constructed client. + """ + return LfpProvidersServiceClient.from_service_account_file.__func__(LfpProvidersServiceAsyncClient, 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 LfpProvidersServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LfpProvidersServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpProvidersServiceTransport: 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 = LfpProvidersServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp providers 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,LfpProvidersServiceTransport,Callable[..., LfpProvidersServiceTransport]]]): + 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 LfpProvidersServiceTransport 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 = LfpProvidersServiceClient( + 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.accounts_v1.LfpProvidersServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "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.accounts.v1.LfpProvidersService", + "credentialsType": None, + } + ) + + async def find_lfp_providers(self, + request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersAsyncPager: + r"""Find the LFP provider candidates in a given country. + + .. 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_accounts_v1 + + async def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.FindLfpProvidersRequest, dict]]): + The request object. Request message for the + FindLfpProviders method. + parent (:class:`str`): + Required. The name of the parent resource under which + the LFP providers are found. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. + + 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_accounts_v1.services.lfp_providers_service.pagers.FindLfpProvidersAsyncPager: + Response message for the + FindLfpProviders 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, lfpproviders.FindLfpProvidersRequest): + request = lfpproviders.FindLfpProvidersRequest(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.find_lfp_providers] + + # 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.FindLfpProvidersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def link_lfp_provider(self, + request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: + r"""Link the specified merchant to a LFP provider for the + specified country. + + .. 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_accounts_v1 + + async def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = await client.link_lfp_provider(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.LinkLfpProviderRequest, dict]]): + The request object. Request message for the + LinkLfpProvider method. + name (:class:`str`): + Required. The name of the LFP provider resource to link. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. + The ``lfp_provider`` is the LFP provider ID. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.LinkLfpProviderResponse: + Response message for the + LinkLfpProvider method. + + """ + # 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, lfpproviders.LinkLfpProviderRequest): + request = lfpproviders.LinkLfpProviderRequest(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.link_lfp_provider] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "LfpProvidersServiceAsyncClient": + 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__ = ( + "LfpProvidersServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py new file mode 100644 index 000000000000..329721f9aec6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py @@ -0,0 +1,871 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import pagers +from google.shopping.merchant_accounts_v1.types import lfpproviders +from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LfpProvidersServiceGrpcTransport +from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport +from .transports.rest import LfpProvidersServiceRestTransport + + +class LfpProvidersServiceClientMeta(type): + """Metaclass for the LfpProvidersService 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[LfpProvidersServiceTransport]] + _transport_registry["grpc"] = LfpProvidersServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LfpProvidersServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LfpProvidersServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LfpProvidersServiceTransport]: + """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 LfpProvidersServiceClient(metaclass=LfpProvidersServiceClientMeta): + """The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + """ + + @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: + LfpProvidersServiceClient: 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: + LfpProvidersServiceClient: 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) -> LfpProvidersServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpProvidersServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def lfp_provider_path(account: str,omnichannel_setting: str,lfp_provider: str,) -> str: + """Returns a fully-qualified lfp_provider string.""" + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) + + @staticmethod + def parse_lfp_provider_path(path: str) -> Dict[str,str]: + """Parses a lfp_provider path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)/lfpProviders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: + """Returns a fully-qualified omnichannel_setting string.""" + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + + @staticmethod + def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: + """Parses a omnichannel_setting path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?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 = LfpProvidersServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LfpProvidersServiceClient._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 = LfpProvidersServiceClient._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, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp providers 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,LfpProvidersServiceTransport,Callable[..., LfpProvidersServiceTransport]]]): + 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 LfpProvidersServiceTransport 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 = LfpProvidersServiceClient._read_environment_variables() + self._client_cert_source = LfpProvidersServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LfpProvidersServiceClient._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, LfpProvidersServiceTransport) + if transport_provided: + # transport is a LfpProvidersServiceTransport 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(LfpProvidersServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LfpProvidersServiceClient._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[LfpProvidersServiceTransport], Callable[..., LfpProvidersServiceTransport]] = ( + LfpProvidersServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LfpProvidersServiceTransport], 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.accounts_v1.LfpProvidersServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "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.accounts.v1.LfpProvidersService", + "credentialsType": None, + } + ) + + def find_lfp_providers(self, + request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersPager: + r"""Find the LFP provider candidates in a given country. + + .. 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_accounts_v1 + + def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.FindLfpProvidersRequest, dict]): + The request object. Request message for the + FindLfpProviders method. + parent (str): + Required. The name of the parent resource under which + the LFP providers are found. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. + + 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_accounts_v1.services.lfp_providers_service.pagers.FindLfpProvidersPager: + Response message for the + FindLfpProviders 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, lfpproviders.FindLfpProvidersRequest): + request = lfpproviders.FindLfpProvidersRequest(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.find_lfp_providers] + + # 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.FindLfpProvidersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def link_lfp_provider(self, + request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: + r"""Link the specified merchant to a LFP provider for the + specified country. + + .. 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_accounts_v1 + + def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = client.link_lfp_provider(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.LinkLfpProviderRequest, dict]): + The request object. Request message for the + LinkLfpProvider method. + name (str): + Required. The name of the LFP provider resource to link. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. + The ``lfp_provider`` is the LFP provider ID. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.LinkLfpProviderResponse: + Response message for the + LinkLfpProvider method. + + """ + # 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, lfpproviders.LinkLfpProviderRequest): + request = lfpproviders.LinkLfpProviderRequest(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.link_lfp_provider] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LfpProvidersServiceClient": + 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__ = ( + "LfpProvidersServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py new file mode 100644 index 000000000000..53a009bf4800 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_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_accounts_v1.types import lfpproviders + + +class FindLfpProvidersPager: + """A pager for iterating through ``find_lfp_providers`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.FindLfpProvidersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lfp_providers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FindLfpProviders`` requests and continue to iterate + through the ``lfp_providers`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.FindLfpProvidersResponse` + 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[..., lfpproviders.FindLfpProvidersResponse], + request: lfpproviders.FindLfpProvidersRequest, + response: lfpproviders.FindLfpProvidersResponse, + *, + 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_accounts_v1.types.FindLfpProvidersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.FindLfpProvidersResponse): + 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 = lfpproviders.FindLfpProvidersRequest(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[lfpproviders.FindLfpProvidersResponse]: + 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[lfpproviders.LfpProvider]: + for page in self.pages: + yield from page.lfp_providers + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class FindLfpProvidersAsyncPager: + """A pager for iterating through ``find_lfp_providers`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.FindLfpProvidersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lfp_providers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FindLfpProviders`` requests and continue to iterate + through the ``lfp_providers`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.FindLfpProvidersResponse` + 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[lfpproviders.FindLfpProvidersResponse]], + request: lfpproviders.FindLfpProvidersRequest, + response: lfpproviders.FindLfpProvidersResponse, + *, + 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_accounts_v1.types.FindLfpProvidersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.FindLfpProvidersResponse): + 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 = lfpproviders.FindLfpProvidersRequest(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[lfpproviders.FindLfpProvidersResponse]: + 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[lfpproviders.LfpProvider]: + async def async_generator(): + async for page in self.pages: + for response in page.lfp_providers: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst new file mode 100644 index 000000000000..9ef07da24bc0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LfpProvidersServiceTransport` is the ABC for all transports. +- public child `LfpProvidersServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LfpProvidersServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLfpProvidersServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LfpProvidersServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py new file mode 100644 index 000000000000..f6510b1f8477 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_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 LfpProvidersServiceTransport +from .grpc import LfpProvidersServiceGrpcTransport +from .grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport +from .rest import LfpProvidersServiceRestTransport +from .rest import LfpProvidersServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LfpProvidersServiceTransport]] +_transport_registry['grpc'] = LfpProvidersServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LfpProvidersServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LfpProvidersServiceRestTransport + +__all__ = ( + 'LfpProvidersServiceTransport', + 'LfpProvidersServiceGrpcTransport', + 'LfpProvidersServiceGrpcAsyncIOTransport', + 'LfpProvidersServiceRestTransport', + 'LfpProvidersServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py new file mode 100644 index 000000000000..c4a1d5c5a99f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import lfpproviders + +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 LfpProvidersServiceTransport(abc.ABC): + """Abstract transport class for LfpProvidersService.""" + + 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.find_lfp_providers: gapic_v1.method.wrap_method( + self.find_lfp_providers, + default_timeout=None, + client_info=client_info, + ), + self.link_lfp_provider: gapic_v1.method.wrap_method( + self.link_lfp_provider, + 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 find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + Union[ + lfpproviders.FindLfpProvidersResponse, + Awaitable[lfpproviders.FindLfpProvidersResponse] + ]]: + raise NotImplementedError() + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + Union[ + lfpproviders.LinkLfpProviderResponse, + Awaitable[lfpproviders.LinkLfpProviderResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LfpProvidersServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py new file mode 100644 index 000000000000..b2712bf438f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py @@ -0,0 +1,376 @@ +# -*- 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.shopping.merchant_accounts_v1.types import lfpproviders +from .base import LfpProvidersServiceTransport, 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.accounts.v1.LfpProvidersService", + "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.accounts.v1.LfpProvidersService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpProvidersServiceGrpcTransport(LfpProvidersServiceTransport): + """gRPC backend transport for LfpProvidersService. + + The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + + 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 find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + lfpproviders.FindLfpProvidersResponse]: + r"""Return a callable for the find lfp providers method over gRPC. + + Find the LFP provider candidates in a given country. + + Returns: + Callable[[~.FindLfpProvidersRequest], + ~.FindLfpProvidersResponse]: + 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 'find_lfp_providers' not in self._stubs: + self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.LfpProvidersService/FindLfpProviders', + request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, + response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, + ) + return self._stubs['find_lfp_providers'] + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + lfpproviders.LinkLfpProviderResponse]: + r"""Return a callable for the link lfp provider method over gRPC. + + Link the specified merchant to a LFP provider for the + specified country. + + Returns: + Callable[[~.LinkLfpProviderRequest], + ~.LinkLfpProviderResponse]: + 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 'link_lfp_provider' not in self._stubs: + self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.LfpProvidersService/LinkLfpProvider', + request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, + response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, + ) + return self._stubs['link_lfp_provider'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LfpProvidersServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..a6c7f3a46da0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py @@ -0,0 +1,402 @@ +# -*- 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.shopping.merchant_accounts_v1.types import lfpproviders +from .base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LfpProvidersServiceGrpcTransport + +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.accounts.v1.LfpProvidersService", + "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.accounts.v1.LfpProvidersService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpProvidersServiceGrpcAsyncIOTransport(LfpProvidersServiceTransport): + """gRPC AsyncIO backend transport for LfpProvidersService. + + The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + + 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 find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + Awaitable[lfpproviders.FindLfpProvidersResponse]]: + r"""Return a callable for the find lfp providers method over gRPC. + + Find the LFP provider candidates in a given country. + + Returns: + Callable[[~.FindLfpProvidersRequest], + Awaitable[~.FindLfpProvidersResponse]]: + 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 'find_lfp_providers' not in self._stubs: + self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.LfpProvidersService/FindLfpProviders', + request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, + response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, + ) + return self._stubs['find_lfp_providers'] + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + Awaitable[lfpproviders.LinkLfpProviderResponse]]: + r"""Return a callable for the link lfp provider method over gRPC. + + Link the specified merchant to a LFP provider for the + specified country. + + Returns: + Callable[[~.LinkLfpProviderRequest], + Awaitable[~.LinkLfpProviderResponse]]: + 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 'link_lfp_provider' not in self._stubs: + self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.LfpProvidersService/LinkLfpProvider', + request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, + response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, + ) + return self._stubs['link_lfp_provider'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.find_lfp_providers: self._wrap_method( + self.find_lfp_providers, + default_timeout=None, + client_info=client_info, + ), + self.link_lfp_provider: self._wrap_method( + self.link_lfp_provider, + 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__ = ( + 'LfpProvidersServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py new file mode 100644 index 000000000000..57d1bb8ac958 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py @@ -0,0 +1,534 @@ +# -*- 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.shopping.merchant_accounts_v1.types import lfpproviders + + +from .rest_base import _BaseLfpProvidersServiceRestTransport +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 LfpProvidersServiceRestInterceptor: + """Interceptor for LfpProvidersService. + + 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 LfpProvidersServiceRestTransport. + + .. code-block:: python + class MyCustomLfpProvidersServiceInterceptor(LfpProvidersServiceRestInterceptor): + def pre_find_lfp_providers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_find_lfp_providers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_link_lfp_provider(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_link_lfp_provider(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LfpProvidersServiceRestTransport(interceptor=MyCustomLfpProvidersServiceInterceptor()) + client = LfpProvidersServiceClient(transport=transport) + + + """ + def pre_find_lfp_providers(self, request: lfpproviders.FindLfpProvidersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for find_lfp_providers + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpProvidersService server. + """ + return request, metadata + + def post_find_lfp_providers(self, response: lfpproviders.FindLfpProvidersResponse) -> lfpproviders.FindLfpProvidersResponse: + """Post-rpc interceptor for find_lfp_providers + + DEPRECATED. Please use the `post_find_lfp_providers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LfpProvidersService server but before + it is returned to user code. This `post_find_lfp_providers` interceptor runs + before the `post_find_lfp_providers_with_metadata` interceptor. + """ + return response + + def post_find_lfp_providers_with_metadata(self, response: lfpproviders.FindLfpProvidersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for find_lfp_providers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LfpProvidersService server but before it is returned to user code. + + We recommend only using this `post_find_lfp_providers_with_metadata` + interceptor in new development instead of the `post_find_lfp_providers` interceptor. + When both interceptors are used, this `post_find_lfp_providers_with_metadata` interceptor runs after the + `post_find_lfp_providers` interceptor. The (possibly modified) response returned by + `post_find_lfp_providers` will be passed to + `post_find_lfp_providers_with_metadata`. + """ + return response, metadata + + def pre_link_lfp_provider(self, request: lfpproviders.LinkLfpProviderRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for link_lfp_provider + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpProvidersService server. + """ + return request, metadata + + def post_link_lfp_provider(self, response: lfpproviders.LinkLfpProviderResponse) -> lfpproviders.LinkLfpProviderResponse: + """Post-rpc interceptor for link_lfp_provider + + DEPRECATED. Please use the `post_link_lfp_provider_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LfpProvidersService server but before + it is returned to user code. This `post_link_lfp_provider` interceptor runs + before the `post_link_lfp_provider_with_metadata` interceptor. + """ + return response + + def post_link_lfp_provider_with_metadata(self, response: lfpproviders.LinkLfpProviderResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for link_lfp_provider + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LfpProvidersService server but before it is returned to user code. + + We recommend only using this `post_link_lfp_provider_with_metadata` + interceptor in new development instead of the `post_link_lfp_provider` interceptor. + When both interceptors are used, this `post_link_lfp_provider_with_metadata` interceptor runs after the + `post_link_lfp_provider` interceptor. The (possibly modified) response returned by + `post_link_lfp_provider` will be passed to + `post_link_lfp_provider_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class LfpProvidersServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LfpProvidersServiceRestInterceptor + + +class LfpProvidersServiceRestTransport(_BaseLfpProvidersServiceRestTransport): + """REST backend synchronous transport for LfpProvidersService. + + The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + + 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[LfpProvidersServiceRestInterceptor] = 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 LfpProvidersServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _FindLfpProviders(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders, LfpProvidersServiceRestStub): + def __hash__(self): + return hash("LfpProvidersServiceRestTransport.FindLfpProviders") + + @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: lfpproviders.FindLfpProvidersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpproviders.FindLfpProvidersResponse: + r"""Call the find lfp providers method over HTTP. + + Args: + request (~.lfpproviders.FindLfpProvidersRequest): + The request object. Request message for the + FindLfpProviders 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: + ~.lfpproviders.FindLfpProvidersResponse: + Response message for the + FindLfpProviders method. + + """ + + http_options = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_http_options() + + request, metadata = self._interceptor.pre_find_lfp_providers(request, metadata) + transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.LfpProvidersServiceClient.FindLfpProviders", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "rpcName": "FindLfpProviders", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpProvidersServiceRestTransport._FindLfpProviders._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 = lfpproviders.FindLfpProvidersResponse() + pb_resp = lfpproviders.FindLfpProvidersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_find_lfp_providers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_find_lfp_providers_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpproviders.FindLfpProvidersResponse.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.accounts_v1.LfpProvidersServiceClient.find_lfp_providers", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "rpcName": "FindLfpProviders", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _LinkLfpProvider(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider, LfpProvidersServiceRestStub): + def __hash__(self): + return hash("LfpProvidersServiceRestTransport.LinkLfpProvider") + + @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: lfpproviders.LinkLfpProviderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpproviders.LinkLfpProviderResponse: + r"""Call the link lfp provider method over HTTP. + + Args: + request (~.lfpproviders.LinkLfpProviderRequest): + The request object. Request message for the + LinkLfpProvider 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: + ~.lfpproviders.LinkLfpProviderResponse: + Response message for the + LinkLfpProvider method. + + """ + + http_options = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_http_options() + + request, metadata = self._interceptor.pre_link_lfp_provider(request, metadata) + transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_transcoded_request(http_options, request) + + body = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.LfpProvidersServiceClient.LinkLfpProvider", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "rpcName": "LinkLfpProvider", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpProvidersServiceRestTransport._LinkLfpProvider._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 = lfpproviders.LinkLfpProviderResponse() + pb_resp = lfpproviders.LinkLfpProviderResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_link_lfp_provider(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_link_lfp_provider_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpproviders.LinkLfpProviderResponse.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.accounts_v1.LfpProvidersServiceClient.link_lfp_provider", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "rpcName": "LinkLfpProvider", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + lfpproviders.FindLfpProvidersResponse]: + # 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._FindLfpProviders(self._session, self._host, self._interceptor) # type: ignore + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + lfpproviders.LinkLfpProviderResponse]: + # 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._LinkLfpProvider(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LfpProvidersServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py new file mode 100644 index 000000000000..ad33e0ffb372 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import lfpproviders + + +class _BaseLfpProvidersServiceRestTransport(LfpProvidersServiceTransport): + """Base REST backend transport for LfpProvidersService. + + 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 _BaseFindLfpProviders: + 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': '/accounts/v1/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpproviders.FindLfpProvidersRequest.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(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseLinkLfpProvider: + 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': '/accounts/v1/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpproviders.LinkLfpProviderRequest.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(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLfpProvidersServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py new file mode 100644 index 000000000000..242598846a6e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_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 OmnichannelSettingsServiceClient +from .async_client import OmnichannelSettingsServiceAsyncClient + +__all__ = ( + 'OmnichannelSettingsServiceClient', + 'OmnichannelSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py new file mode 100644 index 000000000000..f321a178bbe4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py @@ -0,0 +1,866 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import pagers +from google.shopping.merchant_accounts_v1.types import omnichannelsettings +from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport +from .client import OmnichannelSettingsServiceClient + +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 OmnichannelSettingsServiceAsyncClient: + """The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + """ + + _client: OmnichannelSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(OmnichannelSettingsServiceClient.account_path) + parse_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_account_path) + omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.omnichannel_setting_path) + parse_omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.parse_omnichannel_setting_path) + common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OmnichannelSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OmnichannelSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OmnichannelSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(OmnichannelSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(OmnichannelSettingsServiceClient.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: + OmnichannelSettingsServiceAsyncClient: The constructed client. + """ + return OmnichannelSettingsServiceClient.from_service_account_info.__func__(OmnichannelSettingsServiceAsyncClient, 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: + OmnichannelSettingsServiceAsyncClient: The constructed client. + """ + return OmnichannelSettingsServiceClient.from_service_account_file.__func__(OmnichannelSettingsServiceAsyncClient, 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 OmnichannelSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> OmnichannelSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OmnichannelSettingsServiceTransport: 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 = OmnichannelSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the omnichannel settings 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,OmnichannelSettingsServiceTransport,Callable[..., OmnichannelSettingsServiceTransport]]]): + 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 OmnichannelSettingsServiceTransport 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 = OmnichannelSettingsServiceClient( + 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.accounts_v1.OmnichannelSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "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.accounts.v1.OmnichannelSettingsService", + "credentialsType": None, + } + ) + + async def get_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Get the omnichannel settings for a given merchant. + + .. 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_accounts_v1 + + async def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetOmnichannelSettingRequest, dict]]): + The request object. Request message for the + GetOmnichannelSettings method. + name (:class:`str`): + Required. The name of the omnichannel setting to + retrieve. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannelsettings.GetOmnichannelSettingRequest): + request = omnichannelsettings.GetOmnichannelSettingRequest(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.get_omnichannel_setting] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_omnichannel_settings(self, + request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsAsyncPager: + r"""List all the omnichannel settings for a given + merchant. + + .. 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_accounts_v1 + + async def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsRequest, dict]]): + The request object. Request message for the + ListOmnichannelSettings method. + parent (:class:`str`): + Required. The parent, which owns this collection of + omnichannel settings. Format: ``accounts/{account}`` + + 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_accounts_v1.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsAsyncPager: + Response message for the + ListOmnichannelSettings 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, omnichannelsettings.ListOmnichannelSettingsRequest): + request = omnichannelsettings.ListOmnichannelSettingsRequest(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_omnichannel_settings] + + # 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.ListOmnichannelSettingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, + *, + parent: Optional[str] = None, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Create the omnichannel settings for a given merchant. + + .. 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_accounts_v1 + + async def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.CreateOmnichannelSettingRequest, dict]]): + The request object. Request message for the + CreateOmnichannelSetting method. + parent (:class:`str`): + Required. The parent resource where this omnichannel + setting will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + omnichannel_setting (:class:`google.shopping.merchant_accounts_v1.types.OmnichannelSetting`): + Required. The omnichannel setting to + create. + + This corresponds to the ``omnichannel_setting`` 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_accounts_v1.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannel_setting] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.CreateOmnichannelSettingRequest): + request = omnichannelsettings.CreateOmnichannelSettingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_omnichannel_setting] + + # 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 update_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, + *, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Update the omnichannel setting for a given merchant + in a given country. + + .. 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_accounts_v1 + + async def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateOmnichannelSettingRequest, dict]]): + The request object. Request message for the + UpdateOmnichannelSetting method. + omnichannel_setting (:class:`google.shopping.merchant_accounts_v1.types.OmnichannelSetting`): + Required. The omnichannel setting to update. + + The omnichannel setting's ``name`` field is used to + identify the omnichannel setting to be updated. + + This corresponds to the ``omnichannel_setting`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. + + The following fields are supported in snake_case only: + + - ``lsf_type`` + - ``in_stock`` + - ``pickup`` + - ``odo`` + - ``about`` + - ``inventory_verification`` + + Full replacement with wildcard ``*``\ is supported, + while empty/implied update mask is not. + + This corresponds to the ``update_mask`` 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_accounts_v1.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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 = [omnichannel_setting, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.UpdateOmnichannelSettingRequest): + request = omnichannelsettings.UpdateOmnichannelSettingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_omnichannel_setting] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("omnichannel_setting.name", request.omnichannel_setting.name), + )), + ) + + # 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 request_inventory_verification(self, + request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: + r"""Requests inventory verification for a given merchant + in a given country. + + .. 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_accounts_v1 + + async def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = await client.request_inventory_verification(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationRequest, dict]]): + The request object. Request message for the + RequestInventoryVerification method. + name (:class:`str`): + Required. The name of the omnichannel setting to request + inventory verification. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. + + """ + # 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, omnichannelsettings.RequestInventoryVerificationRequest): + request = omnichannelsettings.RequestInventoryVerificationRequest(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.request_inventory_verification] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "OmnichannelSettingsServiceAsyncClient": + 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__ = ( + "OmnichannelSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py new file mode 100644 index 000000000000..08b5ee2eb384 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py @@ -0,0 +1,1231 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import pagers +from google.shopping.merchant_accounts_v1.types import omnichannelsettings +from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OmnichannelSettingsServiceGrpcTransport +from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport +from .transports.rest import OmnichannelSettingsServiceRestTransport + + +class OmnichannelSettingsServiceClientMeta(type): + """Metaclass for the OmnichannelSettingsService 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[OmnichannelSettingsServiceTransport]] + _transport_registry["grpc"] = OmnichannelSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OmnichannelSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = OmnichannelSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[OmnichannelSettingsServiceTransport]: + """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 OmnichannelSettingsServiceClient(metaclass=OmnichannelSettingsServiceClientMeta): + """The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + """ + + @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: + OmnichannelSettingsServiceClient: 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: + OmnichannelSettingsServiceClient: 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) -> OmnichannelSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OmnichannelSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: + """Returns a fully-qualified omnichannel_setting string.""" + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + + @staticmethod + def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: + """Parses a omnichannel_setting path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?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 = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient._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, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the omnichannel settings 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,OmnichannelSettingsServiceTransport,Callable[..., OmnichannelSettingsServiceTransport]]]): + 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 OmnichannelSettingsServiceTransport 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 = OmnichannelSettingsServiceClient._read_environment_variables() + self._client_cert_source = OmnichannelSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = OmnichannelSettingsServiceClient._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, OmnichannelSettingsServiceTransport) + if transport_provided: + # transport is a OmnichannelSettingsServiceTransport 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(OmnichannelSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + OmnichannelSettingsServiceClient._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[OmnichannelSettingsServiceTransport], Callable[..., OmnichannelSettingsServiceTransport]] = ( + OmnichannelSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OmnichannelSettingsServiceTransport], 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.accounts_v1.OmnichannelSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "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.accounts.v1.OmnichannelSettingsService", + "credentialsType": None, + } + ) + + def get_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Get the omnichannel settings for a given merchant. + + .. 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_accounts_v1 + + def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetOmnichannelSettingRequest, dict]): + The request object. Request message for the + GetOmnichannelSettings method. + name (str): + Required. The name of the omnichannel setting to + retrieve. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannelsettings.GetOmnichannelSettingRequest): + request = omnichannelsettings.GetOmnichannelSettingRequest(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.get_omnichannel_setting] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_omnichannel_settings(self, + request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsPager: + r"""List all the omnichannel settings for a given + merchant. + + .. 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_accounts_v1 + + def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsRequest, dict]): + The request object. Request message for the + ListOmnichannelSettings method. + parent (str): + Required. The parent, which owns this collection of + omnichannel settings. Format: ``accounts/{account}`` + + 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_accounts_v1.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsPager: + Response message for the + ListOmnichannelSettings 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, omnichannelsettings.ListOmnichannelSettingsRequest): + request = omnichannelsettings.ListOmnichannelSettingsRequest(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_omnichannel_settings] + + # 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.ListOmnichannelSettingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, + *, + parent: Optional[str] = None, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Create the omnichannel settings for a given merchant. + + .. 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_accounts_v1 + + def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.CreateOmnichannelSettingRequest, dict]): + The request object. Request message for the + CreateOmnichannelSetting method. + parent (str): + Required. The parent resource where this omnichannel + setting will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + omnichannel_setting (google.shopping.merchant_accounts_v1.types.OmnichannelSetting): + Required. The omnichannel setting to + create. + + This corresponds to the ``omnichannel_setting`` 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_accounts_v1.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannel_setting] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.CreateOmnichannelSettingRequest): + request = omnichannelsettings.CreateOmnichannelSettingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_omnichannel_setting] + + # 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 update_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, + *, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Update the omnichannel setting for a given merchant + in a given country. + + .. 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_accounts_v1 + + def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateOmnichannelSettingRequest, dict]): + The request object. Request message for the + UpdateOmnichannelSetting method. + omnichannel_setting (google.shopping.merchant_accounts_v1.types.OmnichannelSetting): + Required. The omnichannel setting to update. + + The omnichannel setting's ``name`` field is used to + identify the omnichannel setting to be updated. + + This corresponds to the ``omnichannel_setting`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + + The following fields are supported in snake_case only: + + - ``lsf_type`` + - ``in_stock`` + - ``pickup`` + - ``odo`` + - ``about`` + - ``inventory_verification`` + + Full replacement with wildcard ``*``\ is supported, + while empty/implied update mask is not. + + This corresponds to the ``update_mask`` 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_accounts_v1.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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 = [omnichannel_setting, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.UpdateOmnichannelSettingRequest): + request = omnichannelsettings.UpdateOmnichannelSettingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_omnichannel_setting] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("omnichannel_setting.name", request.omnichannel_setting.name), + )), + ) + + # 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 request_inventory_verification(self, + request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: + r"""Requests inventory verification for a given merchant + in a given country. + + .. 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_accounts_v1 + + def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = client.request_inventory_verification(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationRequest, dict]): + The request object. Request message for the + RequestInventoryVerification method. + name (str): + Required. The name of the omnichannel setting to request + inventory verification. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. + + """ + # 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, omnichannelsettings.RequestInventoryVerificationRequest): + request = omnichannelsettings.RequestInventoryVerificationRequest(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.request_inventory_verification] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "OmnichannelSettingsServiceClient": + 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__ = ( + "OmnichannelSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py new file mode 100644 index 000000000000..3119bb94204c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_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_accounts_v1.types import omnichannelsettings + + +class ListOmnichannelSettingsPager: + """A pager for iterating through ``list_omnichannel_settings`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``omnichannel_settings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOmnichannelSettings`` requests and continue to iterate + through the ``omnichannel_settings`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsResponse` + 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[..., omnichannelsettings.ListOmnichannelSettingsResponse], + request: omnichannelsettings.ListOmnichannelSettingsRequest, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + *, + 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_accounts_v1.types.ListOmnichannelSettingsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsResponse): + 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 = omnichannelsettings.ListOmnichannelSettingsRequest(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[omnichannelsettings.ListOmnichannelSettingsResponse]: + 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[omnichannelsettings.OmnichannelSetting]: + for page in self.pages: + yield from page.omnichannel_settings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOmnichannelSettingsAsyncPager: + """A pager for iterating through ``list_omnichannel_settings`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``omnichannel_settings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOmnichannelSettings`` requests and continue to iterate + through the ``omnichannel_settings`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsResponse` + 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[omnichannelsettings.ListOmnichannelSettingsResponse]], + request: omnichannelsettings.ListOmnichannelSettingsRequest, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + *, + 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_accounts_v1.types.ListOmnichannelSettingsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsResponse): + 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 = omnichannelsettings.ListOmnichannelSettingsRequest(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[omnichannelsettings.ListOmnichannelSettingsResponse]: + 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[omnichannelsettings.OmnichannelSetting]: + async def async_generator(): + async for page in self.pages: + for response in page.omnichannel_settings: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst new file mode 100644 index 000000000000..494c6b3d2bd7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OmnichannelSettingsServiceTransport` is the ABC for all transports. +- public child `OmnichannelSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OmnichannelSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOmnichannelSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OmnichannelSettingsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py new file mode 100644 index 000000000000..60f6dbfcf9cd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_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 OmnichannelSettingsServiceTransport +from .grpc import OmnichannelSettingsServiceGrpcTransport +from .grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport +from .rest import OmnichannelSettingsServiceRestTransport +from .rest import OmnichannelSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] +_transport_registry['grpc'] = OmnichannelSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OmnichannelSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = OmnichannelSettingsServiceRestTransport + +__all__ = ( + 'OmnichannelSettingsServiceTransport', + 'OmnichannelSettingsServiceGrpcTransport', + 'OmnichannelSettingsServiceGrpcAsyncIOTransport', + 'OmnichannelSettingsServiceRestTransport', + 'OmnichannelSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py new file mode 100644 index 000000000000..0f5b4dadfbc9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py @@ -0,0 +1,215 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import omnichannelsettings + +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 OmnichannelSettingsServiceTransport(abc.ABC): + """Abstract transport class for OmnichannelSettingsService.""" + + 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.get_omnichannel_setting: gapic_v1.method.wrap_method( + self.get_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.list_omnichannel_settings: gapic_v1.method.wrap_method( + self.list_omnichannel_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_omnichannel_setting: gapic_v1.method.wrap_method( + self.create_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.update_omnichannel_setting: gapic_v1.method.wrap_method( + self.update_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.request_inventory_verification: gapic_v1.method.wrap_method( + self.request_inventory_verification, + 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 get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting] + ]]: + raise NotImplementedError() + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + Union[ + omnichannelsettings.ListOmnichannelSettingsResponse, + Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse] + ]]: + raise NotImplementedError() + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting] + ]]: + raise NotImplementedError() + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting] + ]]: + raise NotImplementedError() + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + Union[ + omnichannelsettings.RequestInventoryVerificationResponse, + Awaitable[omnichannelsettings.RequestInventoryVerificationResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'OmnichannelSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py new file mode 100644 index 000000000000..0cd69db8e3dc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py @@ -0,0 +1,459 @@ +# -*- 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.shopping.merchant_accounts_v1.types import omnichannelsettings +from .base import OmnichannelSettingsServiceTransport, 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.accounts.v1.OmnichannelSettingsService", + "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.accounts.v1.OmnichannelSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OmnichannelSettingsServiceGrpcTransport(OmnichannelSettingsServiceTransport): + """gRPC backend transport for OmnichannelSettingsService. + + The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + + 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 get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + r"""Return a callable for the get omnichannel setting method over gRPC. + + Get the omnichannel settings for a given merchant. + + Returns: + Callable[[~.GetOmnichannelSettingRequest], + ~.OmnichannelSetting]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_omnichannel_setting' not in self._stubs: + self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/GetOmnichannelSetting', + request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['get_omnichannel_setting'] + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + omnichannelsettings.ListOmnichannelSettingsResponse]: + r"""Return a callable for the list omnichannel settings method over gRPC. + + List all the omnichannel settings for a given + merchant. + + Returns: + Callable[[~.ListOmnichannelSettingsRequest], + ~.ListOmnichannelSettingsResponse]: + 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_omnichannel_settings' not in self._stubs: + self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/ListOmnichannelSettings', + request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, + response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, + ) + return self._stubs['list_omnichannel_settings'] + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + r"""Return a callable for the create omnichannel setting method over gRPC. + + Create the omnichannel settings for a given merchant. + + Returns: + Callable[[~.CreateOmnichannelSettingRequest], + ~.OmnichannelSetting]: + 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 'create_omnichannel_setting' not in self._stubs: + self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/CreateOmnichannelSetting', + request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['create_omnichannel_setting'] + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + r"""Return a callable for the update omnichannel setting method over gRPC. + + Update the omnichannel setting for a given merchant + in a given country. + + Returns: + Callable[[~.UpdateOmnichannelSettingRequest], + ~.OmnichannelSetting]: + 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 'update_omnichannel_setting' not in self._stubs: + self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/UpdateOmnichannelSetting', + request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['update_omnichannel_setting'] + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + omnichannelsettings.RequestInventoryVerificationResponse]: + r"""Return a callable for the request inventory verification method over gRPC. + + Requests inventory verification for a given merchant + in a given country. + + Returns: + Callable[[~.RequestInventoryVerificationRequest], + ~.RequestInventoryVerificationResponse]: + 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 'request_inventory_verification' not in self._stubs: + self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/RequestInventoryVerification', + request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, + response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, + ) + return self._stubs['request_inventory_verification'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'OmnichannelSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e7fa978af5f3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,500 @@ +# -*- 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.shopping.merchant_accounts_v1.types import omnichannelsettings +from .base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OmnichannelSettingsServiceGrpcTransport + +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.accounts.v1.OmnichannelSettingsService", + "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.accounts.v1.OmnichannelSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OmnichannelSettingsServiceGrpcAsyncIOTransport(OmnichannelSettingsServiceTransport): + """gRPC AsyncIO backend transport for OmnichannelSettingsService. + + The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + + 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 get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting]]: + r"""Return a callable for the get omnichannel setting method over gRPC. + + Get the omnichannel settings for a given merchant. + + Returns: + Callable[[~.GetOmnichannelSettingRequest], + Awaitable[~.OmnichannelSetting]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_omnichannel_setting' not in self._stubs: + self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/GetOmnichannelSetting', + request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['get_omnichannel_setting'] + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse]]: + r"""Return a callable for the list omnichannel settings method over gRPC. + + List all the omnichannel settings for a given + merchant. + + Returns: + Callable[[~.ListOmnichannelSettingsRequest], + Awaitable[~.ListOmnichannelSettingsResponse]]: + 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_omnichannel_settings' not in self._stubs: + self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/ListOmnichannelSettings', + request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, + response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, + ) + return self._stubs['list_omnichannel_settings'] + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting]]: + r"""Return a callable for the create omnichannel setting method over gRPC. + + Create the omnichannel settings for a given merchant. + + Returns: + Callable[[~.CreateOmnichannelSettingRequest], + Awaitable[~.OmnichannelSetting]]: + 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 'create_omnichannel_setting' not in self._stubs: + self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/CreateOmnichannelSetting', + request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['create_omnichannel_setting'] + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting]]: + r"""Return a callable for the update omnichannel setting method over gRPC. + + Update the omnichannel setting for a given merchant + in a given country. + + Returns: + Callable[[~.UpdateOmnichannelSettingRequest], + Awaitable[~.OmnichannelSetting]]: + 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 'update_omnichannel_setting' not in self._stubs: + self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/UpdateOmnichannelSetting', + request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['update_omnichannel_setting'] + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + Awaitable[omnichannelsettings.RequestInventoryVerificationResponse]]: + r"""Return a callable for the request inventory verification method over gRPC. + + Requests inventory verification for a given merchant + in a given country. + + Returns: + Callable[[~.RequestInventoryVerificationRequest], + Awaitable[~.RequestInventoryVerificationResponse]]: + 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 'request_inventory_verification' not in self._stubs: + self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/RequestInventoryVerification', + request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, + response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, + ) + return self._stubs['request_inventory_verification'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_omnichannel_setting: self._wrap_method( + self.get_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.list_omnichannel_settings: self._wrap_method( + self.list_omnichannel_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_omnichannel_setting: self._wrap_method( + self.create_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.update_omnichannel_setting: self._wrap_method( + self.update_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.request_inventory_verification: self._wrap_method( + self.request_inventory_verification, + 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__ = ( + 'OmnichannelSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py new file mode 100644 index 000000000000..3b2e087d3189 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py @@ -0,0 +1,1068 @@ +# -*- 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.shopping.merchant_accounts_v1.types import omnichannelsettings + + +from .rest_base import _BaseOmnichannelSettingsServiceRestTransport +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 OmnichannelSettingsServiceRestInterceptor: + """Interceptor for OmnichannelSettingsService. + + 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 OmnichannelSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomOmnichannelSettingsServiceInterceptor(OmnichannelSettingsServiceRestInterceptor): + def pre_create_omnichannel_setting(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_omnichannel_setting(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_omnichannel_setting(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_omnichannel_setting(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_omnichannel_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_omnichannel_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_request_inventory_verification(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_request_inventory_verification(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_omnichannel_setting(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_omnichannel_setting(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OmnichannelSettingsServiceRestTransport(interceptor=MyCustomOmnichannelSettingsServiceInterceptor()) + client = OmnichannelSettingsServiceClient(transport=transport) + + + """ + def pre_create_omnichannel_setting(self, request: omnichannelsettings.CreateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.CreateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_omnichannel_setting + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_create_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + """Post-rpc interceptor for create_omnichannel_setting + + DEPRECATED. Please use the `post_create_omnichannel_setting_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_create_omnichannel_setting` interceptor runs + before the `post_create_omnichannel_setting_with_metadata` interceptor. + """ + return response + + def post_create_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_omnichannel_setting + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_create_omnichannel_setting_with_metadata` + interceptor in new development instead of the `post_create_omnichannel_setting` interceptor. + When both interceptors are used, this `post_create_omnichannel_setting_with_metadata` interceptor runs after the + `post_create_omnichannel_setting` interceptor. The (possibly modified) response returned by + `post_create_omnichannel_setting` will be passed to + `post_create_omnichannel_setting_with_metadata`. + """ + return response, metadata + + def pre_get_omnichannel_setting(self, request: omnichannelsettings.GetOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.GetOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_omnichannel_setting + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_get_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + """Post-rpc interceptor for get_omnichannel_setting + + DEPRECATED. Please use the `post_get_omnichannel_setting_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_get_omnichannel_setting` interceptor runs + before the `post_get_omnichannel_setting_with_metadata` interceptor. + """ + return response + + def post_get_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_omnichannel_setting + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_omnichannel_setting_with_metadata` + interceptor in new development instead of the `post_get_omnichannel_setting` interceptor. + When both interceptors are used, this `post_get_omnichannel_setting_with_metadata` interceptor runs after the + `post_get_omnichannel_setting` interceptor. The (possibly modified) response returned by + `post_get_omnichannel_setting` will be passed to + `post_get_omnichannel_setting_with_metadata`. + """ + return response, metadata + + def pre_list_omnichannel_settings(self, request: omnichannelsettings.ListOmnichannelSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_omnichannel_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_list_omnichannel_settings(self, response: omnichannelsettings.ListOmnichannelSettingsResponse) -> omnichannelsettings.ListOmnichannelSettingsResponse: + """Post-rpc interceptor for list_omnichannel_settings + + DEPRECATED. Please use the `post_list_omnichannel_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_list_omnichannel_settings` interceptor runs + before the `post_list_omnichannel_settings_with_metadata` interceptor. + """ + return response + + def post_list_omnichannel_settings_with_metadata(self, response: omnichannelsettings.ListOmnichannelSettingsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_omnichannel_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_list_omnichannel_settings_with_metadata` + interceptor in new development instead of the `post_list_omnichannel_settings` interceptor. + When both interceptors are used, this `post_list_omnichannel_settings_with_metadata` interceptor runs after the + `post_list_omnichannel_settings` interceptor. The (possibly modified) response returned by + `post_list_omnichannel_settings` will be passed to + `post_list_omnichannel_settings_with_metadata`. + """ + return response, metadata + + def pre_request_inventory_verification(self, request: omnichannelsettings.RequestInventoryVerificationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for request_inventory_verification + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_request_inventory_verification(self, response: omnichannelsettings.RequestInventoryVerificationResponse) -> omnichannelsettings.RequestInventoryVerificationResponse: + """Post-rpc interceptor for request_inventory_verification + + DEPRECATED. Please use the `post_request_inventory_verification_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_request_inventory_verification` interceptor runs + before the `post_request_inventory_verification_with_metadata` interceptor. + """ + return response + + def post_request_inventory_verification_with_metadata(self, response: omnichannelsettings.RequestInventoryVerificationResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for request_inventory_verification + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_request_inventory_verification_with_metadata` + interceptor in new development instead of the `post_request_inventory_verification` interceptor. + When both interceptors are used, this `post_request_inventory_verification_with_metadata` interceptor runs after the + `post_request_inventory_verification` interceptor. The (possibly modified) response returned by + `post_request_inventory_verification` will be passed to + `post_request_inventory_verification_with_metadata`. + """ + return response, metadata + + def pre_update_omnichannel_setting(self, request: omnichannelsettings.UpdateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.UpdateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_omnichannel_setting + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_update_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + """Post-rpc interceptor for update_omnichannel_setting + + DEPRECATED. Please use the `post_update_omnichannel_setting_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_update_omnichannel_setting` interceptor runs + before the `post_update_omnichannel_setting_with_metadata` interceptor. + """ + return response + + def post_update_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_omnichannel_setting + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_update_omnichannel_setting_with_metadata` + interceptor in new development instead of the `post_update_omnichannel_setting` interceptor. + When both interceptors are used, this `post_update_omnichannel_setting_with_metadata` interceptor runs after the + `post_update_omnichannel_setting` interceptor. The (possibly modified) response returned by + `post_update_omnichannel_setting` will be passed to + `post_update_omnichannel_setting_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class OmnichannelSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OmnichannelSettingsServiceRestInterceptor + + +class OmnichannelSettingsServiceRestTransport(_BaseOmnichannelSettingsServiceRestTransport): + """REST backend synchronous transport for OmnichannelSettingsService. + + The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + + 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[OmnichannelSettingsServiceRestInterceptor] = 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 OmnichannelSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.CreateOmnichannelSetting") + + @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: omnichannelsettings.CreateOmnichannelSettingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Call the create omnichannel + setting method over HTTP. + + Args: + request (~.omnichannelsettings.CreateOmnichannelSettingRequest): + The request object. Request message for the + CreateOmnichannelSetting 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_http_options() + + request, metadata = self._interceptor.pre_create_omnichannel_setting(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_transcoded_request(http_options, request) + + body = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.CreateOmnichannelSetting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "CreateOmnichannelSetting", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._CreateOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() + pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_omnichannel_setting(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_omnichannel_setting_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1.OmnichannelSettingsServiceClient.create_omnichannel_setting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "CreateOmnichannelSetting", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.GetOmnichannelSetting") + + @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: omnichannelsettings.GetOmnichannelSettingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Call the get omnichannel setting method over HTTP. + + Args: + request (~.omnichannelsettings.GetOmnichannelSettingRequest): + The request object. Request message for the + GetOmnichannelSettings 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_http_options() + + request, metadata = self._interceptor.pre_get_omnichannel_setting(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.GetOmnichannelSetting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "GetOmnichannelSetting", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._GetOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() + pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_omnichannel_setting(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_omnichannel_setting_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1.OmnichannelSettingsServiceClient.get_omnichannel_setting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "GetOmnichannelSetting", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOmnichannelSettings(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.ListOmnichannelSettings") + + @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: omnichannelsettings.ListOmnichannelSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.ListOmnichannelSettingsResponse: + r"""Call the list omnichannel settings method over HTTP. + + Args: + request (~.omnichannelsettings.ListOmnichannelSettingsRequest): + The request object. Request message for the + ListOmnichannelSettings 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: + ~.omnichannelsettings.ListOmnichannelSettingsResponse: + Response message for the + ListOmnichannelSettings method. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_http_options() + + request, metadata = self._interceptor.pre_list_omnichannel_settings(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.ListOmnichannelSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "ListOmnichannelSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._ListOmnichannelSettings._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 = omnichannelsettings.ListOmnichannelSettingsResponse() + pb_resp = omnichannelsettings.ListOmnichannelSettingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_omnichannel_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_omnichannel_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.ListOmnichannelSettingsResponse.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.accounts_v1.OmnichannelSettingsServiceClient.list_omnichannel_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "ListOmnichannelSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RequestInventoryVerification(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.RequestInventoryVerification") + + @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: omnichannelsettings.RequestInventoryVerificationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: + r"""Call the request inventory + verification method over HTTP. + + Args: + request (~.omnichannelsettings.RequestInventoryVerificationRequest): + The request object. Request message for the + RequestInventoryVerification 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: + ~.omnichannelsettings.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_http_options() + + request, metadata = self._interceptor.pre_request_inventory_verification(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_transcoded_request(http_options, request) + + body = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.RequestInventoryVerification", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "RequestInventoryVerification", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._RequestInventoryVerification._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 = omnichannelsettings.RequestInventoryVerificationResponse() + pb_resp = omnichannelsettings.RequestInventoryVerificationResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_request_inventory_verification(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_request_inventory_verification_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.RequestInventoryVerificationResponse.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.accounts_v1.OmnichannelSettingsServiceClient.request_inventory_verification", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "RequestInventoryVerification", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.UpdateOmnichannelSetting") + + @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: omnichannelsettings.UpdateOmnichannelSettingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Call the update omnichannel + setting method over HTTP. + + Args: + request (~.omnichannelsettings.UpdateOmnichannelSettingRequest): + The request object. Request message for the + UpdateOmnichannelSetting 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_http_options() + + request, metadata = self._interceptor.pre_update_omnichannel_setting(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_transcoded_request(http_options, request) + + body = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.UpdateOmnichannelSetting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "UpdateOmnichannelSetting", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._UpdateOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() + pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_omnichannel_setting(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_omnichannel_setting_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1.OmnichannelSettingsServiceClient.update_omnichannel_setting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "rpcName": "UpdateOmnichannelSetting", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + # 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._CreateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + # 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._GetOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + omnichannelsettings.ListOmnichannelSettingsResponse]: + # 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._ListOmnichannelSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + omnichannelsettings.RequestInventoryVerificationResponse]: + # 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._RequestInventoryVerification(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + # 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._UpdateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'OmnichannelSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..5a6bf3c35dbe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py @@ -0,0 +1,306 @@ +# -*- 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 OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import omnichannelsettings + + +class _BaseOmnichannelSettingsServiceRestTransport(OmnichannelSettingsServiceTransport): + """Base REST backend transport for OmnichannelSettingsService. + + 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 _BaseCreateOmnichannelSetting: + 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': '/accounts/v1/{parent=accounts/*}/omnichannelSettings', + 'body': 'omnichannel_setting', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.CreateOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOmnichannelSetting: + 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': '/accounts/v1/{name=accounts/*/omnichannelSettings/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.GetOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListOmnichannelSettings: + 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': '/accounts/v1/{parent=accounts/*}/omnichannelSettings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.ListOmnichannelSettingsRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRequestInventoryVerification: + 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': '/accounts/v1/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.RequestInventoryVerificationRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateOmnichannelSetting: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}', + 'body': 'omnichannel_setting', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.UpdateOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseOmnichannelSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py new file mode 100644 index 000000000000..856118f59e37 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_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 OnlineReturnPolicyServiceClient +from .async_client import OnlineReturnPolicyServiceAsyncClient + +__all__ = ( + 'OnlineReturnPolicyServiceClient', + 'OnlineReturnPolicyServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py new file mode 100644 index 000000000000..36f356f18deb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py @@ -0,0 +1,721 @@ +# -*- 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_accounts_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_accounts_v1.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy +from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport +from .client import OnlineReturnPolicyServiceClient + +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 OnlineReturnPolicyServiceAsyncClient: + """The service facilitates the management of a business's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + """ + + _client: OnlineReturnPolicyServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + + online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.online_return_policy_path) + parse_online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.parse_online_return_policy_path) + common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OnlineReturnPolicyServiceClient.common_project_path) + parse_common_project_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_project_path) + common_location_path = staticmethod(OnlineReturnPolicyServiceClient.common_location_path) + parse_common_location_path = staticmethod(OnlineReturnPolicyServiceClient.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: + OnlineReturnPolicyServiceAsyncClient: The constructed client. + """ + return OnlineReturnPolicyServiceClient.from_service_account_info.__func__(OnlineReturnPolicyServiceAsyncClient, 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: + OnlineReturnPolicyServiceAsyncClient: The constructed client. + """ + return OnlineReturnPolicyServiceClient.from_service_account_file.__func__(OnlineReturnPolicyServiceAsyncClient, 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 OnlineReturnPolicyServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> OnlineReturnPolicyServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OnlineReturnPolicyServiceTransport: 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 = OnlineReturnPolicyServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the online return policy 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,OnlineReturnPolicyServiceTransport,Callable[..., OnlineReturnPolicyServiceTransport]]]): + 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 OnlineReturnPolicyServiceTransport 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 = OnlineReturnPolicyServiceClient( + 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.accounts_v1.OnlineReturnPolicyServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "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.accounts.v1.OnlineReturnPolicyService", + "credentialsType": None, + } + ) + + async def get_online_return_policy(self, + request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: + r"""Gets an existing return policy for a given business. + + .. 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_accounts_v1 + + async def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``GetOnlineReturnPolicy`` + method. + name (:class:`str`): + Required. The name of the return policy to retrieve. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy.GetOnlineReturnPolicyRequest): + request = online_return_policy.GetOnlineReturnPolicyRequest(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.get_online_return_policy] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_online_return_policies(self, + request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesAsyncPager: + r"""Lists all existing return policies for a given + business. + + .. 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_accounts_v1 + + async def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesRequest, dict]]): + The request object. Request message for the ``ListOnlineReturnPolicies`` + method. + parent (:class:`str`): + Required. The Merchant Center account for which to list + return policies. Format: ``accounts/{account}`` + + 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_accounts_v1.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager: + Response message for the ListOnlineReturnPolicies + 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, online_return_policy.ListOnlineReturnPoliciesRequest): + request = online_return_policy.ListOnlineReturnPoliciesRequest(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_online_return_policies] + + # 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.ListOnlineReturnPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_online_return_policy(self, + request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Creates a new return policy for a given business. + + .. 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_accounts_v1 + + async def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1.OnlineReturnPolicy() + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = await client.create_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.CreateOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + method. + parent (:class:`str`): + Required. The Merchant Center account for which the + return policy will be created. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + online_return_policy (:class:`google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy`): + Required. The return policy object to + create. + + This corresponds to the ``online_return_policy`` 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_accounts_v1.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if online_return_policy is not None: + request.online_return_policy = online_return_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_online_return_policy] + + # 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_online_return_policy(self, + request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, + *, + name: 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 an existing return policy. + + .. 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_accounts_v1 + + async def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + await client.delete_online_return_policy(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.DeleteOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + method. + name (:class:`str`): + Required. The name of the return policy to delete. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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, online_return_policy.DeleteOnlineReturnPolicyRequest): + request = online_return_policy.DeleteOnlineReturnPolicyRequest(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_online_return_policy] + + # 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) -> "OnlineReturnPolicyServiceAsyncClient": + 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__ = ( + "OnlineReturnPolicyServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py new file mode 100644 index 000000000000..6b9305c24342 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py @@ -0,0 +1,1078 @@ +# -*- 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_accounts_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_accounts_v1.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy +from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OnlineReturnPolicyServiceGrpcTransport +from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport +from .transports.rest import OnlineReturnPolicyServiceRestTransport + + +class OnlineReturnPolicyServiceClientMeta(type): + """Metaclass for the OnlineReturnPolicyService 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[OnlineReturnPolicyServiceTransport]] + _transport_registry["grpc"] = OnlineReturnPolicyServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OnlineReturnPolicyServiceGrpcAsyncIOTransport + _transport_registry["rest"] = OnlineReturnPolicyServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[OnlineReturnPolicyServiceTransport]: + """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 OnlineReturnPolicyServiceClient(metaclass=OnlineReturnPolicyServiceClientMeta): + """The service facilitates the management of a business's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + """ + + @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: + OnlineReturnPolicyServiceClient: 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: + OnlineReturnPolicyServiceClient: 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) -> OnlineReturnPolicyServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OnlineReturnPolicyServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def online_return_policy_path(account: str,return_policy: str,) -> str: + """Returns a fully-qualified online_return_policy string.""" + return "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) + + @staticmethod + def parse_online_return_policy_path(path: str) -> Dict[str,str]: + """Parses a online_return_policy path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/onlineReturnPolicies/(?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 = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient._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, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the online return policy 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,OnlineReturnPolicyServiceTransport,Callable[..., OnlineReturnPolicyServiceTransport]]]): + 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 OnlineReturnPolicyServiceTransport 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 = OnlineReturnPolicyServiceClient._read_environment_variables() + self._client_cert_source = OnlineReturnPolicyServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = OnlineReturnPolicyServiceClient._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, OnlineReturnPolicyServiceTransport) + if transport_provided: + # transport is a OnlineReturnPolicyServiceTransport 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(OnlineReturnPolicyServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + OnlineReturnPolicyServiceClient._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[OnlineReturnPolicyServiceTransport], Callable[..., OnlineReturnPolicyServiceTransport]] = ( + OnlineReturnPolicyServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OnlineReturnPolicyServiceTransport], 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.accounts_v1.OnlineReturnPolicyServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "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.accounts.v1.OnlineReturnPolicyService", + "credentialsType": None, + } + ) + + def get_online_return_policy(self, + request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: + r"""Gets an existing return policy for a given business. + + .. 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_accounts_v1 + + def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``GetOnlineReturnPolicy`` + method. + name (str): + Required. The name of the return policy to retrieve. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy.GetOnlineReturnPolicyRequest): + request = online_return_policy.GetOnlineReturnPolicyRequest(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.get_online_return_policy] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_online_return_policies(self, + request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesPager: + r"""Lists all existing return policies for a given + business. + + .. 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_accounts_v1 + + def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesRequest, dict]): + The request object. Request message for the ``ListOnlineReturnPolicies`` + method. + parent (str): + Required. The Merchant Center account for which to list + return policies. Format: ``accounts/{account}`` + + 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_accounts_v1.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager: + Response message for the ListOnlineReturnPolicies + 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, online_return_policy.ListOnlineReturnPoliciesRequest): + request = online_return_policy.ListOnlineReturnPoliciesRequest(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_online_return_policies] + + # 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.ListOnlineReturnPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_online_return_policy(self, + request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Creates a new return policy for a given business. + + .. 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_accounts_v1 + + def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1.OnlineReturnPolicy() + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = client.create_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.CreateOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + method. + parent (str): + Required. The Merchant Center account for which the + return policy will be created. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + online_return_policy (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy): + Required. The return policy object to + create. + + This corresponds to the ``online_return_policy`` 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_accounts_v1.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if online_return_policy is not None: + request.online_return_policy = online_return_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_online_return_policy] + + # 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_online_return_policy(self, + request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, + *, + name: 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 an existing return policy. + + .. 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_accounts_v1 + + def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + client.delete_online_return_policy(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.DeleteOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + method. + name (str): + Required. The name of the return policy to delete. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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, online_return_policy.DeleteOnlineReturnPolicyRequest): + request = online_return_policy.DeleteOnlineReturnPolicyRequest(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_online_return_policy] + + # 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) -> "OnlineReturnPolicyServiceClient": + 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__ = ( + "OnlineReturnPolicyServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py new file mode 100644 index 000000000000..8bd1d763b1bd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_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_accounts_v1.types import online_return_policy + + +class ListOnlineReturnPoliciesPager: + """A pager for iterating through ``list_online_return_policies`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``online_return_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOnlineReturnPolicies`` requests and continue to iterate + through the ``online_return_policies`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesResponse` + 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[..., online_return_policy.ListOnlineReturnPoliciesResponse], + request: online_return_policy.ListOnlineReturnPoliciesRequest, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + *, + 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_accounts_v1.types.ListOnlineReturnPoliciesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesResponse): + 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 = online_return_policy.ListOnlineReturnPoliciesRequest(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[online_return_policy.ListOnlineReturnPoliciesResponse]: + 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[online_return_policy.OnlineReturnPolicy]: + for page in self.pages: + yield from page.online_return_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOnlineReturnPoliciesAsyncPager: + """A pager for iterating through ``list_online_return_policies`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``online_return_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOnlineReturnPolicies`` requests and continue to iterate + through the ``online_return_policies`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesResponse` + 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[online_return_policy.ListOnlineReturnPoliciesResponse]], + request: online_return_policy.ListOnlineReturnPoliciesRequest, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + *, + 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_accounts_v1.types.ListOnlineReturnPoliciesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesResponse): + 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 = online_return_policy.ListOnlineReturnPoliciesRequest(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[online_return_policy.ListOnlineReturnPoliciesResponse]: + 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[online_return_policy.OnlineReturnPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.online_return_policies: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst new file mode 100644 index 000000000000..a6e34721a621 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OnlineReturnPolicyServiceTransport` is the ABC for all transports. +- public child `OnlineReturnPolicyServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OnlineReturnPolicyServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOnlineReturnPolicyServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OnlineReturnPolicyServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py new file mode 100644 index 000000000000..406ed1cc95a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_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 OnlineReturnPolicyServiceTransport +from .grpc import OnlineReturnPolicyServiceGrpcTransport +from .grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport +from .rest import OnlineReturnPolicyServiceRestTransport +from .rest import OnlineReturnPolicyServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] +_transport_registry['grpc'] = OnlineReturnPolicyServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OnlineReturnPolicyServiceGrpcAsyncIOTransport +_transport_registry['rest'] = OnlineReturnPolicyServiceRestTransport + +__all__ = ( + 'OnlineReturnPolicyServiceTransport', + 'OnlineReturnPolicyServiceGrpcTransport', + 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', + 'OnlineReturnPolicyServiceRestTransport', + 'OnlineReturnPolicyServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py new file mode 100644 index 000000000000..a6176e61390f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py @@ -0,0 +1,203 @@ +# -*- 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_accounts_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_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy + +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 OnlineReturnPolicyServiceTransport(abc.ABC): + """Abstract transport class for OnlineReturnPolicyService.""" + + 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.get_online_return_policy: gapic_v1.method.wrap_method( + self.get_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_online_return_policies: gapic_v1.method.wrap_method( + self.list_online_return_policies, + default_timeout=None, + client_info=client_info, + ), + self.create_online_return_policy: gapic_v1.method.wrap_method( + self.create_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_online_return_policy: gapic_v1.method.wrap_method( + self.delete_online_return_policy, + 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 get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + Union[ + online_return_policy.OnlineReturnPolicy, + Awaitable[online_return_policy.OnlineReturnPolicy] + ]]: + raise NotImplementedError() + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + Union[ + online_return_policy.ListOnlineReturnPoliciesResponse, + Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + Union[ + gsma_online_return_policy.OnlineReturnPolicy, + Awaitable[gsma_online_return_policy.OnlineReturnPolicy] + ]]: + raise NotImplementedError() + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'OnlineReturnPolicyServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py new file mode 100644 index 000000000000..aa34b6df0792 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py @@ -0,0 +1,434 @@ +# -*- 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_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy +from .base import OnlineReturnPolicyServiceTransport, 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.accounts.v1.OnlineReturnPolicyService", + "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.accounts.v1.OnlineReturnPolicyService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OnlineReturnPolicyServiceGrpcTransport(OnlineReturnPolicyServiceTransport): + """gRPC backend transport for OnlineReturnPolicyService. + + The service facilitates the management of a business's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + + 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 get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + online_return_policy.OnlineReturnPolicy]: + r"""Return a callable for the get online return policy method over gRPC. + + Gets an existing return policy for a given business. + + Returns: + Callable[[~.GetOnlineReturnPolicyRequest], + ~.OnlineReturnPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_online_return_policy' not in self._stubs: + self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/GetOnlineReturnPolicy', + request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, + response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['get_online_return_policy'] + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + online_return_policy.ListOnlineReturnPoliciesResponse]: + r"""Return a callable for the list online return policies method over gRPC. + + Lists all existing return policies for a given + business. + + Returns: + Callable[[~.ListOnlineReturnPoliciesRequest], + ~.ListOnlineReturnPoliciesResponse]: + 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_online_return_policies' not in self._stubs: + self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/ListOnlineReturnPolicies', + request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, + response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, + ) + return self._stubs['list_online_return_policies'] + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy]: + r"""Return a callable for the create online return policy method over gRPC. + + Creates a new return policy for a given business. + + Returns: + Callable[[~.CreateOnlineReturnPolicyRequest], + ~.OnlineReturnPolicy]: + 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 'create_online_return_policy' not in self._stubs: + self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/CreateOnlineReturnPolicy', + request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, + response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['create_online_return_policy'] + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete online return policy method over gRPC. + + Deletes an existing return policy. + + Returns: + Callable[[~.DeleteOnlineReturnPolicyRequest], + ~.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_online_return_policy' not in self._stubs: + self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', + request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_online_return_policy'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'OnlineReturnPolicyServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..eb982dc7694b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py @@ -0,0 +1,470 @@ +# -*- 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_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy +from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OnlineReturnPolicyServiceGrpcTransport + +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.accounts.v1.OnlineReturnPolicyService", + "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.accounts.v1.OnlineReturnPolicyService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OnlineReturnPolicyServiceGrpcAsyncIOTransport(OnlineReturnPolicyServiceTransport): + """gRPC AsyncIO backend transport for OnlineReturnPolicyService. + + The service facilitates the management of a business's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + + 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 get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + Awaitable[online_return_policy.OnlineReturnPolicy]]: + r"""Return a callable for the get online return policy method over gRPC. + + Gets an existing return policy for a given business. + + Returns: + Callable[[~.GetOnlineReturnPolicyRequest], + Awaitable[~.OnlineReturnPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_online_return_policy' not in self._stubs: + self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/GetOnlineReturnPolicy', + request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, + response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['get_online_return_policy'] + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse]]: + r"""Return a callable for the list online return policies method over gRPC. + + Lists all existing return policies for a given + business. + + Returns: + Callable[[~.ListOnlineReturnPoliciesRequest], + Awaitable[~.ListOnlineReturnPoliciesResponse]]: + 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_online_return_policies' not in self._stubs: + self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/ListOnlineReturnPolicies', + request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, + response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, + ) + return self._stubs['list_online_return_policies'] + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + Awaitable[gsma_online_return_policy.OnlineReturnPolicy]]: + r"""Return a callable for the create online return policy method over gRPC. + + Creates a new return policy for a given business. + + Returns: + Callable[[~.CreateOnlineReturnPolicyRequest], + Awaitable[~.OnlineReturnPolicy]]: + 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 'create_online_return_policy' not in self._stubs: + self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/CreateOnlineReturnPolicy', + request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, + response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['create_online_return_policy'] + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete online return policy method over gRPC. + + Deletes an existing return policy. + + Returns: + Callable[[~.DeleteOnlineReturnPolicyRequest], + 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_online_return_policy' not in self._stubs: + self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', + request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_online_return_policy'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_online_return_policy: self._wrap_method( + self.get_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_online_return_policies: self._wrap_method( + self.list_online_return_policies, + default_timeout=None, + client_info=client_info, + ), + self.create_online_return_policy: self._wrap_method( + self.create_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_online_return_policy: self._wrap_method( + self.delete_online_return_policy, + 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__ = ( + 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py new file mode 100644 index 000000000000..c1f3e011bc04 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py @@ -0,0 +1,827 @@ +# -*- 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_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy + + +from .rest_base import _BaseOnlineReturnPolicyServiceRestTransport +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 OnlineReturnPolicyServiceRestInterceptor: + """Interceptor for OnlineReturnPolicyService. + + 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 OnlineReturnPolicyServiceRestTransport. + + .. code-block:: python + class MyCustomOnlineReturnPolicyServiceInterceptor(OnlineReturnPolicyServiceRestInterceptor): + def pre_create_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_online_return_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_online_return_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_online_return_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_online_return_policies(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OnlineReturnPolicyServiceRestTransport(interceptor=MyCustomOnlineReturnPolicyServiceInterceptor()) + client = OnlineReturnPolicyServiceClient(transport=transport) + + + """ + def pre_create_online_return_policy(self, request: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_create_online_return_policy(self, response: gsma_online_return_policy.OnlineReturnPolicy) -> gsma_online_return_policy.OnlineReturnPolicy: + """Post-rpc interceptor for create_online_return_policy + + DEPRECATED. Please use the `post_create_online_return_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_create_online_return_policy` interceptor runs + before the `post_create_online_return_policy_with_metadata` interceptor. + """ + return response + + def post_create_online_return_policy_with_metadata(self, response: gsma_online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_online_return_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_create_online_return_policy_with_metadata` + interceptor in new development instead of the `post_create_online_return_policy` interceptor. + When both interceptors are used, this `post_create_online_return_policy_with_metadata` interceptor runs after the + `post_create_online_return_policy` interceptor. The (possibly modified) response returned by + `post_create_online_return_policy` will be passed to + `post_create_online_return_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_online_return_policy(self, request: online_return_policy.DeleteOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.DeleteOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def pre_get_online_return_policy(self, request: online_return_policy.GetOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_get_online_return_policy(self, response: online_return_policy.OnlineReturnPolicy) -> online_return_policy.OnlineReturnPolicy: + """Post-rpc interceptor for get_online_return_policy + + DEPRECATED. Please use the `post_get_online_return_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_get_online_return_policy` interceptor runs + before the `post_get_online_return_policy_with_metadata` interceptor. + """ + return response + + def post_get_online_return_policy_with_metadata(self, response: online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_online_return_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_get_online_return_policy_with_metadata` + interceptor in new development instead of the `post_get_online_return_policy` interceptor. + When both interceptors are used, this `post_get_online_return_policy_with_metadata` interceptor runs after the + `post_get_online_return_policy` interceptor. The (possibly modified) response returned by + `post_get_online_return_policy` will be passed to + `post_get_online_return_policy_with_metadata`. + """ + return response, metadata + + def pre_list_online_return_policies(self, request: online_return_policy.ListOnlineReturnPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_online_return_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_list_online_return_policies(self, response: online_return_policy.ListOnlineReturnPoliciesResponse) -> online_return_policy.ListOnlineReturnPoliciesResponse: + """Post-rpc interceptor for list_online_return_policies + + DEPRECATED. Please use the `post_list_online_return_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_list_online_return_policies` interceptor runs + before the `post_list_online_return_policies_with_metadata` interceptor. + """ + return response + + def post_list_online_return_policies_with_metadata(self, response: online_return_policy.ListOnlineReturnPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_online_return_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_list_online_return_policies_with_metadata` + interceptor in new development instead of the `post_list_online_return_policies` interceptor. + When both interceptors are used, this `post_list_online_return_policies_with_metadata` interceptor runs after the + `post_list_online_return_policies` interceptor. The (possibly modified) response returned by + `post_list_online_return_policies` will be passed to + `post_list_online_return_policies_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class OnlineReturnPolicyServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OnlineReturnPolicyServiceRestInterceptor + + +class OnlineReturnPolicyServiceRestTransport(_BaseOnlineReturnPolicyServiceRestTransport): + """REST backend synchronous transport for OnlineReturnPolicyService. + + The service facilitates the management of a business's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + + 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[OnlineReturnPolicyServiceRestInterceptor] = 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 OnlineReturnPolicyServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.CreateOnlineReturnPolicy") + + @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: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Call the create online return + policy method over HTTP. + + Args: + request (~.gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + 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: + ~.gsma_online_return_policy.OnlineReturnPolicy: + `Online return + policy `__ + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_create_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_transcoded_request(http_options, request) + + body = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.CreateOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "CreateOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._CreateOnlineReturnPolicy._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 = gsma_online_return_policy.OnlineReturnPolicy() + pb_resp = gsma_online_return_policy.OnlineReturnPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_online_return_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_online_return_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_online_return_policy.OnlineReturnPolicy.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.accounts_v1.OnlineReturnPolicyServiceClient.create_online_return_policy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "CreateOnlineReturnPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.DeleteOnlineReturnPolicy") + + @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: online_return_policy.DeleteOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete online return + policy method over HTTP. + + Args: + request (~.online_return_policy.DeleteOnlineReturnPolicyRequest): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_delete_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.DeleteOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "DeleteOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._DeleteOnlineReturnPolicy._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 _GetOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.GetOnlineReturnPolicy") + + @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: online_return_policy.GetOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> online_return_policy.OnlineReturnPolicy: + r"""Call the get online return policy method over HTTP. + + Args: + request (~.online_return_policy.GetOnlineReturnPolicyRequest): + The request object. Request message for the ``GetOnlineReturnPolicy`` + 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: + ~.online_return_policy.OnlineReturnPolicy: + `Online return + policy `__ + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.GetOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "GetOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._GetOnlineReturnPolicy._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 = online_return_policy.OnlineReturnPolicy() + pb_resp = online_return_policy.OnlineReturnPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_online_return_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_online_return_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = online_return_policy.OnlineReturnPolicy.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.accounts_v1.OnlineReturnPolicyServiceClient.get_online_return_policy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "GetOnlineReturnPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOnlineReturnPolicies(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.ListOnlineReturnPolicies") + + @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: online_return_policy.ListOnlineReturnPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> online_return_policy.ListOnlineReturnPoliciesResponse: + r"""Call the list online return + policies method over HTTP. + + Args: + request (~.online_return_policy.ListOnlineReturnPoliciesRequest): + The request object. Request message for the ``ListOnlineReturnPolicies`` + 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: + ~.online_return_policy.ListOnlineReturnPoliciesResponse: + Response message for the ``ListOnlineReturnPolicies`` + method. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_http_options() + + request, metadata = self._interceptor.pre_list_online_return_policies(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.ListOnlineReturnPolicies", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "ListOnlineReturnPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._ListOnlineReturnPolicies._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 = online_return_policy.ListOnlineReturnPoliciesResponse() + pb_resp = online_return_policy.ListOnlineReturnPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_online_return_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_online_return_policies_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = online_return_policy.ListOnlineReturnPoliciesResponse.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.accounts_v1.OnlineReturnPolicyServiceClient.list_online_return_policies", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "rpcName": "ListOnlineReturnPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy]: + # 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._CreateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + 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._DeleteOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + online_return_policy.OnlineReturnPolicy]: + # 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._GetOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + online_return_policy.ListOnlineReturnPoliciesResponse]: + # 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._ListOnlineReturnPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'OnlineReturnPolicyServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py new file mode 100644 index 000000000000..38fdb9520846 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py @@ -0,0 +1,251 @@ +# -*- 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 OnlineReturnPolicyServiceTransport, 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_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy + + +class _BaseOnlineReturnPolicyServiceRestTransport(OnlineReturnPolicyServiceTransport): + """Base REST backend transport for OnlineReturnPolicyService. + + 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 _BaseCreateOnlineReturnPolicy: + 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': '/accounts/v1/{parent=accounts/*}/onlineReturnPolicies', + 'body': 'online_return_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOnlineReturnPolicy: + 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': '/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = online_return_policy.DeleteOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOnlineReturnPolicy: + 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': '/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = online_return_policy.GetOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListOnlineReturnPolicies: + 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': '/accounts/v1/{parent=accounts/*}/onlineReturnPolicies', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = online_return_policy.ListOnlineReturnPoliciesRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseOnlineReturnPolicyServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py new file mode 100644 index 000000000000..400e3ec082c8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_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 ProgramsServiceClient +from .async_client import ProgramsServiceAsyncClient + +__all__ = ( + 'ProgramsServiceClient', + 'ProgramsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py new file mode 100644 index 000000000000..a51835cd13d2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py @@ -0,0 +1,763 @@ +# -*- 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_accounts_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_accounts_v1.services.programs_service import pagers +from google.shopping.merchant_accounts_v1.types import programs +from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport +from .client import ProgramsServiceClient + +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 ProgramsServiceAsyncClient: + """Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a business's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + """ + + _client: ProgramsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ProgramsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ProgramsServiceClient._DEFAULT_UNIVERSE + + program_path = staticmethod(ProgramsServiceClient.program_path) + parse_program_path = staticmethod(ProgramsServiceClient.parse_program_path) + common_billing_account_path = staticmethod(ProgramsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProgramsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProgramsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProgramsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProgramsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProgramsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProgramsServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProgramsServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProgramsServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProgramsServiceClient.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: + ProgramsServiceAsyncClient: The constructed client. + """ + return ProgramsServiceClient.from_service_account_info.__func__(ProgramsServiceAsyncClient, 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: + ProgramsServiceAsyncClient: The constructed client. + """ + return ProgramsServiceClient.from_service_account_file.__func__(ProgramsServiceAsyncClient, 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 ProgramsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProgramsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProgramsServiceTransport: 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 = ProgramsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the programs 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,ProgramsServiceTransport,Callable[..., ProgramsServiceTransport]]]): + 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 ProgramsServiceTransport 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 = ProgramsServiceClient( + 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.accounts_v1.ProgramsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "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.accounts.v1.ProgramsService", + "credentialsType": None, + } + ) + + async def get_program(self, + request: Optional[Union[programs.GetProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Retrieves the specified program for the 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_accounts_v1 + + async def sample_get_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.get_program(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetProgramRequest, dict]]): + The request object. Request message for the GetProgram + method. + name (:class:`str`): + Required. The name of the program to retrieve. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to a Merchant Center accounts. A typical example of + this is the [Free product + listings](\ https://support.google.com/merchants/answer/13889434) + program, which enables products from a business's + store to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - free-listings + - shopping-ads + - youtube-shopping-checkout + + """ + # 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, programs.GetProgramRequest): + request = programs.GetProgramRequest(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.get_program] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_programs(self, + request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsAsyncPager: + r"""Retrieves all programs for the 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_accounts_v1 + + async def sample_list_programs(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListProgramsRequest, dict]]): + The request object. Request message for the ListPrograms + method. + parent (:class:`str`): + Required. The name of the account for which to retrieve + all programs. Format: ``accounts/{account}`` + + 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_accounts_v1.services.programs_service.pagers.ListProgramsAsyncPager: + Response message for the ListPrograms + 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, programs.ListProgramsRequest): + request = programs.ListProgramsRequest(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_programs] + + # 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.ListProgramsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def enable_program(self, + request: Optional[Union[programs.EnableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Enable participation in the specified program for the + 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_accounts_v1 + + async def sample_enable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.enable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.EnableProgramRequest, dict]]): + The request object. Request message for the EnableProgram + method. + name (:class:`str`): + Required. The name of the program for which to enable + participation for the given account. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to a Merchant Center accounts. A typical example of + this is the [Free product + listings](\ https://support.google.com/merchants/answer/13889434) + program, which enables products from a business's + store to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - free-listings + - shopping-ads + - youtube-shopping-checkout + + """ + # 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, programs.EnableProgramRequest): + request = programs.EnableProgramRequest(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.enable_program] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def disable_program(self, + request: Optional[Union[programs.DisableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Disable participation in the specified program for + the 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_accounts_v1 + + async def sample_disable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.disable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.DisableProgramRequest, dict]]): + The request object. Request message for the + DisableProgram method. + name (:class:`str`): + Required. The name of the program for which to disable + participation for the given account. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to a Merchant Center accounts. A typical example of + this is the [Free product + listings](\ https://support.google.com/merchants/answer/13889434) + program, which enables products from a business's + store to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - free-listings + - shopping-ads + - youtube-shopping-checkout + + """ + # 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, programs.DisableProgramRequest): + request = programs.DisableProgramRequest(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.disable_program] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ProgramsServiceAsyncClient": + 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__ = ( + "ProgramsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py new file mode 100644 index 000000000000..0a008e79e355 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py @@ -0,0 +1,1120 @@ +# -*- 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_accounts_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_accounts_v1.services.programs_service import pagers +from google.shopping.merchant_accounts_v1.types import programs +from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProgramsServiceGrpcTransport +from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport +from .transports.rest import ProgramsServiceRestTransport + + +class ProgramsServiceClientMeta(type): + """Metaclass for the ProgramsService 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[ProgramsServiceTransport]] + _transport_registry["grpc"] = ProgramsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProgramsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ProgramsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProgramsServiceTransport]: + """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 ProgramsServiceClient(metaclass=ProgramsServiceClientMeta): + """Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a business's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + """ + + @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: + ProgramsServiceClient: 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: + ProgramsServiceClient: 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) -> ProgramsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProgramsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def program_path(account: str,program: str,) -> str: + """Returns a fully-qualified program string.""" + return "accounts/{account}/programs/{program}".format(account=account, program=program, ) + + @staticmethod + def parse_program_path(path: str) -> Dict[str,str]: + """Parses a program path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/programs/(?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 = ProgramsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ProgramsServiceClient._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 = ProgramsServiceClient._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, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the programs 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,ProgramsServiceTransport,Callable[..., ProgramsServiceTransport]]]): + 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 ProgramsServiceTransport 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 = ProgramsServiceClient._read_environment_variables() + self._client_cert_source = ProgramsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProgramsServiceClient._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, ProgramsServiceTransport) + if transport_provided: + # transport is a ProgramsServiceTransport 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(ProgramsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ProgramsServiceClient._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[ProgramsServiceTransport], Callable[..., ProgramsServiceTransport]] = ( + ProgramsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProgramsServiceTransport], 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.accounts_v1.ProgramsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "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.accounts.v1.ProgramsService", + "credentialsType": None, + } + ) + + def get_program(self, + request: Optional[Union[programs.GetProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Retrieves the specified program for the 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_accounts_v1 + + def sample_get_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = client.get_program(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetProgramRequest, dict]): + The request object. Request message for the GetProgram + method. + name (str): + Required. The name of the program to retrieve. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to a Merchant Center accounts. A typical example of + this is the [Free product + listings](\ https://support.google.com/merchants/answer/13889434) + program, which enables products from a business's + store to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - free-listings + - shopping-ads + - youtube-shopping-checkout + + """ + # 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, programs.GetProgramRequest): + request = programs.GetProgramRequest(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.get_program] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_programs(self, + request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsPager: + r"""Retrieves all programs for the 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_accounts_v1 + + def sample_list_programs(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListProgramsRequest, dict]): + The request object. Request message for the ListPrograms + method. + parent (str): + Required. The name of the account for which to retrieve + all programs. Format: ``accounts/{account}`` + + 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_accounts_v1.services.programs_service.pagers.ListProgramsPager: + Response message for the ListPrograms + 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, programs.ListProgramsRequest): + request = programs.ListProgramsRequest(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_programs] + + # 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.ListProgramsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def enable_program(self, + request: Optional[Union[programs.EnableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Enable participation in the specified program for the + 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_accounts_v1 + + def sample_enable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.enable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.EnableProgramRequest, dict]): + The request object. Request message for the EnableProgram + method. + name (str): + Required. The name of the program for which to enable + participation for the given account. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to a Merchant Center accounts. A typical example of + this is the [Free product + listings](\ https://support.google.com/merchants/answer/13889434) + program, which enables products from a business's + store to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - free-listings + - shopping-ads + - youtube-shopping-checkout + + """ + # 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, programs.EnableProgramRequest): + request = programs.EnableProgramRequest(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.enable_program] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def disable_program(self, + request: Optional[Union[programs.DisableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Disable participation in the specified program for + the 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_accounts_v1 + + def sample_disable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.disable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.DisableProgramRequest, dict]): + The request object. Request message for the + DisableProgram method. + name (str): + Required. The name of the program for which to disable + participation for the given account. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to a Merchant Center accounts. A typical example of + this is the [Free product + listings](\ https://support.google.com/merchants/answer/13889434) + program, which enables products from a business's + store to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - free-listings + - shopping-ads + - youtube-shopping-checkout + + """ + # 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, programs.DisableProgramRequest): + request = programs.DisableProgramRequest(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.disable_program] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProgramsServiceClient": + 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__ = ( + "ProgramsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py new file mode 100644 index 000000000000..6fa0359f8ad0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_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_accounts_v1.types import programs + + +class ListProgramsPager: + """A pager for iterating through ``list_programs`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListProgramsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``programs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPrograms`` requests and continue to iterate + through the ``programs`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListProgramsResponse` + 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[..., programs.ListProgramsResponse], + request: programs.ListProgramsRequest, + response: programs.ListProgramsResponse, + *, + 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_accounts_v1.types.ListProgramsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListProgramsResponse): + 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 = programs.ListProgramsRequest(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[programs.ListProgramsResponse]: + 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[programs.Program]: + for page in self.pages: + yield from page.programs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProgramsAsyncPager: + """A pager for iterating through ``list_programs`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListProgramsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``programs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPrograms`` requests and continue to iterate + through the ``programs`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListProgramsResponse` + 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[programs.ListProgramsResponse]], + request: programs.ListProgramsRequest, + response: programs.ListProgramsResponse, + *, + 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_accounts_v1.types.ListProgramsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListProgramsResponse): + 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 = programs.ListProgramsRequest(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[programs.ListProgramsResponse]: + 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[programs.Program]: + async def async_generator(): + async for page in self.pages: + for response in page.programs: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst new file mode 100644 index 000000000000..b36d6af5aeda --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProgramsServiceTransport` is the ABC for all transports. +- public child `ProgramsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProgramsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProgramsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProgramsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py new file mode 100644 index 000000000000..dc803437b5a1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_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 ProgramsServiceTransport +from .grpc import ProgramsServiceGrpcTransport +from .grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport +from .rest import ProgramsServiceRestTransport +from .rest import ProgramsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProgramsServiceTransport]] +_transport_registry['grpc'] = ProgramsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProgramsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ProgramsServiceRestTransport + +__all__ = ( + 'ProgramsServiceTransport', + 'ProgramsServiceGrpcTransport', + 'ProgramsServiceGrpcAsyncIOTransport', + 'ProgramsServiceRestTransport', + 'ProgramsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py new file mode 100644 index 000000000000..638318303da2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py @@ -0,0 +1,201 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import programs + +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 ProgramsServiceTransport(abc.ABC): + """Abstract transport class for ProgramsService.""" + + 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.get_program: gapic_v1.method.wrap_method( + self.get_program, + default_timeout=None, + client_info=client_info, + ), + self.list_programs: gapic_v1.method.wrap_method( + self.list_programs, + default_timeout=None, + client_info=client_info, + ), + self.enable_program: gapic_v1.method.wrap_method( + self.enable_program, + default_timeout=None, + client_info=client_info, + ), + self.disable_program: gapic_v1.method.wrap_method( + self.disable_program, + 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 get_program(self) -> Callable[ + [programs.GetProgramRequest], + Union[ + programs.Program, + Awaitable[programs.Program] + ]]: + raise NotImplementedError() + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + Union[ + programs.ListProgramsResponse, + Awaitable[programs.ListProgramsResponse] + ]]: + raise NotImplementedError() + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + Union[ + programs.Program, + Awaitable[programs.Program] + ]]: + raise NotImplementedError() + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + Union[ + programs.Program, + Awaitable[programs.Program] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProgramsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py new file mode 100644 index 000000000000..0b38768d78c0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py @@ -0,0 +1,436 @@ +# -*- 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.shopping.merchant_accounts_v1.types import programs +from .base import ProgramsServiceTransport, 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.accounts.v1.ProgramsService", + "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.accounts.v1.ProgramsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ProgramsServiceGrpcTransport(ProgramsServiceTransport): + """gRPC backend transport for ProgramsService. + + Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a business's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + + 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 get_program(self) -> Callable[ + [programs.GetProgramRequest], + programs.Program]: + r"""Return a callable for the get program method over gRPC. + + Retrieves the specified program for the account. + + Returns: + Callable[[~.GetProgramRequest], + ~.Program]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_program' not in self._stubs: + self._stubs['get_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/GetProgram', + request_serializer=programs.GetProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['get_program'] + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + programs.ListProgramsResponse]: + r"""Return a callable for the list programs method over gRPC. + + Retrieves all programs for the account. + + Returns: + Callable[[~.ListProgramsRequest], + ~.ListProgramsResponse]: + 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_programs' not in self._stubs: + self._stubs['list_programs'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/ListPrograms', + request_serializer=programs.ListProgramsRequest.serialize, + response_deserializer=programs.ListProgramsResponse.deserialize, + ) + return self._stubs['list_programs'] + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + programs.Program]: + r"""Return a callable for the enable program method over gRPC. + + Enable participation in the specified program for the + account. + + Returns: + Callable[[~.EnableProgramRequest], + ~.Program]: + 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 'enable_program' not in self._stubs: + self._stubs['enable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/EnableProgram', + request_serializer=programs.EnableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['enable_program'] + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + programs.Program]: + r"""Return a callable for the disable program method over gRPC. + + Disable participation in the specified program for + the account. + + Returns: + Callable[[~.DisableProgramRequest], + ~.Program]: + 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 'disable_program' not in self._stubs: + self._stubs['disable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/DisableProgram', + request_serializer=programs.DisableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['disable_program'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProgramsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..5d146558736a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py @@ -0,0 +1,472 @@ +# -*- 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.shopping.merchant_accounts_v1.types import programs +from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProgramsServiceGrpcTransport + +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.accounts.v1.ProgramsService", + "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.accounts.v1.ProgramsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ProgramsServiceGrpcAsyncIOTransport(ProgramsServiceTransport): + """gRPC AsyncIO backend transport for ProgramsService. + + Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a business's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + + 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 get_program(self) -> Callable[ + [programs.GetProgramRequest], + Awaitable[programs.Program]]: + r"""Return a callable for the get program method over gRPC. + + Retrieves the specified program for the account. + + Returns: + Callable[[~.GetProgramRequest], + Awaitable[~.Program]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_program' not in self._stubs: + self._stubs['get_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/GetProgram', + request_serializer=programs.GetProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['get_program'] + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + Awaitable[programs.ListProgramsResponse]]: + r"""Return a callable for the list programs method over gRPC. + + Retrieves all programs for the account. + + Returns: + Callable[[~.ListProgramsRequest], + Awaitable[~.ListProgramsResponse]]: + 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_programs' not in self._stubs: + self._stubs['list_programs'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/ListPrograms', + request_serializer=programs.ListProgramsRequest.serialize, + response_deserializer=programs.ListProgramsResponse.deserialize, + ) + return self._stubs['list_programs'] + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + Awaitable[programs.Program]]: + r"""Return a callable for the enable program method over gRPC. + + Enable participation in the specified program for the + account. + + Returns: + Callable[[~.EnableProgramRequest], + Awaitable[~.Program]]: + 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 'enable_program' not in self._stubs: + self._stubs['enable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/EnableProgram', + request_serializer=programs.EnableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['enable_program'] + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + Awaitable[programs.Program]]: + r"""Return a callable for the disable program method over gRPC. + + Disable participation in the specified program for + the account. + + Returns: + Callable[[~.DisableProgramRequest], + Awaitable[~.Program]]: + 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 'disable_program' not in self._stubs: + self._stubs['disable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ProgramsService/DisableProgram', + request_serializer=programs.DisableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['disable_program'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_program: self._wrap_method( + self.get_program, + default_timeout=None, + client_info=client_info, + ), + self.list_programs: self._wrap_method( + self.list_programs, + default_timeout=None, + client_info=client_info, + ), + self.enable_program: self._wrap_method( + self.enable_program, + default_timeout=None, + client_info=client_info, + ), + self.disable_program: self._wrap_method( + self.disable_program, + 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__ = ( + 'ProgramsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py new file mode 100644 index 000000000000..a56450e66673 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py @@ -0,0 +1,934 @@ +# -*- 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.shopping.merchant_accounts_v1.types import programs + + +from .rest_base import _BaseProgramsServiceRestTransport +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 ProgramsServiceRestInterceptor: + """Interceptor for ProgramsService. + + 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 ProgramsServiceRestTransport. + + .. code-block:: python + class MyCustomProgramsServiceInterceptor(ProgramsServiceRestInterceptor): + def pre_disable_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_programs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_programs(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProgramsServiceRestTransport(interceptor=MyCustomProgramsServiceInterceptor()) + client = ProgramsServiceClient(transport=transport) + + + """ + def pre_disable_program(self, request: programs.DisableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for disable_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_disable_program(self, response: programs.Program) -> programs.Program: + """Post-rpc interceptor for disable_program + + DEPRECATED. Please use the `post_disable_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_disable_program` interceptor runs + before the `post_disable_program_with_metadata` interceptor. + """ + return response + + def post_disable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for disable_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_disable_program_with_metadata` + interceptor in new development instead of the `post_disable_program` interceptor. + When both interceptors are used, this `post_disable_program_with_metadata` interceptor runs after the + `post_disable_program` interceptor. The (possibly modified) response returned by + `post_disable_program` will be passed to + `post_disable_program_with_metadata`. + """ + return response, metadata + + def pre_enable_program(self, request: programs.EnableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for enable_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_enable_program(self, response: programs.Program) -> programs.Program: + """Post-rpc interceptor for enable_program + + DEPRECATED. Please use the `post_enable_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_enable_program` interceptor runs + before the `post_enable_program_with_metadata` interceptor. + """ + return response + + def post_enable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for enable_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_enable_program_with_metadata` + interceptor in new development instead of the `post_enable_program` interceptor. + When both interceptors are used, this `post_enable_program_with_metadata` interceptor runs after the + `post_enable_program` interceptor. The (possibly modified) response returned by + `post_enable_program` will be passed to + `post_enable_program_with_metadata`. + """ + return response, metadata + + def pre_get_program(self, request: programs.GetProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_get_program(self, response: programs.Program) -> programs.Program: + """Post-rpc interceptor for get_program + + DEPRECATED. Please use the `post_get_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_get_program` interceptor runs + before the `post_get_program_with_metadata` interceptor. + """ + return response + + def post_get_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_get_program_with_metadata` + interceptor in new development instead of the `post_get_program` interceptor. + When both interceptors are used, this `post_get_program_with_metadata` interceptor runs after the + `post_get_program` interceptor. The (possibly modified) response returned by + `post_get_program` will be passed to + `post_get_program_with_metadata`. + """ + return response, metadata + + def pre_list_programs(self, request: programs.ListProgramsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_programs + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_list_programs(self, response: programs.ListProgramsResponse) -> programs.ListProgramsResponse: + """Post-rpc interceptor for list_programs + + DEPRECATED. Please use the `post_list_programs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_list_programs` interceptor runs + before the `post_list_programs_with_metadata` interceptor. + """ + return response + + def post_list_programs_with_metadata(self, response: programs.ListProgramsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_programs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_list_programs_with_metadata` + interceptor in new development instead of the `post_list_programs` interceptor. + When both interceptors are used, this `post_list_programs_with_metadata` interceptor runs after the + `post_list_programs` interceptor. The (possibly modified) response returned by + `post_list_programs` will be passed to + `post_list_programs_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ProgramsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProgramsServiceRestInterceptor + + +class ProgramsServiceRestTransport(_BaseProgramsServiceRestTransport): + """REST backend synchronous transport for ProgramsService. + + Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a business's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + + 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[ProgramsServiceRestInterceptor] = 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 ProgramsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DisableProgram(_BaseProgramsServiceRestTransport._BaseDisableProgram, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.DisableProgram") + + @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: programs.DisableProgramRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.Program: + r"""Call the disable program method over HTTP. + + Args: + request (~.programs.DisableProgramRequest): + The request object. Request message for the + DisableProgram 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: + ~.programs.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality to + a Merchant Center accounts. A typical example of this is + the `Free product + listings `__ + program, which enables products from a business's store + to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - ``free-listings`` + - ``shopping-ads`` + - ``youtube-shopping-checkout`` + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_http_options() + + request, metadata = self._interceptor.pre_disable_program(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_transcoded_request(http_options, request) + + body = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.DisableProgram", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "DisableProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._DisableProgram._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 = programs.Program() + pb_resp = programs.Program.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_disable_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_disable_program_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.Program.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.accounts_v1.ProgramsServiceClient.disable_program", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "DisableProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _EnableProgram(_BaseProgramsServiceRestTransport._BaseEnableProgram, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.EnableProgram") + + @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: programs.EnableProgramRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.Program: + r"""Call the enable program method over HTTP. + + Args: + request (~.programs.EnableProgramRequest): + The request object. Request message for the EnableProgram + 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: + ~.programs.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality to + a Merchant Center accounts. A typical example of this is + the `Free product + listings `__ + program, which enables products from a business's store + to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - ``free-listings`` + - ``shopping-ads`` + - ``youtube-shopping-checkout`` + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_http_options() + + request, metadata = self._interceptor.pre_enable_program(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_transcoded_request(http_options, request) + + body = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.EnableProgram", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "EnableProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._EnableProgram._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 = programs.Program() + pb_resp = programs.Program.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_enable_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_enable_program_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.Program.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.accounts_v1.ProgramsServiceClient.enable_program", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "EnableProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetProgram(_BaseProgramsServiceRestTransport._BaseGetProgram, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.GetProgram") + + @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: programs.GetProgramRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.Program: + r"""Call the get program method over HTTP. + + Args: + request (~.programs.GetProgramRequest): + The request object. Request message for the GetProgram + 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: + ~.programs.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality to + a Merchant Center accounts. A typical example of this is + the `Free product + listings `__ + program, which enables products from a business's store + to be shown across Google for free. + + The following list is the available set of program + resource IDs accessible through the API: + + - ``free-listings`` + - ``shopping-ads`` + - ``youtube-shopping-checkout`` + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseGetProgram._get_http_options() + + request, metadata = self._interceptor.pre_get_program(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseGetProgram._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseGetProgram._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.GetProgram", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "GetProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._GetProgram._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 = programs.Program() + pb_resp = programs.Program.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_program_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.Program.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.accounts_v1.ProgramsServiceClient.get_program", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "GetProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPrograms(_BaseProgramsServiceRestTransport._BaseListPrograms, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.ListPrograms") + + @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: programs.ListProgramsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.ListProgramsResponse: + r"""Call the list programs method over HTTP. + + Args: + request (~.programs.ListProgramsRequest): + The request object. Request message for the ListPrograms + 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: + ~.programs.ListProgramsResponse: + Response message for the ListPrograms + method. + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseListPrograms._get_http_options() + + request, metadata = self._interceptor.pre_list_programs(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseListPrograms._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseListPrograms._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.ListPrograms", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "ListPrograms", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._ListPrograms._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 = programs.ListProgramsResponse() + pb_resp = programs.ListProgramsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_programs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_programs_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.ListProgramsResponse.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.accounts_v1.ProgramsServiceClient.list_programs", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", + "rpcName": "ListPrograms", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + programs.Program]: + # 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._DisableProgram(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + programs.Program]: + # 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._EnableProgram(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_program(self) -> Callable[ + [programs.GetProgramRequest], + programs.Program]: + # 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._GetProgram(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + programs.ListProgramsResponse]: + # 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._ListPrograms(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ProgramsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py new file mode 100644 index 000000000000..841b18e2ca4f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py @@ -0,0 +1,259 @@ +# -*- 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 ProgramsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import programs + + +class _BaseProgramsServiceRestTransport(ProgramsServiceTransport): + """Base REST backend transport for ProgramsService. + + 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 _BaseDisableProgram: + 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': '/accounts/v1/{name=accounts/*/programs/*}:disable', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.DisableProgramRequest.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(_BaseProgramsServiceRestTransport._BaseDisableProgram._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEnableProgram: + 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': '/accounts/v1/{name=accounts/*/programs/*}:enable', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.EnableProgramRequest.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(_BaseProgramsServiceRestTransport._BaseEnableProgram._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProgram: + 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': '/accounts/v1/{name=accounts/*/programs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.GetProgramRequest.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(_BaseProgramsServiceRestTransport._BaseGetProgram._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPrograms: + 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': '/accounts/v1/{parent=accounts/*}/programs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.ListProgramsRequest.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(_BaseProgramsServiceRestTransport._BaseListPrograms._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseProgramsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py new file mode 100644 index 000000000000..4809e9fed9f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_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 RegionsServiceClient +from .async_client import RegionsServiceAsyncClient + +__all__ = ( + 'RegionsServiceClient', + 'RegionsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py new file mode 100644 index 000000000000..0a23741838d8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py @@ -0,0 +1,847 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.regions_service import pagers +from google.shopping.merchant_accounts_v1.types import regions +from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport +from .client import RegionsServiceClient + +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 RegionsServiceAsyncClient: + """Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1.Region] + """ + + _client: RegionsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RegionsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RegionsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(RegionsServiceClient.account_path) + parse_account_path = staticmethod(RegionsServiceClient.parse_account_path) + region_path = staticmethod(RegionsServiceClient.region_path) + parse_region_path = staticmethod(RegionsServiceClient.parse_region_path) + common_billing_account_path = staticmethod(RegionsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegionsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegionsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegionsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegionsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegionsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegionsServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegionsServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegionsServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegionsServiceClient.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: + RegionsServiceAsyncClient: The constructed client. + """ + return RegionsServiceClient.from_service_account_info.__func__(RegionsServiceAsyncClient, 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: + RegionsServiceAsyncClient: The constructed client. + """ + return RegionsServiceClient.from_service_account_file.__func__(RegionsServiceAsyncClient, 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 RegionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RegionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionsServiceTransport: 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 = RegionsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regions 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,RegionsServiceTransport,Callable[..., RegionsServiceTransport]]]): + 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 RegionsServiceTransport 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 = RegionsServiceClient( + 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.accounts_v1.RegionsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "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.accounts.v1.RegionsService", + "credentialsType": None, + } + ) + + async def get_region(self, + request: Optional[Union[regions.GetRegionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Retrieves a region defined in your Merchant Center + 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_accounts_v1 + + async def sample_get_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_region(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetRegionRequest, dict]]): + The request object. Request message for the ``GetRegion`` method. + name (:class:`str`): + Required. The name of the region to retrieve. Format: + ``accounts/{account}/regions/{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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, regions.GetRegionRequest): + request = regions.GetRegionRequest(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.get_region] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_region(self, + request: Optional[Union[regions.CreateRegionRequest, dict]] = None, + *, + parent: Optional[str] = None, + region: Optional[regions.Region] = None, + region_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1 + + async def sample_create_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = await client.create_region(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.CreateRegionRequest, dict]]): + The request object. Request message for the ``CreateRegion`` method. + parent (:class:`str`): + Required. The account to create a region for. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (:class:`google.shopping.merchant_accounts_v1.types.Region`): + Required. The region to create. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_id (:class:`str`): + Required. The identifier for the + region, unique over all regions of the + same account. + + This corresponds to the ``region_id`` 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_accounts_v1.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, region, region_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.CreateRegionRequest): + request = regions.CreateRegionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if region is not None: + request.region = region + if region_id is not None: + request.region_id = region_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_region] + + # 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 update_region(self, + request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, + *, + region: Optional[regions.Region] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1 + + async def sample_update_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateRegionRequest( + ) + + # Make the request + response = await client.update_region(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateRegionRequest, dict]]): + The request object. Request message for the ``UpdateRegion`` method. + region (:class:`google.shopping.merchant_accounts_v1.types.Region`): + Required. The updated region. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The comma-separated field mask indicating the + fields to update. Example: + ``"displayName,postalCodeArea.regionCode"``. + + This corresponds to the ``update_mask`` 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_accounts_v1.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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 = [region, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.UpdateRegionRequest): + request = regions.UpdateRegionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if region is not None: + request.region = region + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_region] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("region.name", request.region.name), + )), + ) + + # 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_region(self, + request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, + *, + name: 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 a region definition from your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1 + + async def sample_delete_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + await client.delete_region(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.DeleteRegionRequest, dict]]): + The request object. Request message for the ``DeleteRegion`` method. + name (:class:`str`): + Required. The name of the region to delete. Format: + ``accounts/{account}/regions/{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, regions.DeleteRegionRequest): + request = regions.DeleteRegionRequest(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_region] + + # 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 list_regions(self, + request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsAsyncPager: + r"""Lists the regions in your Merchant Center 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_accounts_v1 + + async def sample_list_regions(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListRegionsRequest, dict]]): + The request object. Request message for the ``ListRegions`` method. + parent (:class:`str`): + Required. The account to list regions for. Format: + ``accounts/{account}`` + + 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_accounts_v1.services.regions_service.pagers.ListRegionsAsyncPager: + Response message for the ListRegions 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, regions.ListRegionsRequest): + request = regions.ListRegionsRequest(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_regions] + + # 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.ListRegionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RegionsServiceAsyncClient": + 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__ = ( + "RegionsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py new file mode 100644 index 000000000000..97e99287902d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py @@ -0,0 +1,1212 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.regions_service import pagers +from google.shopping.merchant_accounts_v1.types import regions +from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegionsServiceGrpcTransport +from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport +from .transports.rest import RegionsServiceRestTransport + + +class RegionsServiceClientMeta(type): + """Metaclass for the RegionsService 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[RegionsServiceTransport]] + _transport_registry["grpc"] = RegionsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegionsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RegionsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RegionsServiceTransport]: + """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 RegionsServiceClient(metaclass=RegionsServiceClientMeta): + """Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1.Region] + """ + + @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: + RegionsServiceClient: 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: + RegionsServiceClient: 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) -> RegionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def region_path(account: str,region: str,) -> str: + """Returns a fully-qualified region string.""" + return "accounts/{account}/regions/{region}".format(account=account, region=region, ) + + @staticmethod + def parse_region_path(path: str) -> Dict[str,str]: + """Parses a region path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/regions/(?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 = RegionsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RegionsServiceClient._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 = RegionsServiceClient._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, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regions 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,RegionsServiceTransport,Callable[..., RegionsServiceTransport]]]): + 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 RegionsServiceTransport 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 = RegionsServiceClient._read_environment_variables() + self._client_cert_source = RegionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RegionsServiceClient._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, RegionsServiceTransport) + if transport_provided: + # transport is a RegionsServiceTransport 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(RegionsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RegionsServiceClient._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[RegionsServiceTransport], Callable[..., RegionsServiceTransport]] = ( + RegionsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionsServiceTransport], 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.accounts_v1.RegionsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "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.accounts.v1.RegionsService", + "credentialsType": None, + } + ) + + def get_region(self, + request: Optional[Union[regions.GetRegionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Retrieves a region defined in your Merchant Center + 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_accounts_v1 + + def sample_get_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = client.get_region(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetRegionRequest, dict]): + The request object. Request message for the ``GetRegion`` method. + name (str): + Required. The name of the region to retrieve. Format: + ``accounts/{account}/regions/{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`. + + Returns: + google.shopping.merchant_accounts_v1.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, regions.GetRegionRequest): + request = regions.GetRegionRequest(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.get_region] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_region(self, + request: Optional[Union[regions.CreateRegionRequest, dict]] = None, + *, + parent: Optional[str] = None, + region: Optional[regions.Region] = None, + region_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1 + + def sample_create_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = client.create_region(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.CreateRegionRequest, dict]): + The request object. Request message for the ``CreateRegion`` method. + parent (str): + Required. The account to create a region for. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (google.shopping.merchant_accounts_v1.types.Region): + Required. The region to create. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_id (str): + Required. The identifier for the + region, unique over all regions of the + same account. + + This corresponds to the ``region_id`` 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_accounts_v1.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, region, region_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.CreateRegionRequest): + request = regions.CreateRegionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if region is not None: + request.region = region + if region_id is not None: + request.region_id = region_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_region] + + # 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 update_region(self, + request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, + *, + region: Optional[regions.Region] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1 + + def sample_update_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateRegionRequest( + ) + + # Make the request + response = client.update_region(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateRegionRequest, dict]): + The request object. Request message for the ``UpdateRegion`` method. + region (google.shopping.merchant_accounts_v1.types.Region): + Required. The updated region. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The comma-separated field mask indicating the + fields to update. Example: + ``"displayName,postalCodeArea.regionCode"``. + + This corresponds to the ``update_mask`` 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_accounts_v1.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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 = [region, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.UpdateRegionRequest): + request = regions.UpdateRegionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if region is not None: + request.region = region + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_region] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("region.name", request.region.name), + )), + ) + + # 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_region(self, + request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, + *, + name: 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 a region definition from your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1 + + def sample_delete_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + client.delete_region(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.DeleteRegionRequest, dict]): + The request object. Request message for the ``DeleteRegion`` method. + name (str): + Required. The name of the region to delete. Format: + ``accounts/{account}/regions/{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, regions.DeleteRegionRequest): + request = regions.DeleteRegionRequest(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_region] + + # 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 list_regions(self, + request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsPager: + r"""Lists the regions in your Merchant Center 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_accounts_v1 + + def sample_list_regions(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListRegionsRequest, dict]): + The request object. Request message for the ``ListRegions`` method. + parent (str): + Required. The account to list regions for. Format: + ``accounts/{account}`` + + 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_accounts_v1.services.regions_service.pagers.ListRegionsPager: + Response message for the ListRegions 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, regions.ListRegionsRequest): + request = regions.ListRegionsRequest(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_regions] + + # 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.ListRegionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RegionsServiceClient": + 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__ = ( + "RegionsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py new file mode 100644 index 000000000000..6a25efa04dd8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_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_accounts_v1.types import regions + + +class ListRegionsPager: + """A pager for iterating through ``list_regions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListRegionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``regions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRegions`` requests and continue to iterate + through the ``regions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListRegionsResponse` + 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[..., regions.ListRegionsResponse], + request: regions.ListRegionsRequest, + response: regions.ListRegionsResponse, + *, + 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_accounts_v1.types.ListRegionsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListRegionsResponse): + 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 = regions.ListRegionsRequest(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[regions.ListRegionsResponse]: + 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[regions.Region]: + for page in self.pages: + yield from page.regions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRegionsAsyncPager: + """A pager for iterating through ``list_regions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListRegionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``regions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRegions`` requests and continue to iterate + through the ``regions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListRegionsResponse` + 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[regions.ListRegionsResponse]], + request: regions.ListRegionsRequest, + response: regions.ListRegionsResponse, + *, + 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_accounts_v1.types.ListRegionsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListRegionsResponse): + 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 = regions.ListRegionsRequest(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[regions.ListRegionsResponse]: + 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[regions.Region]: + async def async_generator(): + async for page in self.pages: + for response in page.regions: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst new file mode 100644 index 000000000000..58b1a6574ad7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionsServiceTransport` is the ABC for all transports. +- public child `RegionsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py new file mode 100644 index 000000000000..e958dfda0512 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_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 RegionsServiceTransport +from .grpc import RegionsServiceGrpcTransport +from .grpc_asyncio import RegionsServiceGrpcAsyncIOTransport +from .rest import RegionsServiceRestTransport +from .rest import RegionsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegionsServiceTransport]] +_transport_registry['grpc'] = RegionsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegionsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RegionsServiceRestTransport + +__all__ = ( + 'RegionsServiceTransport', + 'RegionsServiceGrpcTransport', + 'RegionsServiceGrpcAsyncIOTransport', + 'RegionsServiceRestTransport', + 'RegionsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py new file mode 100644 index 000000000000..a1f149140f44 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py @@ -0,0 +1,216 @@ +# -*- 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_accounts_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_accounts_v1.types import regions + +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 RegionsServiceTransport(abc.ABC): + """Abstract transport class for RegionsService.""" + + 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.get_region: gapic_v1.method.wrap_method( + self.get_region, + default_timeout=None, + client_info=client_info, + ), + self.create_region: gapic_v1.method.wrap_method( + self.create_region, + default_timeout=None, + client_info=client_info, + ), + self.update_region: gapic_v1.method.wrap_method( + self.update_region, + default_timeout=None, + client_info=client_info, + ), + self.delete_region: gapic_v1.method.wrap_method( + self.delete_region, + default_timeout=None, + client_info=client_info, + ), + self.list_regions: gapic_v1.method.wrap_method( + self.list_regions, + 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 get_region(self) -> Callable[ + [regions.GetRegionRequest], + Union[ + regions.Region, + Awaitable[regions.Region] + ]]: + raise NotImplementedError() + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + Union[ + regions.Region, + Awaitable[regions.Region] + ]]: + raise NotImplementedError() + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + Union[ + regions.Region, + Awaitable[regions.Region] + ]]: + raise NotImplementedError() + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + Union[ + regions.ListRegionsResponse, + Awaitable[regions.ListRegionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RegionsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py new file mode 100644 index 000000000000..3c9745b0a812 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py @@ -0,0 +1,459 @@ +# -*- 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_accounts_v1.types import regions +from .base import RegionsServiceTransport, 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.accounts.v1.RegionsService", + "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.accounts.v1.RegionsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionsServiceGrpcTransport(RegionsServiceTransport): + """gRPC backend transport for RegionsService. + + Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1.Region] + + 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 get_region(self) -> Callable[ + [regions.GetRegionRequest], + regions.Region]: + r"""Return a callable for the get region method over gRPC. + + Retrieves a region defined in your Merchant Center + account. + + Returns: + Callable[[~.GetRegionRequest], + ~.Region]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_region' not in self._stubs: + self._stubs['get_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/GetRegion', + request_serializer=regions.GetRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['get_region'] + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + regions.Region]: + r"""Return a callable for the create region method over gRPC. + + Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.CreateRegionRequest], + ~.Region]: + 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 'create_region' not in self._stubs: + self._stubs['create_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/CreateRegion', + request_serializer=regions.CreateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['create_region'] + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + regions.Region]: + r"""Return a callable for the update region method over gRPC. + + Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.UpdateRegionRequest], + ~.Region]: + 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 'update_region' not in self._stubs: + self._stubs['update_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/UpdateRegion', + request_serializer=regions.UpdateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['update_region'] + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete region method over gRPC. + + Deletes a region definition from your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.DeleteRegionRequest], + ~.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_region' not in self._stubs: + self._stubs['delete_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/DeleteRegion', + request_serializer=regions.DeleteRegionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_region'] + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + regions.ListRegionsResponse]: + r"""Return a callable for the list regions method over gRPC. + + Lists the regions in your Merchant Center account. + + Returns: + Callable[[~.ListRegionsRequest], + ~.ListRegionsResponse]: + 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_regions' not in self._stubs: + self._stubs['list_regions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/ListRegions', + request_serializer=regions.ListRegionsRequest.serialize, + response_deserializer=regions.ListRegionsResponse.deserialize, + ) + return self._stubs['list_regions'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RegionsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..0c9b25f62067 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py @@ -0,0 +1,500 @@ +# -*- 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_accounts_v1.types import regions +from .base import RegionsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegionsServiceGrpcTransport + +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.accounts.v1.RegionsService", + "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.accounts.v1.RegionsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionsServiceGrpcAsyncIOTransport(RegionsServiceTransport): + """gRPC AsyncIO backend transport for RegionsService. + + Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1.Region] + + 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 get_region(self) -> Callable[ + [regions.GetRegionRequest], + Awaitable[regions.Region]]: + r"""Return a callable for the get region method over gRPC. + + Retrieves a region defined in your Merchant Center + account. + + Returns: + Callable[[~.GetRegionRequest], + Awaitable[~.Region]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_region' not in self._stubs: + self._stubs['get_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/GetRegion', + request_serializer=regions.GetRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['get_region'] + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + Awaitable[regions.Region]]: + r"""Return a callable for the create region method over gRPC. + + Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.CreateRegionRequest], + Awaitable[~.Region]]: + 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 'create_region' not in self._stubs: + self._stubs['create_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/CreateRegion', + request_serializer=regions.CreateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['create_region'] + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + Awaitable[regions.Region]]: + r"""Return a callable for the update region method over gRPC. + + Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.UpdateRegionRequest], + Awaitable[~.Region]]: + 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 'update_region' not in self._stubs: + self._stubs['update_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/UpdateRegion', + request_serializer=regions.UpdateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['update_region'] + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete region method over gRPC. + + Deletes a region definition from your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.DeleteRegionRequest], + 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_region' not in self._stubs: + self._stubs['delete_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/DeleteRegion', + request_serializer=regions.DeleteRegionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_region'] + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + Awaitable[regions.ListRegionsResponse]]: + r"""Return a callable for the list regions method over gRPC. + + Lists the regions in your Merchant Center account. + + Returns: + Callable[[~.ListRegionsRequest], + Awaitable[~.ListRegionsResponse]]: + 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_regions' not in self._stubs: + self._stubs['list_regions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.RegionsService/ListRegions', + request_serializer=regions.ListRegionsRequest.serialize, + response_deserializer=regions.ListRegionsResponse.deserialize, + ) + return self._stubs['list_regions'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_region: self._wrap_method( + self.get_region, + default_timeout=None, + client_info=client_info, + ), + self.create_region: self._wrap_method( + self.create_region, + default_timeout=None, + client_info=client_info, + ), + self.update_region: self._wrap_method( + self.update_region, + default_timeout=None, + client_info=client_info, + ), + self.delete_region: self._wrap_method( + self.delete_region, + default_timeout=None, + client_info=client_info, + ), + self.list_regions: self._wrap_method( + self.list_regions, + 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__ = ( + 'RegionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py new file mode 100644 index 000000000000..d0e734288934 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py @@ -0,0 +1,1004 @@ +# -*- 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_accounts_v1.types import regions + + +from .rest_base import _BaseRegionsServiceRestTransport +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 RegionsServiceRestInterceptor: + """Interceptor for RegionsService. + + 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 RegionsServiceRestTransport. + + .. code-block:: python + class MyCustomRegionsServiceInterceptor(RegionsServiceRestInterceptor): + def pre_create_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_region(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_region(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_regions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_regions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_region(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionsServiceRestTransport(interceptor=MyCustomRegionsServiceInterceptor()) + client = RegionsServiceClient(transport=transport) + + + """ + def pre_create_region(self, request: regions.CreateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_create_region(self, response: regions.Region) -> regions.Region: + """Post-rpc interceptor for create_region + + DEPRECATED. Please use the `post_create_region_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_create_region` interceptor runs + before the `post_create_region_with_metadata` interceptor. + """ + return response + + def post_create_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_region + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_create_region_with_metadata` + interceptor in new development instead of the `post_create_region` interceptor. + When both interceptors are used, this `post_create_region_with_metadata` interceptor runs after the + `post_create_region` interceptor. The (possibly modified) response returned by + `post_create_region` will be passed to + `post_create_region_with_metadata`. + """ + return response, metadata + + def pre_delete_region(self, request: regions.DeleteRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def pre_get_region(self, request: regions.GetRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_get_region(self, response: regions.Region) -> regions.Region: + """Post-rpc interceptor for get_region + + DEPRECATED. Please use the `post_get_region_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_get_region` interceptor runs + before the `post_get_region_with_metadata` interceptor. + """ + return response + + def post_get_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_region + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_get_region_with_metadata` + interceptor in new development instead of the `post_get_region` interceptor. + When both interceptors are used, this `post_get_region_with_metadata` interceptor runs after the + `post_get_region` interceptor. The (possibly modified) response returned by + `post_get_region` will be passed to + `post_get_region_with_metadata`. + """ + return response, metadata + + def pre_list_regions(self, request: regions.ListRegionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_regions + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_list_regions(self, response: regions.ListRegionsResponse) -> regions.ListRegionsResponse: + """Post-rpc interceptor for list_regions + + DEPRECATED. Please use the `post_list_regions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_list_regions` interceptor runs + before the `post_list_regions_with_metadata` interceptor. + """ + return response + + def post_list_regions_with_metadata(self, response: regions.ListRegionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_regions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_list_regions_with_metadata` + interceptor in new development instead of the `post_list_regions` interceptor. + When both interceptors are used, this `post_list_regions_with_metadata` interceptor runs after the + `post_list_regions` interceptor. The (possibly modified) response returned by + `post_list_regions` will be passed to + `post_list_regions_with_metadata`. + """ + return response, metadata + + def pre_update_region(self, request: regions.UpdateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_update_region(self, response: regions.Region) -> regions.Region: + """Post-rpc interceptor for update_region + + DEPRECATED. Please use the `post_update_region_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_update_region` interceptor runs + before the `post_update_region_with_metadata` interceptor. + """ + return response + + def post_update_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_region + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_update_region_with_metadata` + interceptor in new development instead of the `post_update_region` interceptor. + When both interceptors are used, this `post_update_region_with_metadata` interceptor runs after the + `post_update_region` interceptor. The (possibly modified) response returned by + `post_update_region` will be passed to + `post_update_region_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RegionsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionsServiceRestInterceptor + + +class RegionsServiceRestTransport(_BaseRegionsServiceRestTransport): + """REST backend synchronous transport for RegionsService. + + Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1.Region] + + 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[RegionsServiceRestInterceptor] = 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 RegionsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateRegion(_BaseRegionsServiceRestTransport._BaseCreateRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.CreateRegion") + + @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: regions.CreateRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.Region: + r"""Call the create region method over HTTP. + + Args: + request (~.regions.CreateRegionRequest): + The request object. Request message for the ``CreateRegion`` 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: + ~.regions.Region: + Represents a geographic region that you can use as a + target with both the ``RegionalInventory`` and + ``ShippingSettings`` services. You can define regions as + collections of either postal codes or, in some + countries, using predefined geotargets. For more + information, see `Set up + regions `__ + for more information. + + """ + + http_options = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_http_options() + + request, metadata = self._interceptor.pre_create_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_transcoded_request(http_options, request) + + body = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.CreateRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "CreateRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._CreateRegion._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 = regions.Region() + pb_resp = regions.Region.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_region(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_region_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.Region.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.accounts_v1.RegionsServiceClient.create_region", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "CreateRegion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteRegion(_BaseRegionsServiceRestTransport._BaseDeleteRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.DeleteRegion") + + @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: regions.DeleteRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete region method over HTTP. + + Args: + request (~.regions.DeleteRegionRequest): + The request object. Request message for the ``DeleteRegion`` 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 = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_http_options() + + request, metadata = self._interceptor.pre_delete_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.DeleteRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "DeleteRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._DeleteRegion._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 _GetRegion(_BaseRegionsServiceRestTransport._BaseGetRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.GetRegion") + + @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: regions.GetRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.Region: + r"""Call the get region method over HTTP. + + Args: + request (~.regions.GetRegionRequest): + The request object. Request message for the ``GetRegion`` 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: + ~.regions.Region: + Represents a geographic region that you can use as a + target with both the ``RegionalInventory`` and + ``ShippingSettings`` services. You can define regions as + collections of either postal codes or, in some + countries, using predefined geotargets. For more + information, see `Set up + regions `__ + for more information. + + """ + + http_options = _BaseRegionsServiceRestTransport._BaseGetRegion._get_http_options() + + request, metadata = self._interceptor.pre_get_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseGetRegion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseGetRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.GetRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "GetRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._GetRegion._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 = regions.Region() + pb_resp = regions.Region.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_region(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_region_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.Region.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.accounts_v1.RegionsServiceClient.get_region", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "GetRegion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRegions(_BaseRegionsServiceRestTransport._BaseListRegions, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.ListRegions") + + @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: regions.ListRegionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.ListRegionsResponse: + r"""Call the list regions method over HTTP. + + Args: + request (~.regions.ListRegionsRequest): + The request object. Request message for the ``ListRegions`` 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: + ~.regions.ListRegionsResponse: + Response message for the ``ListRegions`` method. + """ + + http_options = _BaseRegionsServiceRestTransport._BaseListRegions._get_http_options() + + request, metadata = self._interceptor.pre_list_regions(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseListRegions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseListRegions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.ListRegions", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "ListRegions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._ListRegions._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 = regions.ListRegionsResponse() + pb_resp = regions.ListRegionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_regions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_regions_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.ListRegionsResponse.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.accounts_v1.RegionsServiceClient.list_regions", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "ListRegions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateRegion(_BaseRegionsServiceRestTransport._BaseUpdateRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.UpdateRegion") + + @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: regions.UpdateRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.Region: + r"""Call the update region method over HTTP. + + Args: + request (~.regions.UpdateRegionRequest): + The request object. Request message for the ``UpdateRegion`` 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: + ~.regions.Region: + Represents a geographic region that you can use as a + target with both the ``RegionalInventory`` and + ``ShippingSettings`` services. You can define regions as + collections of either postal codes or, in some + countries, using predefined geotargets. For more + information, see `Set up + regions `__ + for more information. + + """ + + http_options = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_http_options() + + request, metadata = self._interceptor.pre_update_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_transcoded_request(http_options, request) + + body = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.UpdateRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "UpdateRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._UpdateRegion._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 = regions.Region() + pb_resp = regions.Region.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_region(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_region_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.Region.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.accounts_v1.RegionsServiceClient.update_region", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", + "rpcName": "UpdateRegion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + regions.Region]: + # 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._CreateRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + 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._DeleteRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_region(self) -> Callable[ + [regions.GetRegionRequest], + regions.Region]: + # 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._GetRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + regions.ListRegionsResponse]: + # 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._ListRegions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + regions.Region]: + # 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._UpdateRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RegionsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py new file mode 100644 index 000000000000..1ce66206aae9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py @@ -0,0 +1,297 @@ +# -*- 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 RegionsServiceTransport, 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_accounts_v1.types import regions + + +class _BaseRegionsServiceRestTransport(RegionsServiceTransport): + """Base REST backend transport for RegionsService. + + 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 _BaseCreateRegion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "regionId" : "", } + + @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': '/accounts/v1/{parent=accounts/*}/regions', + 'body': 'region', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.CreateRegionRequest.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(_BaseRegionsServiceRestTransport._BaseCreateRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteRegion: + 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': '/accounts/v1/{name=accounts/*/regions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.DeleteRegionRequest.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(_BaseRegionsServiceRestTransport._BaseDeleteRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRegion: + 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': '/accounts/v1/{name=accounts/*/regions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.GetRegionRequest.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(_BaseRegionsServiceRestTransport._BaseGetRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRegions: + 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': '/accounts/v1/{parent=accounts/*}/regions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.ListRegionsRequest.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(_BaseRegionsServiceRestTransport._BaseListRegions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateRegion: + 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': 'patch', + 'uri': '/accounts/v1/{region.name=accounts/*/regions/*}', + 'body': 'region', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.UpdateRegionRequest.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(_BaseRegionsServiceRestTransport._BaseUpdateRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRegionsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py new file mode 100644 index 000000000000..023e41c50a7f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_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 ShippingSettingsServiceClient +from .async_client import ShippingSettingsServiceAsyncClient + +__all__ = ( + 'ShippingSettingsServiceClient', + 'ShippingSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py new file mode 100644 index 000000000000..0325c9e594f1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py @@ -0,0 +1,469 @@ +# -*- 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_accounts_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_accounts_v1.types import shippingsettings +from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport +from .client import ShippingSettingsServiceClient + +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 ShippingSettingsServiceAsyncClient: + """Service to get method call shipping setting information per + Merchant API method. + """ + + _client: ShippingSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(ShippingSettingsServiceClient.account_path) + parse_account_path = staticmethod(ShippingSettingsServiceClient.parse_account_path) + shipping_settings_path = staticmethod(ShippingSettingsServiceClient.shipping_settings_path) + parse_shipping_settings_path = staticmethod(ShippingSettingsServiceClient.parse_shipping_settings_path) + common_billing_account_path = staticmethod(ShippingSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ShippingSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ShippingSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ShippingSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ShippingSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ShippingSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ShippingSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(ShippingSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(ShippingSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(ShippingSettingsServiceClient.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: + ShippingSettingsServiceAsyncClient: The constructed client. + """ + return ShippingSettingsServiceClient.from_service_account_info.__func__(ShippingSettingsServiceAsyncClient, 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: + ShippingSettingsServiceAsyncClient: The constructed client. + """ + return ShippingSettingsServiceClient.from_service_account_file.__func__(ShippingSettingsServiceAsyncClient, 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 ShippingSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ShippingSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ShippingSettingsServiceTransport: 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 = ShippingSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the shipping settings 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,ShippingSettingsServiceTransport,Callable[..., ShippingSettingsServiceTransport]]]): + 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 ShippingSettingsServiceTransport 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 = ShippingSettingsServiceClient( + 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.accounts_v1.ShippingSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "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.accounts.v1.ShippingSettingsService", + "credentialsType": None, + } + ) + + async def get_shipping_settings(self, + request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Retrieve shipping setting information. + + .. 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_accounts_v1 + + async def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetShippingSettingsRequest, dict]]): + The request object. Request message for the ``GetShippingSetting`` method. + name (:class:`str`): + Required. The name of the shipping setting to retrieve. + Format: ``accounts/{account}/shippingsettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.ShippingSettings: + The Merchant Center account's [shipping + settings](\ https://support.google.com/merchants/answer/6069284). + The ShippingSettings resource lets you retrieve and + update the shipping settings of your advanced account + and all its associated sub-accounts. + + """ + # 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, shippingsettings.GetShippingSettingsRequest): + request = shippingsettings.GetShippingSettingsRequest(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.get_shipping_settings] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_shipping_settings(self, + request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Replace the shipping setting of a business with the + request shipping setting. Executing this method requires + admin access. + + .. 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_accounts_v1 + + async def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = await client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.InsertShippingSettingsRequest, dict]]): + The request object. Request message for the ``InsertShippingSetting`` + 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_accounts_v1.types.ShippingSettings: + The Merchant Center account's [shipping + settings](\ https://support.google.com/merchants/answer/6069284). + The ShippingSettings resource lets you retrieve and + update the shipping settings of your advanced account + and all its associated sub-accounts. + + """ + # 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, shippingsettings.InsertShippingSettingsRequest): + request = shippingsettings.InsertShippingSettingsRequest(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_shipping_settings] + + # 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 __aenter__(self) -> "ShippingSettingsServiceAsyncClient": + 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__ = ( + "ShippingSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py new file mode 100644 index 000000000000..c83008848825 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py @@ -0,0 +1,838 @@ +# -*- 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_accounts_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_accounts_v1.types import shippingsettings +from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ShippingSettingsServiceGrpcTransport +from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport +from .transports.rest import ShippingSettingsServiceRestTransport + + +class ShippingSettingsServiceClientMeta(type): + """Metaclass for the ShippingSettingsService 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[ShippingSettingsServiceTransport]] + _transport_registry["grpc"] = ShippingSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ShippingSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ShippingSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ShippingSettingsServiceTransport]: + """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 ShippingSettingsServiceClient(metaclass=ShippingSettingsServiceClientMeta): + """Service to get method call shipping setting information per + Merchant API method. + """ + + @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: + ShippingSettingsServiceClient: 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: + ShippingSettingsServiceClient: 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) -> ShippingSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ShippingSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def shipping_settings_path(account: str,) -> str: + """Returns a fully-qualified shipping_settings string.""" + return "accounts/{account}/shippingSettings".format(account=account, ) + + @staticmethod + def parse_shipping_settings_path(path: str) -> Dict[str,str]: + """Parses a shipping_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/shippingSettings$", 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 = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient._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, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the shipping settings 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,ShippingSettingsServiceTransport,Callable[..., ShippingSettingsServiceTransport]]]): + 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 ShippingSettingsServiceTransport 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 = ShippingSettingsServiceClient._read_environment_variables() + self._client_cert_source = ShippingSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ShippingSettingsServiceClient._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, ShippingSettingsServiceTransport) + if transport_provided: + # transport is a ShippingSettingsServiceTransport 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(ShippingSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ShippingSettingsServiceClient._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[ShippingSettingsServiceTransport], Callable[..., ShippingSettingsServiceTransport]] = ( + ShippingSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ShippingSettingsServiceTransport], 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.accounts_v1.ShippingSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "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.accounts.v1.ShippingSettingsService", + "credentialsType": None, + } + ) + + def get_shipping_settings(self, + request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Retrieve shipping setting information. + + .. 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_accounts_v1 + + def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetShippingSettingsRequest, dict]): + The request object. Request message for the ``GetShippingSetting`` method. + name (str): + Required. The name of the shipping setting to retrieve. + Format: ``accounts/{account}/shippingsettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.ShippingSettings: + The Merchant Center account's [shipping + settings](\ https://support.google.com/merchants/answer/6069284). + The ShippingSettings resource lets you retrieve and + update the shipping settings of your advanced account + and all its associated sub-accounts. + + """ + # 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, shippingsettings.GetShippingSettingsRequest): + request = shippingsettings.GetShippingSettingsRequest(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.get_shipping_settings] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_shipping_settings(self, + request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Replace the shipping setting of a business with the + request shipping setting. Executing this method requires + admin access. + + .. 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_accounts_v1 + + def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.InsertShippingSettingsRequest, dict]): + The request object. Request message for the ``InsertShippingSetting`` + 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_accounts_v1.types.ShippingSettings: + The Merchant Center account's [shipping + settings](\ https://support.google.com/merchants/answer/6069284). + The ShippingSettings resource lets you retrieve and + update the shipping settings of your advanced account + and all its associated sub-accounts. + + """ + # 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, shippingsettings.InsertShippingSettingsRequest): + request = shippingsettings.InsertShippingSettingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_shipping_settings] + + # 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 __enter__(self) -> "ShippingSettingsServiceClient": + 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__ = ( + "ShippingSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst new file mode 100644 index 000000000000..a638b7b9035f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ShippingSettingsServiceTransport` is the ABC for all transports. +- public child `ShippingSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ShippingSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseShippingSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ShippingSettingsServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py new file mode 100644 index 000000000000..cbb84e1b0a91 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_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 ShippingSettingsServiceTransport +from .grpc import ShippingSettingsServiceGrpcTransport +from .grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport +from .rest import ShippingSettingsServiceRestTransport +from .rest import ShippingSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ShippingSettingsServiceTransport]] +_transport_registry['grpc'] = ShippingSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ShippingSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ShippingSettingsServiceRestTransport + +__all__ = ( + 'ShippingSettingsServiceTransport', + 'ShippingSettingsServiceGrpcTransport', + 'ShippingSettingsServiceGrpcAsyncIOTransport', + 'ShippingSettingsServiceRestTransport', + 'ShippingSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py new file mode 100644 index 000000000000..960e9328bda1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import shippingsettings + +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 ShippingSettingsServiceTransport(abc.ABC): + """Abstract transport class for ShippingSettingsService.""" + + 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.get_shipping_settings: gapic_v1.method.wrap_method( + self.get_shipping_settings, + default_timeout=None, + client_info=client_info, + ), + self.insert_shipping_settings: gapic_v1.method.wrap_method( + self.insert_shipping_settings, + 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 get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + Union[ + shippingsettings.ShippingSettings, + Awaitable[shippingsettings.ShippingSettings] + ]]: + raise NotImplementedError() + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + Union[ + shippingsettings.ShippingSettings, + Awaitable[shippingsettings.ShippingSettings] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ShippingSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py new file mode 100644 index 000000000000..477d03cf4f7f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py @@ -0,0 +1,375 @@ +# -*- 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.shopping.merchant_accounts_v1.types import shippingsettings +from .base import ShippingSettingsServiceTransport, 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.accounts.v1.ShippingSettingsService", + "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.accounts.v1.ShippingSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ShippingSettingsServiceGrpcTransport(ShippingSettingsServiceTransport): + """gRPC backend transport for ShippingSettingsService. + + Service to get method call shipping setting information per + Merchant API method. + + 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 get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + shippingsettings.ShippingSettings]: + r"""Return a callable for the get shipping settings method over gRPC. + + Retrieve shipping setting information. + + Returns: + Callable[[~.GetShippingSettingsRequest], + ~.ShippingSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_shipping_settings' not in self._stubs: + self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ShippingSettingsService/GetShippingSettings', + request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['get_shipping_settings'] + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + shippingsettings.ShippingSettings]: + r"""Return a callable for the insert shipping settings method over gRPC. + + Replace the shipping setting of a business with the + request shipping setting. Executing this method requires + admin access. + + Returns: + Callable[[~.InsertShippingSettingsRequest], + ~.ShippingSettings]: + 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_shipping_settings' not in self._stubs: + self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ShippingSettingsService/InsertShippingSettings', + request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['insert_shipping_settings'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ShippingSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..275ed2b5daa2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,401 @@ +# -*- 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.shopping.merchant_accounts_v1.types import shippingsettings +from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ShippingSettingsServiceGrpcTransport + +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.accounts.v1.ShippingSettingsService", + "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.accounts.v1.ShippingSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ShippingSettingsServiceGrpcAsyncIOTransport(ShippingSettingsServiceTransport): + """gRPC AsyncIO backend transport for ShippingSettingsService. + + Service to get method call shipping setting information per + Merchant API method. + + 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 get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + Awaitable[shippingsettings.ShippingSettings]]: + r"""Return a callable for the get shipping settings method over gRPC. + + Retrieve shipping setting information. + + Returns: + Callable[[~.GetShippingSettingsRequest], + Awaitable[~.ShippingSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_shipping_settings' not in self._stubs: + self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ShippingSettingsService/GetShippingSettings', + request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['get_shipping_settings'] + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + Awaitable[shippingsettings.ShippingSettings]]: + r"""Return a callable for the insert shipping settings method over gRPC. + + Replace the shipping setting of a business with the + request shipping setting. Executing this method requires + admin access. + + Returns: + Callable[[~.InsertShippingSettingsRequest], + Awaitable[~.ShippingSettings]]: + 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_shipping_settings' not in self._stubs: + self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.ShippingSettingsService/InsertShippingSettings', + request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['insert_shipping_settings'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_shipping_settings: self._wrap_method( + self.get_shipping_settings, + default_timeout=None, + client_info=client_info, + ), + self.insert_shipping_settings: self._wrap_method( + self.insert_shipping_settings, + 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__ = ( + 'ShippingSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py new file mode 100644 index 000000000000..cbade75bcb65 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py @@ -0,0 +1,537 @@ +# -*- 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.shopping.merchant_accounts_v1.types import shippingsettings + + +from .rest_base import _BaseShippingSettingsServiceRestTransport +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 ShippingSettingsServiceRestInterceptor: + """Interceptor for ShippingSettingsService. + + 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 ShippingSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomShippingSettingsServiceInterceptor(ShippingSettingsServiceRestInterceptor): + def pre_get_shipping_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_shipping_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert_shipping_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_shipping_settings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ShippingSettingsServiceRestTransport(interceptor=MyCustomShippingSettingsServiceInterceptor()) + client = ShippingSettingsServiceClient(transport=transport) + + + """ + def pre_get_shipping_settings(self, request: shippingsettings.GetShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_shipping_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the ShippingSettingsService server. + """ + return request, metadata + + def post_get_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: + """Post-rpc interceptor for get_shipping_settings + + DEPRECATED. Please use the `post_get_shipping_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ShippingSettingsService server but before + it is returned to user code. This `post_get_shipping_settings` interceptor runs + before the `post_get_shipping_settings_with_metadata` interceptor. + """ + return response + + def post_get_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_shipping_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ShippingSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_shipping_settings_with_metadata` + interceptor in new development instead of the `post_get_shipping_settings` interceptor. + When both interceptors are used, this `post_get_shipping_settings_with_metadata` interceptor runs after the + `post_get_shipping_settings` interceptor. The (possibly modified) response returned by + `post_get_shipping_settings` will be passed to + `post_get_shipping_settings_with_metadata`. + """ + return response, metadata + + def pre_insert_shipping_settings(self, request: shippingsettings.InsertShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_shipping_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the ShippingSettingsService server. + """ + return request, metadata + + def post_insert_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: + """Post-rpc interceptor for insert_shipping_settings + + DEPRECATED. Please use the `post_insert_shipping_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ShippingSettingsService server but before + it is returned to user code. This `post_insert_shipping_settings` interceptor runs + before the `post_insert_shipping_settings_with_metadata` interceptor. + """ + return response + + def post_insert_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert_shipping_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ShippingSettingsService server but before it is returned to user code. + + We recommend only using this `post_insert_shipping_settings_with_metadata` + interceptor in new development instead of the `post_insert_shipping_settings` interceptor. + When both interceptors are used, this `post_insert_shipping_settings_with_metadata` interceptor runs after the + `post_insert_shipping_settings` interceptor. The (possibly modified) response returned by + `post_insert_shipping_settings` will be passed to + `post_insert_shipping_settings_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ShippingSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ShippingSettingsServiceRestInterceptor + + +class ShippingSettingsServiceRestTransport(_BaseShippingSettingsServiceRestTransport): + """REST backend synchronous transport for ShippingSettingsService. + + Service to get method call shipping setting information per + Merchant API method. + + 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[ShippingSettingsServiceRestInterceptor] = 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 ShippingSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings, ShippingSettingsServiceRestStub): + def __hash__(self): + return hash("ShippingSettingsServiceRestTransport.GetShippingSettings") + + @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: shippingsettings.GetShippingSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> shippingsettings.ShippingSettings: + r"""Call the get shipping settings method over HTTP. + + Args: + request (~.shippingsettings.GetShippingSettingsRequest): + The request object. Request message for the ``GetShippingSetting`` 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: + ~.shippingsettings.ShippingSettings: + The Merchant Center account's `shipping + settings `__. + The ``ShippingSettings`` resource lets you retrieve and + update the shipping settings of your advanced account + and all its associated sub-accounts. + + """ + + http_options = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_http_options() + + request, metadata = self._interceptor.pre_get_shipping_settings(request, metadata) + transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ShippingSettingsServiceClient.GetShippingSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "rpcName": "GetShippingSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ShippingSettingsServiceRestTransport._GetShippingSettings._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 = shippingsettings.ShippingSettings() + pb_resp = shippingsettings.ShippingSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_shipping_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_shipping_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = shippingsettings.ShippingSettings.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.accounts_v1.ShippingSettingsServiceClient.get_shipping_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "rpcName": "GetShippingSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InsertShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings, ShippingSettingsServiceRestStub): + def __hash__(self): + return hash("ShippingSettingsServiceRestTransport.InsertShippingSettings") + + @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: shippingsettings.InsertShippingSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> shippingsettings.ShippingSettings: + r"""Call the insert shipping settings method over HTTP. + + Args: + request (~.shippingsettings.InsertShippingSettingsRequest): + The request object. Request message for the ``InsertShippingSetting`` + 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: + ~.shippingsettings.ShippingSettings: + The Merchant Center account's `shipping + settings `__. + The ``ShippingSettings`` resource lets you retrieve and + update the shipping settings of your advanced account + and all its associated sub-accounts. + + """ + + http_options = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_http_options() + + request, metadata = self._interceptor.pre_insert_shipping_settings(request, metadata) + transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_transcoded_request(http_options, request) + + body = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ShippingSettingsServiceClient.InsertShippingSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "rpcName": "InsertShippingSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ShippingSettingsServiceRestTransport._InsertShippingSettings._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 = shippingsettings.ShippingSettings() + pb_resp = shippingsettings.ShippingSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_shipping_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_shipping_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = shippingsettings.ShippingSettings.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.accounts_v1.ShippingSettingsServiceClient.insert_shipping_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "rpcName": "InsertShippingSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + shippingsettings.ShippingSettings]: + # 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._GetShippingSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + shippingsettings.ShippingSettings]: + # 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._InsertShippingSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ShippingSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..8d95b4704766 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import shippingsettings + + +class _BaseShippingSettingsServiceRestTransport(ShippingSettingsServiceTransport): + """Base REST backend transport for ShippingSettingsService. + + 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 _BaseGetShippingSettings: + 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': '/accounts/v1/{name=accounts/*/shippingSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = shippingsettings.GetShippingSettingsRequest.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(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertShippingSettings: + 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': '/accounts/v1/{parent=accounts/*}/shippingSettings:insert', + 'body': 'shipping_setting', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = shippingsettings.InsertShippingSettingsRequest.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(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseShippingSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py new file mode 100644 index 000000000000..c0461009811b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_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 TermsOfServiceAgreementStateServiceClient +from .async_client import TermsOfServiceAgreementStateServiceAsyncClient + +__all__ = ( + 'TermsOfServiceAgreementStateServiceClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py new file mode 100644 index 000000000000..75f8a39efc66 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py @@ -0,0 +1,537 @@ +# -*- 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_accounts_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_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind +from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .client import TermsOfServiceAgreementStateServiceClient + +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 TermsOfServiceAgreementStateServiceAsyncClient: + """Service to support ``TermsOfServiceAgreementState`` API.""" + + _client: TermsOfServiceAgreementStateServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.account_path) + parse_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_account_path) + terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_path) + parse_terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path) + terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path) + parse_terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path) + common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_organization_path) + common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_project_path) + parse_common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_project_path) + common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_location_path) + parse_common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.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: + TermsOfServiceAgreementStateServiceAsyncClient: The constructed client. + """ + return TermsOfServiceAgreementStateServiceClient.from_service_account_info.__func__(TermsOfServiceAgreementStateServiceAsyncClient, 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: + TermsOfServiceAgreementStateServiceAsyncClient: The constructed client. + """ + return TermsOfServiceAgreementStateServiceClient.from_service_account_file.__func__(TermsOfServiceAgreementStateServiceAsyncClient, 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 TermsOfServiceAgreementStateServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TermsOfServiceAgreementStateServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceAgreementStateServiceTransport: 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 = TermsOfServiceAgreementStateServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service agreement state 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,TermsOfServiceAgreementStateServiceTransport,Callable[..., TermsOfServiceAgreementStateServiceTransport]]]): + 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 TermsOfServiceAgreementStateServiceTransport 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 = TermsOfServiceAgreementStateServiceClient( + 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.accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "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.accounts.v1.TermsOfServiceAgreementStateService", + "credentialsType": None, + } + ) + + async def get_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Returns the state of a terms of service agreement. + + .. 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_accounts_v1 + + async def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetTermsOfServiceAgreementStateRequest, dict]]): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` method. + name (:class:`str`): + Required. The resource name of the terms of service + version. Format: + ``accounts/{account}/termsOfServiceAgreementStates/{identifier}`` + The identifier format is: + ``{TermsOfServiceKind}-{country}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the business has accepted a terms of service, + [accepted][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty \* If + the business must sign a terms of service, + [required][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both required and accepted can be present. + In this case the accepted terms of services will have + an expiration date set in the + [valid_until][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The required terms of services need to be + accepted before valid_until in order for the account + to continue having a valid agreement. When accepting + new terms of services we expect third-party providers + to display the text associated with the given terms + of service agreement (the url to the file containing + the text is added in the Required message below as + [tos_file_uri][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done + by calling accept on the + [TermsOfService][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. valid_until field. + + """ + # 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, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(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.get_terms_of_service_agreement_state] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retrieve_for_application_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Retrieves the state of the agreement for the + application terms of service. + Application terms of service covers permissions related + to the usage of data provided through Merchant Center, + CSS Center, Manufacturer Center, and more. + + .. 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_accounts_v1 + + async def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest, dict]]): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + method. + parent (:class:`str`): + Required. The account for which to get a + TermsOfServiceAgreementState Format: + ``accounts/{account}`` + + 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_accounts_v1.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the business has accepted a terms of service, + [accepted][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty \* If + the business must sign a terms of service, + [required][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both required and accepted can be present. + In this case the accepted terms of services will have + an expiration date set in the + [valid_until][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The required terms of services need to be + accepted before valid_until in order for the account + to continue having a valid agreement. When accepting + new terms of services we expect third-party providers + to display the text associated with the given terms + of service agreement (the url to the file containing + the text is added in the Required message below as + [tos_file_uri][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done + by calling accept on the + [TermsOfService][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. valid_until field. + + """ + # 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, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(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.retrieve_for_application_terms_of_service_agreement_state] + + # 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 __aenter__(self) -> "TermsOfServiceAgreementStateServiceAsyncClient": + 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__ = ( + "TermsOfServiceAgreementStateServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py new file mode 100644 index 000000000000..99e175d5b10a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py @@ -0,0 +1,914 @@ +# -*- 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_accounts_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_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind +from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TermsOfServiceAgreementStateServiceGrpcTransport +from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .transports.rest import TermsOfServiceAgreementStateServiceRestTransport + + +class TermsOfServiceAgreementStateServiceClientMeta(type): + """Metaclass for the TermsOfServiceAgreementStateService 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[TermsOfServiceAgreementStateServiceTransport]] + _transport_registry["grpc"] = TermsOfServiceAgreementStateServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TermsOfServiceAgreementStateServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TermsOfServiceAgreementStateServiceTransport]: + """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 TermsOfServiceAgreementStateServiceClient(metaclass=TermsOfServiceAgreementStateServiceClientMeta): + """Service to support ``TermsOfServiceAgreementState`` API.""" + + @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: + TermsOfServiceAgreementStateServiceClient: 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: + TermsOfServiceAgreementStateServiceClient: 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) -> TermsOfServiceAgreementStateServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceAgreementStateServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_path(version: str,) -> str: + """Returns a fully-qualified terms_of_service string.""" + return "termsOfService/{version}".format(version=version, ) + + @staticmethod + def parse_terms_of_service_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service path into its component segments.""" + m = re.match(r"^termsOfService/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_agreement_state_path(account: str,identifier: str,) -> str: + """Returns a fully-qualified terms_of_service_agreement_state string.""" + return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + + @staticmethod + def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service_agreement_state path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?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 = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TermsOfServiceAgreementStateServiceClient._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 = TermsOfServiceAgreementStateServiceClient._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, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service agreement state 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,TermsOfServiceAgreementStateServiceTransport,Callable[..., TermsOfServiceAgreementStateServiceTransport]]]): + 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 TermsOfServiceAgreementStateServiceTransport 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 = TermsOfServiceAgreementStateServiceClient._read_environment_variables() + self._client_cert_source = TermsOfServiceAgreementStateServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = TermsOfServiceAgreementStateServiceClient._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, TermsOfServiceAgreementStateServiceTransport) + if transport_provided: + # transport is a TermsOfServiceAgreementStateServiceTransport 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(TermsOfServiceAgreementStateServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + TermsOfServiceAgreementStateServiceClient._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[TermsOfServiceAgreementStateServiceTransport], Callable[..., TermsOfServiceAgreementStateServiceTransport]] = ( + TermsOfServiceAgreementStateServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TermsOfServiceAgreementStateServiceTransport], 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.accounts_v1.TermsOfServiceAgreementStateServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "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.accounts.v1.TermsOfServiceAgreementStateService", + "credentialsType": None, + } + ) + + def get_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Returns the state of a terms of service agreement. + + .. 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_accounts_v1 + + def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetTermsOfServiceAgreementStateRequest, dict]): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` method. + name (str): + Required. The resource name of the terms of service + version. Format: + ``accounts/{account}/termsOfServiceAgreementStates/{identifier}`` + The identifier format is: + ``{TermsOfServiceKind}-{country}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the business has accepted a terms of service, + [accepted][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty \* If + the business must sign a terms of service, + [required][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both required and accepted can be present. + In this case the accepted terms of services will have + an expiration date set in the + [valid_until][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The required terms of services need to be + accepted before valid_until in order for the account + to continue having a valid agreement. When accepting + new terms of services we expect third-party providers + to display the text associated with the given terms + of service agreement (the url to the file containing + the text is added in the Required message below as + [tos_file_uri][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done + by calling accept on the + [TermsOfService][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. valid_until field. + + """ + # 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, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(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.get_terms_of_service_agreement_state] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retrieve_for_application_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Retrieves the state of the agreement for the + application terms of service. + Application terms of service covers permissions related + to the usage of data provided through Merchant Center, + CSS Center, Manufacturer Center, and more. + + .. 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_accounts_v1 + + def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest, dict]): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + method. + parent (str): + Required. The account for which to get a + TermsOfServiceAgreementState Format: + ``accounts/{account}`` + + 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_accounts_v1.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the business has accepted a terms of service, + [accepted][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty \* If + the business must sign a terms of service, + [required][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both required and accepted can be present. + In this case the accepted terms of services will have + an expiration date set in the + [valid_until][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The required terms of services need to be + accepted before valid_until in order for the account + to continue having a valid agreement. When accepting + new terms of services we expect third-party providers + to display the text associated with the given terms + of service agreement (the url to the file containing + the text is added in the Required message below as + [tos_file_uri][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done + by calling accept on the + [TermsOfService][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. valid_until field. + + """ + # 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, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(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.retrieve_for_application_terms_of_service_agreement_state] + + # 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 __enter__(self) -> "TermsOfServiceAgreementStateServiceClient": + 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__ = ( + "TermsOfServiceAgreementStateServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst new file mode 100644 index 000000000000..344858fa2eb5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TermsOfServiceAgreementStateServiceTransport` is the ABC for all transports. +- public child `TermsOfServiceAgreementStateServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTermsOfServiceAgreementStateServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TermsOfServiceAgreementStateServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py new file mode 100644 index 000000000000..3e5e8db05323 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_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 TermsOfServiceAgreementStateServiceTransport +from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport +from .grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .rest import TermsOfServiceAgreementStateServiceRestTransport +from .rest import TermsOfServiceAgreementStateServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] +_transport_registry['grpc'] = TermsOfServiceAgreementStateServiceGrpcTransport +_transport_registry['grpc_asyncio'] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +_transport_registry['rest'] = TermsOfServiceAgreementStateServiceRestTransport + +__all__ = ( + 'TermsOfServiceAgreementStateServiceTransport', + 'TermsOfServiceAgreementStateServiceGrpcTransport', + 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', + 'TermsOfServiceAgreementStateServiceRestTransport', + 'TermsOfServiceAgreementStateServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py new file mode 100644 index 000000000000..f66f5f861dee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import termsofserviceagreementstate + +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 TermsOfServiceAgreementStateServiceTransport(abc.ABC): + """Abstract transport class for TermsOfServiceAgreementStateService.""" + + 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.get_terms_of_service_agreement_state: gapic_v1.method.wrap_method( + self.get_terms_of_service_agreement_state, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_for_application_terms_of_service_agreement_state: gapic_v1.method.wrap_method( + self.retrieve_for_application_terms_of_service_agreement_state, + 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 get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + Union[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] + ]]: + raise NotImplementedError() + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + Union[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TermsOfServiceAgreementStateServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py new file mode 100644 index 000000000000..618bffa5e5a4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py @@ -0,0 +1,378 @@ +# -*- 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.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from .base import TermsOfServiceAgreementStateServiceTransport, 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.accounts.v1.TermsOfServiceAgreementStateService", + "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.accounts.v1.TermsOfServiceAgreementStateService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceAgreementStateServiceGrpcTransport(TermsOfServiceAgreementStateServiceTransport): + """gRPC backend transport for TermsOfServiceAgreementStateService. + + Service to support ``TermsOfServiceAgreementState`` API. + + 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 get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + r"""Return a callable for the get terms of service agreement + state method over gRPC. + + Returns the state of a terms of service agreement. + + Returns: + Callable[[~.GetTermsOfServiceAgreementStateRequest], + ~.TermsOfServiceAgreementState]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service_agreement_state' not in self._stubs: + self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['get_terms_of_service_agreement_state'] + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + r"""Return a callable for the retrieve for application terms + of service agreement state method over gRPC. + + Retrieves the state of the agreement for the + application terms of service. + Application terms of service covers permissions related + to the usage of data provided through Merchant Center, + CSS Center, Manufacturer Center, and more. + + Returns: + Callable[[~.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + ~.TermsOfServiceAgreementState]: + 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 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: + self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TermsOfServiceAgreementStateServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..dc0729d255d6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py @@ -0,0 +1,404 @@ +# -*- 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.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport + +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.accounts.v1.TermsOfServiceAgreementStateService", + "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.accounts.v1.TermsOfServiceAgreementStateService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport(TermsOfServiceAgreementStateServiceTransport): + """gRPC AsyncIO backend transport for TermsOfServiceAgreementStateService. + + Service to support ``TermsOfServiceAgreementState`` API. + + 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 get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: + r"""Return a callable for the get terms of service agreement + state method over gRPC. + + Returns the state of a terms of service agreement. + + Returns: + Callable[[~.GetTermsOfServiceAgreementStateRequest], + Awaitable[~.TermsOfServiceAgreementState]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service_agreement_state' not in self._stubs: + self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['get_terms_of_service_agreement_state'] + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: + r"""Return a callable for the retrieve for application terms + of service agreement state method over gRPC. + + Retrieves the state of the agreement for the + application terms of service. + Application terms of service covers permissions related + to the usage of data provided through Merchant Center, + CSS Center, Manufacturer Center, and more. + + Returns: + Callable[[~.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + Awaitable[~.TermsOfServiceAgreementState]]: + 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 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: + self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_terms_of_service_agreement_state: self._wrap_method( + self.get_terms_of_service_agreement_state, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_for_application_terms_of_service_agreement_state: self._wrap_method( + self.retrieve_for_application_terms_of_service_agreement_state, + 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__ = ( + 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py new file mode 100644 index 000000000000..e73fb463590d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py @@ -0,0 +1,581 @@ +# -*- 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.shopping.merchant_accounts_v1.types import termsofserviceagreementstate + + +from .rest_base import _BaseTermsOfServiceAgreementStateServiceRestTransport +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 TermsOfServiceAgreementStateServiceRestInterceptor: + """Interceptor for TermsOfServiceAgreementStateService. + + 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 TermsOfServiceAgreementStateServiceRestTransport. + + .. code-block:: python + class MyCustomTermsOfServiceAgreementStateServiceInterceptor(TermsOfServiceAgreementStateServiceRestInterceptor): + def pre_get_terms_of_service_agreement_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_terms_of_service_agreement_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_for_application_terms_of_service_agreement_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_for_application_terms_of_service_agreement_state(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TermsOfServiceAgreementStateServiceRestTransport(interceptor=MyCustomTermsOfServiceAgreementStateServiceInterceptor()) + client = TermsOfServiceAgreementStateServiceClient(transport=transport) + + + """ + def pre_get_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_terms_of_service_agreement_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceAgreementStateService server. + """ + return request, metadata + + def post_get_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + """Post-rpc interceptor for get_terms_of_service_agreement_state + + DEPRECATED. Please use the `post_get_terms_of_service_agreement_state_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceAgreementStateService server but before + it is returned to user code. This `post_get_terms_of_service_agreement_state` interceptor runs + before the `post_get_terms_of_service_agreement_state_with_metadata` interceptor. + """ + return response + + def post_get_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_terms_of_service_agreement_state + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceAgreementStateService server but before it is returned to user code. + + We recommend only using this `post_get_terms_of_service_agreement_state_with_metadata` + interceptor in new development instead of the `post_get_terms_of_service_agreement_state` interceptor. + When both interceptors are used, this `post_get_terms_of_service_agreement_state_with_metadata` interceptor runs after the + `post_get_terms_of_service_agreement_state` interceptor. The (possibly modified) response returned by + `post_get_terms_of_service_agreement_state` will be passed to + `post_get_terms_of_service_agreement_state_with_metadata`. + """ + return response, metadata + + def pre_retrieve_for_application_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceAgreementStateService server. + """ + return request, metadata + + def post_retrieve_for_application_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state + + DEPRECATED. Please use the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceAgreementStateService server but before + it is returned to user code. This `post_retrieve_for_application_terms_of_service_agreement_state` interceptor runs + before the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` interceptor. + """ + return response + + def post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceAgreementStateService server but before it is returned to user code. + + We recommend only using this `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` + interceptor in new development instead of the `post_retrieve_for_application_terms_of_service_agreement_state` interceptor. + When both interceptors are used, this `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` interceptor runs after the + `post_retrieve_for_application_terms_of_service_agreement_state` interceptor. The (possibly modified) response returned by + `post_retrieve_for_application_terms_of_service_agreement_state` will be passed to + `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class TermsOfServiceAgreementStateServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TermsOfServiceAgreementStateServiceRestInterceptor + + +class TermsOfServiceAgreementStateServiceRestTransport(_BaseTermsOfServiceAgreementStateServiceRestTransport): + """REST backend synchronous transport for TermsOfServiceAgreementStateService. + + Service to support ``TermsOfServiceAgreementState`` API. + + 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[TermsOfServiceAgreementStateServiceRestInterceptor] = 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 TermsOfServiceAgreementStateServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceAgreementStateServiceRestTransport.GetTermsOfServiceAgreementState") + + @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: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Call the get terms of service + agreement state method over HTTP. + + Args: + request (~.termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` 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: + ~.termsofserviceagreementstate.TermsOfServiceAgreementState: + This resource represents the agreement state for a given + account and terms of service kind. The state is as + follows: + + - If the business has accepted a terms of service, + [``accepted``][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty + - If the business must sign a terms of service, + [``required``][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both ``required`` and ``accepted`` can be + present. In this case the ``accepted`` terms of services + will have an expiration date set in the + [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The ``required`` terms of services need to be + accepted before ``valid_until`` in order for the account + to continue having a valid agreement. When accepting new + terms of services we expect third-party providers to + display the text associated with the given terms of + service agreement (the url to the file containing the + text is added in the Required message below as + [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done by + calling accept on the + [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. ``valid_until`` field. + + """ + + http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_http_options() + + request, metadata = self._interceptor.pre_get_terms_of_service_agreement_state(request, metadata) + transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceAgreementStateServiceClient.GetTermsOfServiceAgreementState", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "rpcName": "GetTermsOfServiceAgreementState", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceAgreementStateServiceRestTransport._GetTermsOfServiceAgreementState._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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + pb_resp = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_terms_of_service_agreement_state(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_terms_of_service_agreement_state_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "rpcName": "GetTermsOfServiceAgreementState", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RetrieveForApplicationTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceAgreementStateServiceRestTransport.RetrieveForApplicationTermsOfServiceAgreementState") + + @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: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Call the retrieve for application + terms of service agreement state method over HTTP. + + Args: + request (~.termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + 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: + ~.termsofserviceagreementstate.TermsOfServiceAgreementState: + This resource represents the agreement state for a given + account and terms of service kind. The state is as + follows: + + - If the business has accepted a terms of service, + [``accepted``][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty + - If the business must sign a terms of service, + [``required``][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both ``required`` and ``accepted`` can be + present. In this case the ``accepted`` terms of services + will have an expiration date set in the + [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The ``required`` terms of services need to be + accepted before ``valid_until`` in order for the account + to continue having a valid agreement. When accepting new + terms of services we expect third-party providers to + display the text associated with the given terms of + service agreement (the url to the file containing the + text is added in the Required message below as + [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done by + calling accept on the + [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. ``valid_until`` field. + + """ + + http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_http_options() + + request, metadata = self._interceptor.pre_retrieve_for_application_terms_of_service_agreement_state(request, metadata) + transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceAgreementStateServiceClient.RetrieveForApplicationTermsOfServiceAgreementState", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceAgreementStateServiceRestTransport._RetrieveForApplicationTermsOfServiceAgreementState._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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + pb_resp = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + # 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._GetTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + # 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._RetrieveForApplicationTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TermsOfServiceAgreementStateServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py new file mode 100644 index 000000000000..b891b391c48e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py @@ -0,0 +1,165 @@ +# -*- 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 TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate + + +class _BaseTermsOfServiceAgreementStateServiceRestTransport(TermsOfServiceAgreementStateServiceTransport): + """Base REST backend transport for TermsOfServiceAgreementStateService. + + 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 _BaseGetTermsOfServiceAgreementState: + 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': '/accounts/v1/{name=accounts/*/termsOfServiceAgreementStates/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRetrieveForApplicationTermsOfServiceAgreementState: + 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': '/accounts/v1/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseTermsOfServiceAgreementStateServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py new file mode 100644 index 000000000000..7bfe24f4bb51 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_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 TermsOfServiceServiceClient +from .async_client import TermsOfServiceServiceAsyncClient + +__all__ = ( + 'TermsOfServiceServiceClient', + 'TermsOfServiceServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py new file mode 100644 index 000000000000..db2dae66a680 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py @@ -0,0 +1,580 @@ +# -*- 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_accounts_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_accounts_v1.types import termsofservice +from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind +from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from .client import TermsOfServiceServiceClient + +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 TermsOfServiceServiceAsyncClient: + """Service to support ``TermsOfService`` API.""" + + _client: TermsOfServiceServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TermsOfServiceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(TermsOfServiceServiceClient.account_path) + parse_account_path = staticmethod(TermsOfServiceServiceClient.parse_account_path) + terms_of_service_path = staticmethod(TermsOfServiceServiceClient.terms_of_service_path) + parse_terms_of_service_path = staticmethod(TermsOfServiceServiceClient.parse_terms_of_service_path) + terms_of_service_agreement_state_path = staticmethod(TermsOfServiceServiceClient.terms_of_service_agreement_state_path) + parse_terms_of_service_agreement_state_path = staticmethod(TermsOfServiceServiceClient.parse_terms_of_service_agreement_state_path) + common_billing_account_path = staticmethod(TermsOfServiceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TermsOfServiceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TermsOfServiceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TermsOfServiceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TermsOfServiceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(TermsOfServiceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(TermsOfServiceServiceClient.common_project_path) + parse_common_project_path = staticmethod(TermsOfServiceServiceClient.parse_common_project_path) + common_location_path = staticmethod(TermsOfServiceServiceClient.common_location_path) + parse_common_location_path = staticmethod(TermsOfServiceServiceClient.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: + TermsOfServiceServiceAsyncClient: The constructed client. + """ + return TermsOfServiceServiceClient.from_service_account_info.__func__(TermsOfServiceServiceAsyncClient, 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: + TermsOfServiceServiceAsyncClient: The constructed client. + """ + return TermsOfServiceServiceClient.from_service_account_file.__func__(TermsOfServiceServiceAsyncClient, 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 TermsOfServiceServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TermsOfServiceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceServiceTransport: 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 = TermsOfServiceServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service 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,TermsOfServiceServiceTransport,Callable[..., TermsOfServiceServiceTransport]]]): + 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 TermsOfServiceServiceTransport 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 = TermsOfServiceServiceClient( + 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.accounts_v1.TermsOfServiceServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "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.accounts.v1.TermsOfServiceService", + "credentialsType": None, + } + ) + + async def get_terms_of_service(self, + request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the ``TermsOfService`` associated with the provided + version. + + .. 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_accounts_v1 + + async def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetTermsOfServiceRequest, dict]]): + The request object. Request message for the ``GetTermsOfService`` method. + name (:class:`str`): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.TermsOfService: + The TermsOfService message represents a specific version of the terms of + service that merchants must accept to access certain + features or services. For more information, see + [Terms of + Service](\ https://support.google.com/merchants/answer/160173). + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can + retrieve the latest terms of service for a given kind + and region through RetrieveLatestTermsOfService, and + accept them as required through AcceptTermsOfService. + + """ + # 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, termsofservice.GetTermsOfServiceRequest): + request = termsofservice.GetTermsOfServiceRequest(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.get_terms_of_service] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retrieve_latest_terms_of_service(self, + request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + .. 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_accounts_v1 + + async def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = await client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.RetrieveLatestTermsOfServiceRequest, dict]]): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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_accounts_v1.types.TermsOfService: + The TermsOfService message represents a specific version of the terms of + service that merchants must accept to access certain + features or services. For more information, see + [Terms of + Service](\ https://support.google.com/merchants/answer/160173). + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can + retrieve the latest terms of service for a given kind + and region through RetrieveLatestTermsOfService, and + accept them as required through AcceptTermsOfService. + + """ + # 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, termsofservice.RetrieveLatestTermsOfServiceRequest): + request = termsofservice.RetrieveLatestTermsOfServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.retrieve_latest_terms_of_service] + + # 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 accept_terms_of_service(self, + request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.AcceptTermsOfServiceResponse: + r"""Accepts a ``TermsOfService``. Executing this method requires + admin access. + + .. 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_accounts_v1 + + async def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + response = await client.accept_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceRequest, dict]]): + The request object. Request message for the ``AcceptTermsOfService`` method. + name (:class:`str`): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceResponse: + Response message for the AcceptTermsOfService method. + """ + # 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, termsofservice.AcceptTermsOfServiceRequest): + request = termsofservice.AcceptTermsOfServiceRequest(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.accept_terms_of_service] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "TermsOfServiceServiceAsyncClient": + 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__ = ( + "TermsOfServiceServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py new file mode 100644 index 000000000000..da21398ba440 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py @@ -0,0 +1,957 @@ +# -*- 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_accounts_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_accounts_v1.types import termsofservice +from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind +from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TermsOfServiceServiceGrpcTransport +from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from .transports.rest import TermsOfServiceServiceRestTransport + + +class TermsOfServiceServiceClientMeta(type): + """Metaclass for the TermsOfServiceService 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[TermsOfServiceServiceTransport]] + _transport_registry["grpc"] = TermsOfServiceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TermsOfServiceServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TermsOfServiceServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TermsOfServiceServiceTransport]: + """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 TermsOfServiceServiceClient(metaclass=TermsOfServiceServiceClientMeta): + """Service to support ``TermsOfService`` API.""" + + @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: + TermsOfServiceServiceClient: 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: + TermsOfServiceServiceClient: 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) -> TermsOfServiceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_path(version: str,) -> str: + """Returns a fully-qualified terms_of_service string.""" + return "termsOfService/{version}".format(version=version, ) + + @staticmethod + def parse_terms_of_service_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service path into its component segments.""" + m = re.match(r"^termsOfService/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_agreement_state_path(account: str,identifier: str,) -> str: + """Returns a fully-qualified terms_of_service_agreement_state string.""" + return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + + @staticmethod + def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service_agreement_state path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?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 = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient._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, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service 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,TermsOfServiceServiceTransport,Callable[..., TermsOfServiceServiceTransport]]]): + 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 TermsOfServiceServiceTransport 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 = TermsOfServiceServiceClient._read_environment_variables() + self._client_cert_source = TermsOfServiceServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = TermsOfServiceServiceClient._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, TermsOfServiceServiceTransport) + if transport_provided: + # transport is a TermsOfServiceServiceTransport 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(TermsOfServiceServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + TermsOfServiceServiceClient._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[TermsOfServiceServiceTransport], Callable[..., TermsOfServiceServiceTransport]] = ( + TermsOfServiceServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TermsOfServiceServiceTransport], 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.accounts_v1.TermsOfServiceServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "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.accounts.v1.TermsOfServiceService", + "credentialsType": None, + } + ) + + def get_terms_of_service(self, + request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the ``TermsOfService`` associated with the provided + version. + + .. 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_accounts_v1 + + def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetTermsOfServiceRequest, dict]): + The request object. Request message for the ``GetTermsOfService`` method. + name (str): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.TermsOfService: + The TermsOfService message represents a specific version of the terms of + service that merchants must accept to access certain + features or services. For more information, see + [Terms of + Service](\ https://support.google.com/merchants/answer/160173). + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can + retrieve the latest terms of service for a given kind + and region through RetrieveLatestTermsOfService, and + accept them as required through AcceptTermsOfService. + + """ + # 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, termsofservice.GetTermsOfServiceRequest): + request = termsofservice.GetTermsOfServiceRequest(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.get_terms_of_service] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retrieve_latest_terms_of_service(self, + request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + .. 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_accounts_v1 + + def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.RetrieveLatestTermsOfServiceRequest, dict]): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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_accounts_v1.types.TermsOfService: + The TermsOfService message represents a specific version of the terms of + service that merchants must accept to access certain + features or services. For more information, see + [Terms of + Service](\ https://support.google.com/merchants/answer/160173). + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can + retrieve the latest terms of service for a given kind + and region through RetrieveLatestTermsOfService, and + accept them as required through AcceptTermsOfService. + + """ + # 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, termsofservice.RetrieveLatestTermsOfServiceRequest): + request = termsofservice.RetrieveLatestTermsOfServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.retrieve_latest_terms_of_service] + + # 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 accept_terms_of_service(self, + request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.AcceptTermsOfServiceResponse: + r"""Accepts a ``TermsOfService``. Executing this method requires + admin access. + + .. 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_accounts_v1 + + def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + response = client.accept_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceRequest, dict]): + The request object. Request message for the ``AcceptTermsOfService`` method. + name (str): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceResponse: + Response message for the AcceptTermsOfService method. + """ + # 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, termsofservice.AcceptTermsOfServiceRequest): + request = termsofservice.AcceptTermsOfServiceRequest(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.accept_terms_of_service] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "TermsOfServiceServiceClient": + 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__ = ( + "TermsOfServiceServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst new file mode 100644 index 000000000000..3a13382bc0d2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TermsOfServiceServiceTransport` is the ABC for all transports. +- public child `TermsOfServiceServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TermsOfServiceServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTermsOfServiceServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TermsOfServiceServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py new file mode 100644 index 000000000000..04c865765be1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_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 TermsOfServiceServiceTransport +from .grpc import TermsOfServiceServiceGrpcTransport +from .grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from .rest import TermsOfServiceServiceRestTransport +from .rest import TermsOfServiceServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceServiceTransport]] +_transport_registry['grpc'] = TermsOfServiceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = TermsOfServiceServiceGrpcAsyncIOTransport +_transport_registry['rest'] = TermsOfServiceServiceRestTransport + +__all__ = ( + 'TermsOfServiceServiceTransport', + 'TermsOfServiceServiceGrpcTransport', + 'TermsOfServiceServiceGrpcAsyncIOTransport', + 'TermsOfServiceServiceRestTransport', + 'TermsOfServiceServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py new file mode 100644 index 000000000000..8b5e81529c75 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py @@ -0,0 +1,187 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1.types import termsofservice + +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 TermsOfServiceServiceTransport(abc.ABC): + """Abstract transport class for TermsOfServiceService.""" + + 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.get_terms_of_service: gapic_v1.method.wrap_method( + self.get_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_latest_terms_of_service: gapic_v1.method.wrap_method( + self.retrieve_latest_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.accept_terms_of_service: gapic_v1.method.wrap_method( + self.accept_terms_of_service, + 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 get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + Union[ + termsofservice.TermsOfService, + Awaitable[termsofservice.TermsOfService] + ]]: + raise NotImplementedError() + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + Union[ + termsofservice.TermsOfService, + Awaitable[termsofservice.TermsOfService] + ]]: + raise NotImplementedError() + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + Union[ + termsofservice.AcceptTermsOfServiceResponse, + Awaitable[termsofservice.AcceptTermsOfServiceResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TermsOfServiceServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py new file mode 100644 index 000000000000..2b35f2ceea6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py @@ -0,0 +1,402 @@ +# -*- 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.shopping.merchant_accounts_v1.types import termsofservice +from .base import TermsOfServiceServiceTransport, 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.accounts.v1.TermsOfServiceService", + "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.accounts.v1.TermsOfServiceService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceServiceGrpcTransport(TermsOfServiceServiceTransport): + """gRPC backend transport for TermsOfServiceService. + + Service to support ``TermsOfService`` API. + + 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 get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + termsofservice.TermsOfService]: + r"""Return a callable for the get terms of service method over gRPC. + + Retrieves the ``TermsOfService`` associated with the provided + version. + + Returns: + Callable[[~.GetTermsOfServiceRequest], + ~.TermsOfService]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service' not in self._stubs: + self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceService/GetTermsOfService', + request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['get_terms_of_service'] + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + termsofservice.TermsOfService]: + r"""Return a callable for the retrieve latest terms of + service method over gRPC. + + Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + Returns: + Callable[[~.RetrieveLatestTermsOfServiceRequest], + ~.TermsOfService]: + 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 'retrieve_latest_terms_of_service' not in self._stubs: + self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceService/RetrieveLatestTermsOfService', + request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['retrieve_latest_terms_of_service'] + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + termsofservice.AcceptTermsOfServiceResponse]: + r"""Return a callable for the accept terms of service method over gRPC. + + Accepts a ``TermsOfService``. Executing this method requires + admin access. + + Returns: + Callable[[~.AcceptTermsOfServiceRequest], + ~.AcceptTermsOfServiceResponse]: + 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 'accept_terms_of_service' not in self._stubs: + self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceService/AcceptTermsOfService', + request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.AcceptTermsOfServiceResponse.deserialize, + ) + return self._stubs['accept_terms_of_service'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TermsOfServiceServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..bae98df8e51e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py @@ -0,0 +1,433 @@ +# -*- 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.shopping.merchant_accounts_v1.types import termsofservice +from .base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TermsOfServiceServiceGrpcTransport + +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.accounts.v1.TermsOfServiceService", + "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.accounts.v1.TermsOfServiceService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceServiceGrpcAsyncIOTransport(TermsOfServiceServiceTransport): + """gRPC AsyncIO backend transport for TermsOfServiceService. + + Service to support ``TermsOfService`` API. + + 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 get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + Awaitable[termsofservice.TermsOfService]]: + r"""Return a callable for the get terms of service method over gRPC. + + Retrieves the ``TermsOfService`` associated with the provided + version. + + Returns: + Callable[[~.GetTermsOfServiceRequest], + Awaitable[~.TermsOfService]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service' not in self._stubs: + self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceService/GetTermsOfService', + request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['get_terms_of_service'] + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + Awaitable[termsofservice.TermsOfService]]: + r"""Return a callable for the retrieve latest terms of + service method over gRPC. + + Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + Returns: + Callable[[~.RetrieveLatestTermsOfServiceRequest], + Awaitable[~.TermsOfService]]: + 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 'retrieve_latest_terms_of_service' not in self._stubs: + self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceService/RetrieveLatestTermsOfService', + request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['retrieve_latest_terms_of_service'] + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + Awaitable[termsofservice.AcceptTermsOfServiceResponse]]: + r"""Return a callable for the accept terms of service method over gRPC. + + Accepts a ``TermsOfService``. Executing this method requires + admin access. + + Returns: + Callable[[~.AcceptTermsOfServiceRequest], + Awaitable[~.AcceptTermsOfServiceResponse]]: + 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 'accept_terms_of_service' not in self._stubs: + self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.TermsOfServiceService/AcceptTermsOfService', + request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.AcceptTermsOfServiceResponse.deserialize, + ) + return self._stubs['accept_terms_of_service'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_terms_of_service: self._wrap_method( + self.get_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_latest_terms_of_service: self._wrap_method( + self.retrieve_latest_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.accept_terms_of_service: self._wrap_method( + self.accept_terms_of_service, + 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__ = ( + 'TermsOfServiceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py new file mode 100644 index 000000000000..05660541d6ae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py @@ -0,0 +1,723 @@ +# -*- 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.shopping.merchant_accounts_v1.types import termsofservice + + +from .rest_base import _BaseTermsOfServiceServiceRestTransport +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 TermsOfServiceServiceRestInterceptor: + """Interceptor for TermsOfServiceService. + + 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 TermsOfServiceServiceRestTransport. + + .. code-block:: python + class MyCustomTermsOfServiceServiceInterceptor(TermsOfServiceServiceRestInterceptor): + def pre_accept_terms_of_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_accept_terms_of_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_terms_of_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_terms_of_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_latest_terms_of_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_latest_terms_of_service(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TermsOfServiceServiceRestTransport(interceptor=MyCustomTermsOfServiceServiceInterceptor()) + client = TermsOfServiceServiceClient(transport=transport) + + + """ + def pre_accept_terms_of_service(self, request: termsofservice.AcceptTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for accept_terms_of_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceService server. + """ + return request, metadata + + def post_accept_terms_of_service(self, response: termsofservice.AcceptTermsOfServiceResponse) -> termsofservice.AcceptTermsOfServiceResponse: + """Post-rpc interceptor for accept_terms_of_service + + DEPRECATED. Please use the `post_accept_terms_of_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. This `post_accept_terms_of_service` interceptor runs + before the `post_accept_terms_of_service_with_metadata` interceptor. + """ + return response + + def post_accept_terms_of_service_with_metadata(self, response: termsofservice.AcceptTermsOfServiceResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.AcceptTermsOfServiceResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for accept_terms_of_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceService server but before it is returned to user code. + + We recommend only using this `post_accept_terms_of_service_with_metadata` + interceptor in new development instead of the `post_accept_terms_of_service` interceptor. + When both interceptors are used, this `post_accept_terms_of_service_with_metadata` interceptor runs after the + `post_accept_terms_of_service` interceptor. The (possibly modified) response returned by + `post_accept_terms_of_service` will be passed to + `post_accept_terms_of_service_with_metadata`. + """ + return response, metadata + + def pre_get_terms_of_service(self, request: termsofservice.GetTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_terms_of_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceService server. + """ + return request, metadata + + def post_get_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: + """Post-rpc interceptor for get_terms_of_service + + DEPRECATED. Please use the `post_get_terms_of_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. This `post_get_terms_of_service` interceptor runs + before the `post_get_terms_of_service_with_metadata` interceptor. + """ + return response + + def post_get_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_terms_of_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceService server but before it is returned to user code. + + We recommend only using this `post_get_terms_of_service_with_metadata` + interceptor in new development instead of the `post_get_terms_of_service` interceptor. + When both interceptors are used, this `post_get_terms_of_service_with_metadata` interceptor runs after the + `post_get_terms_of_service` interceptor. The (possibly modified) response returned by + `post_get_terms_of_service` will be passed to + `post_get_terms_of_service_with_metadata`. + """ + return response, metadata + + def pre_retrieve_latest_terms_of_service(self, request: termsofservice.RetrieveLatestTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for retrieve_latest_terms_of_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceService server. + """ + return request, metadata + + def post_retrieve_latest_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: + """Post-rpc interceptor for retrieve_latest_terms_of_service + + DEPRECATED. Please use the `post_retrieve_latest_terms_of_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. This `post_retrieve_latest_terms_of_service` interceptor runs + before the `post_retrieve_latest_terms_of_service_with_metadata` interceptor. + """ + return response + + def post_retrieve_latest_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for retrieve_latest_terms_of_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceService server but before it is returned to user code. + + We recommend only using this `post_retrieve_latest_terms_of_service_with_metadata` + interceptor in new development instead of the `post_retrieve_latest_terms_of_service` interceptor. + When both interceptors are used, this `post_retrieve_latest_terms_of_service_with_metadata` interceptor runs after the + `post_retrieve_latest_terms_of_service` interceptor. The (possibly modified) response returned by + `post_retrieve_latest_terms_of_service` will be passed to + `post_retrieve_latest_terms_of_service_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class TermsOfServiceServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TermsOfServiceServiceRestInterceptor + + +class TermsOfServiceServiceRestTransport(_BaseTermsOfServiceServiceRestTransport): + """REST backend synchronous transport for TermsOfServiceService. + + Service to support ``TermsOfService`` API. + + 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[TermsOfServiceServiceRestInterceptor] = 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 TermsOfServiceServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AcceptTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService, TermsOfServiceServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceServiceRestTransport.AcceptTermsOfService") + + @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: termsofservice.AcceptTermsOfServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofservice.AcceptTermsOfServiceResponse: + r"""Call the accept terms of service method over HTTP. + + Args: + request (~.termsofservice.AcceptTermsOfServiceRequest): + The request object. Request message for the ``AcceptTermsOfService`` 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: + ~.termsofservice.AcceptTermsOfServiceResponse: + Response message for the ``AcceptTermsOfService`` + method. + + """ + + http_options = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_http_options() + + request, metadata = self._interceptor.pre_accept_terms_of_service(request, metadata) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceServiceClient.AcceptTermsOfService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "rpcName": "AcceptTermsOfService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceServiceRestTransport._AcceptTermsOfService._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 = termsofservice.AcceptTermsOfServiceResponse() + pb_resp = termsofservice.AcceptTermsOfServiceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_accept_terms_of_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_accept_terms_of_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofservice.AcceptTermsOfServiceResponse.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.accounts_v1.TermsOfServiceServiceClient.accept_terms_of_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "rpcName": "AcceptTermsOfService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService, TermsOfServiceServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceServiceRestTransport.GetTermsOfService") + + @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: termsofservice.GetTermsOfServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofservice.TermsOfService: + r"""Call the get terms of service method over HTTP. + + Args: + request (~.termsofservice.GetTermsOfServiceRequest): + The request object. Request message for the ``GetTermsOfService`` 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: + ~.termsofservice.TermsOfService: + The ``TermsOfService`` message represents a specific + version of the terms of service that merchants must + accept to access certain features or services. For more + information, see `Terms of + Service `__. + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can retrieve + the latest terms of service for a given ``kind`` and + ``region`` through ``RetrieveLatestTermsOfService``, and + accept them as required through + ``AcceptTermsOfService``. + + """ + + http_options = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_http_options() + + request, metadata = self._interceptor.pre_get_terms_of_service(request, metadata) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceServiceClient.GetTermsOfService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "rpcName": "GetTermsOfService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceServiceRestTransport._GetTermsOfService._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 = termsofservice.TermsOfService() + pb_resp = termsofservice.TermsOfService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_terms_of_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_terms_of_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofservice.TermsOfService.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.accounts_v1.TermsOfServiceServiceClient.get_terms_of_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "rpcName": "GetTermsOfService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RetrieveLatestTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService, TermsOfServiceServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceServiceRestTransport.RetrieveLatestTermsOfService") + + @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: termsofservice.RetrieveLatestTermsOfServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofservice.TermsOfService: + r"""Call the retrieve latest terms of + service method over HTTP. + + Args: + request (~.termsofservice.RetrieveLatestTermsOfServiceRequest): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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: + ~.termsofservice.TermsOfService: + The ``TermsOfService`` message represents a specific + version of the terms of service that merchants must + accept to access certain features or services. For more + information, see `Terms of + Service `__. + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can retrieve + the latest terms of service for a given ``kind`` and + ``region`` through ``RetrieveLatestTermsOfService``, and + accept them as required through + ``AcceptTermsOfService``. + + """ + + http_options = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_http_options() + + request, metadata = self._interceptor.pre_retrieve_latest_terms_of_service(request, metadata) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceServiceClient.RetrieveLatestTermsOfService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "rpcName": "RetrieveLatestTermsOfService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceServiceRestTransport._RetrieveLatestTermsOfService._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 = termsofservice.TermsOfService() + pb_resp = termsofservice.TermsOfService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_latest_terms_of_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_retrieve_latest_terms_of_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofservice.TermsOfService.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.accounts_v1.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "rpcName": "RetrieveLatestTermsOfService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + termsofservice.AcceptTermsOfServiceResponse]: + # 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._AcceptTermsOfService(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + termsofservice.TermsOfService]: + # 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._GetTermsOfService(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + termsofservice.TermsOfService]: + # 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._RetrieveLatestTermsOfService(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TermsOfServiceServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py new file mode 100644 index 000000000000..8ae3b3ecdbdc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py @@ -0,0 +1,202 @@ +# -*- 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 TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1.types import termsofservice + + +class _BaseTermsOfServiceServiceRestTransport(TermsOfServiceServiceTransport): + """Base REST backend transport for TermsOfServiceService. + + 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 _BaseAcceptTermsOfService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "account" : "", "regionCode" : "", } + + @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': '/accounts/v1/{name=termsOfService/*}:accept', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofservice.AcceptTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTermsOfService: + 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': '/accounts/v1/{name=termsOfService/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofservice.GetTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRetrieveLatestTermsOfService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "regionCode" : "", "kind" : {}, } + + @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': '/accounts/v1/termsOfService:retrieveLatest', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofservice.RetrieveLatestTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseTermsOfServiceServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/__init__.py new file mode 100644 index 000000000000..d60a27bcbaf8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_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 UserServiceClient +from .async_client import UserServiceAsyncClient + +__all__ = ( + 'UserServiceClient', + 'UserServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py new file mode 100644 index 000000000000..ced4321c9b69 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py @@ -0,0 +1,860 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.user_service import pagers +from google.shopping.merchant_accounts_v1.types import accessright +from google.shopping.merchant_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user +from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport +from .client import UserServiceClient + +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 UserServiceAsyncClient: + """Service to support user API.""" + + _client: UserServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = UserServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = UserServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(UserServiceClient.account_path) + parse_account_path = staticmethod(UserServiceClient.parse_account_path) + user_path = staticmethod(UserServiceClient.user_path) + parse_user_path = staticmethod(UserServiceClient.parse_user_path) + common_billing_account_path = staticmethod(UserServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserServiceClient.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: + UserServiceAsyncClient: The constructed client. + """ + return UserServiceClient.from_service_account_info.__func__(UserServiceAsyncClient, 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: + UserServiceAsyncClient: The constructed client. + """ + return UserServiceClient.from_service_account_file.__func__(UserServiceAsyncClient, 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 UserServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserServiceTransport: 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 = UserServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, UserServiceTransport, Callable[..., UserServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user 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,UserServiceTransport,Callable[..., UserServiceTransport]]]): + 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 UserServiceTransport 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 = UserServiceClient( + 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.accounts_v1.UserServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "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.accounts.v1.UserService", + "credentialsType": None, + } + ) + + async def get_user(self, + request: Optional[Union[user.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: + r"""Retrieves a Merchant Center account user. + + .. 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_accounts_v1 + + async def sample_get_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.GetUserRequest, dict]]): + The request object. Request message for the ``GetUser`` method. + name (:class:`str`): + Required. The name of the user to retrieve. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to retrieve the user corresponding + to the caller by using ``me`` rather than an email + address as in ``accounts/{account}/users/me``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.User: + The User message represents a user associated with a Merchant Center + account. It is used to manage user permissions and + access rights within the account. For more + information, see [Frequently asked questions about + people and access + levels](//support.google.com/merchants/answer/12160472). + + """ + # 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, user.GetUserRequest): + request = user.GetUserRequest(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.get_user] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user(self, + request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[gsma_user.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Creates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1 + + async def sample_create_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.CreateUserRequest, dict]]): + The request object. Request message for the ``CreateUser`` method. + parent (:class:`str`): + Required. The resource name of the account for which a + user will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`google.shopping.merchant_accounts_v1.types.User`): + Optional. The user to create. + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (:class:`str`): + Required. The email address of the user (for example, + ``john.doe@gmail.com``). + + This corresponds to the ``user_id`` 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_accounts_v1.types.User: + The User message represents a user associated with a Merchant Center + account. It is used to manage user permissions and + access rights within the account. For more + information, see [Frequently asked questions about + people and access + levels](//support.google.com/merchants/answer/12160472). + + """ + # 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, user, user_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.CreateUserRequest): + request = gsma_user.CreateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user] + + # 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_user(self, + request: Optional[Union[user.DeleteUserRequest, dict]] = None, + *, + name: 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 a Merchant Center account user. Executing + this method requires admin access. The user to be + deleted can't be the last admin user of that account. + Also a user is protected from deletion if it is managed + by Business Manager" + + .. 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_accounts_v1 + + async def sample_delete_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.DeleteUserRequest, dict]]): + The request object. Request message for the ``DeleteUser`` method. + name (:class:`str`): + Required. The name of the user to delete. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to delete the user corresponding to + the caller by using ``me`` rather than an email address + as in ``accounts/{account}/users/me``. + + 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, user.DeleteUserRequest): + request = user.DeleteUserRequest(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_user] + + # 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 update_user(self, + request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, + *, + user: Optional[gsma_user.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Updates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1 + + async def sample_update_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + user = merchant_accounts_v1.User() + user.access_rights = ['API_DEVELOPER'] + + request = merchant_accounts_v1.UpdateUserRequest( + user=user, + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.UpdateUserRequest, dict]]): + The request object. Request message for the ``UpdateUser`` method. + user (:class:`google.shopping.merchant_accounts_v1.types.User`): + Required. The new version of the user. + + Use ``me`` to refer to your own email address, for + example ``accounts/{account}/users/me``. + + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``access_rights`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.User: + The User message represents a user associated with a Merchant Center + account. It is used to manage user permissions and + access rights within the account. For more + information, see [Frequently asked questions about + people and access + levels](//support.google.com/merchants/answer/12160472). + + """ + # 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 = [user, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.UpdateUserRequest): + request = gsma_user.UpdateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # 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 list_users(self, + request: Optional[Union[user.ListUsersRequest, 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.ListUsersAsyncPager: + r"""Lists all users of a Merchant Center 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_accounts_v1 + + async def sample_list_users(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1.types.ListUsersRequest, dict]]): + The request object. Request message for the ``ListUsers`` method. + parent (:class:`str`): + Required. The parent, which owns this collection of + users. Format: ``accounts/{account}`` + + 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_accounts_v1.services.user_service.pagers.ListUsersAsyncPager: + Response message for the ListUsers 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, user.ListUsersRequest): + request = user.ListUsersRequest(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_users] + + # 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.ListUsersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "UserServiceAsyncClient": + 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__ = ( + "UserServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py new file mode 100644 index 000000000000..d861ca155b22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py @@ -0,0 +1,1225 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.user_service import pagers +from google.shopping.merchant_accounts_v1.types import accessright +from google.shopping.merchant_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user +from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserServiceGrpcTransport +from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport +from .transports.rest import UserServiceRestTransport + + +class UserServiceClientMeta(type): + """Metaclass for the UserService 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[UserServiceTransport]] + _transport_registry["grpc"] = UserServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[UserServiceTransport]: + """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 UserServiceClient(metaclass=UserServiceClientMeta): + """Service to support user API.""" + + @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: + UserServiceClient: 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: + UserServiceClient: 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) -> UserServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(account: str,email: str,) -> str: + """Returns a fully-qualified user string.""" + return "accounts/{account}/users/{email}".format(account=account, email=email, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/users/(?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 = UserServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = UserServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = UserServiceClient._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 = UserServiceClient._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, UserServiceTransport, Callable[..., UserServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user 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,UserServiceTransport,Callable[..., UserServiceTransport]]]): + 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 UserServiceTransport 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 = UserServiceClient._read_environment_variables() + self._client_cert_source = UserServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = UserServiceClient._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, UserServiceTransport) + if transport_provided: + # transport is a UserServiceTransport 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(UserServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + UserServiceClient._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[UserServiceTransport], Callable[..., UserServiceTransport]] = ( + UserServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., UserServiceTransport], 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.accounts_v1.UserServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "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.accounts.v1.UserService", + "credentialsType": None, + } + ) + + def get_user(self, + request: Optional[Union[user.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: + r"""Retrieves a Merchant Center account user. + + .. 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_accounts_v1 + + def sample_get_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.GetUserRequest, dict]): + The request object. Request message for the ``GetUser`` method. + name (str): + Required. The name of the user to retrieve. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to retrieve the user corresponding + to the caller by using ``me`` rather than an email + address as in ``accounts/{account}/users/me``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1.types.User: + The User message represents a user associated with a Merchant Center + account. It is used to manage user permissions and + access rights within the account. For more + information, see [Frequently asked questions about + people and access + levels](//support.google.com/merchants/answer/12160472). + + """ + # 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, user.GetUserRequest): + request = user.GetUserRequest(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.get_user] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_user(self, + request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[gsma_user.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Creates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1 + + def sample_create_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.CreateUserRequest, dict]): + The request object. Request message for the ``CreateUser`` method. + parent (str): + Required. The resource name of the account for which a + user will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (google.shopping.merchant_accounts_v1.types.User): + Optional. The user to create. + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user_id (str): + Required. The email address of the user (for example, + ``john.doe@gmail.com``). + + This corresponds to the ``user_id`` 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_accounts_v1.types.User: + The User message represents a user associated with a Merchant Center + account. It is used to manage user permissions and + access rights within the account. For more + information, see [Frequently asked questions about + people and access + levels](//support.google.com/merchants/answer/12160472). + + """ + # 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, user, user_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.CreateUserRequest): + request = gsma_user.CreateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + if user_id is not None: + request.user_id = user_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user] + + # 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_user(self, + request: Optional[Union[user.DeleteUserRequest, dict]] = None, + *, + name: 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 a Merchant Center account user. Executing + this method requires admin access. The user to be + deleted can't be the last admin user of that account. + Also a user is protected from deletion if it is managed + by Business Manager" + + .. 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_accounts_v1 + + def sample_delete_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.DeleteUserRequest, dict]): + The request object. Request message for the ``DeleteUser`` method. + name (str): + Required. The name of the user to delete. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to delete the user corresponding to + the caller by using ``me`` rather than an email address + as in ``accounts/{account}/users/me``. + + 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, user.DeleteUserRequest): + request = user.DeleteUserRequest(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_user] + + # 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 update_user(self, + request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, + *, + user: Optional[gsma_user.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Updates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1 + + def sample_update_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + user = merchant_accounts_v1.User() + user.access_rights = ['API_DEVELOPER'] + + request = merchant_accounts_v1.UpdateUserRequest( + user=user, + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.UpdateUserRequest, dict]): + The request object. Request message for the ``UpdateUser`` method. + user (google.shopping.merchant_accounts_v1.types.User): + Required. The new version of the user. + + Use ``me`` to refer to your own email address, for + example ``accounts/{account}/users/me``. + + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``access_rights`` + + This corresponds to the ``update_mask`` 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_accounts_v1.types.User: + The User message represents a user associated with a Merchant Center + account. It is used to manage user permissions and + access rights within the account. For more + information, see [Frequently asked questions about + people and access + levels](//support.google.com/merchants/answer/12160472). + + """ + # 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 = [user, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.UpdateUserRequest): + request = gsma_user.UpdateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # 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 list_users(self, + request: Optional[Union[user.ListUsersRequest, 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.ListUsersPager: + r"""Lists all users of a Merchant Center 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_accounts_v1 + + def sample_list_users(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1.types.ListUsersRequest, dict]): + The request object. Request message for the ``ListUsers`` method. + parent (str): + Required. The parent, which owns this collection of + users. Format: ``accounts/{account}`` + + 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_accounts_v1.services.user_service.pagers.ListUsersPager: + Response message for the ListUsers 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, user.ListUsersRequest): + request = user.ListUsersRequest(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_users] + + # 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.ListUsersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserServiceClient": + 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__ = ( + "UserServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/pagers.py new file mode 100644 index 000000000000..826a8336b703 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_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_accounts_v1.types import user + + +class ListUsersPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListUsersResponse` + 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[..., user.ListUsersResponse], + request: user.ListUsersRequest, + response: user.ListUsersResponse, + *, + 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_accounts_v1.types.ListUsersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListUsersResponse): + 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 = user.ListUsersRequest(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[user.ListUsersResponse]: + 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[user.User]: + for page in self.pages: + yield from page.users + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersAsyncPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1.types.ListUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1.types.ListUsersResponse` + 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[user.ListUsersResponse]], + request: user.ListUsersRequest, + response: user.ListUsersResponse, + *, + 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_accounts_v1.types.ListUsersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1.types.ListUsersResponse): + 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 = user.ListUsersRequest(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[user.ListUsersResponse]: + 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[user.User]: + async def async_generator(): + async for page in self.pages: + for response in page.users: + 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-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst new file mode 100644 index 000000000000..815387def1a4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`UserServiceTransport` is the ABC for all transports. +- public child `UserServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `UserServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseUserServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `UserServiceRestTransport` 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-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py new file mode 100644 index 000000000000..b8429533bdc0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_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 UserServiceTransport +from .grpc import UserServiceGrpcTransport +from .grpc_asyncio import UserServiceGrpcAsyncIOTransport +from .rest import UserServiceRestTransport +from .rest import UserServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserServiceTransport]] +_transport_registry['grpc'] = UserServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserServiceGrpcAsyncIOTransport +_transport_registry['rest'] = UserServiceRestTransport + +__all__ = ( + 'UserServiceTransport', + 'UserServiceGrpcTransport', + 'UserServiceGrpcAsyncIOTransport', + 'UserServiceRestTransport', + 'UserServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py new file mode 100644 index 000000000000..2eb9b38addc7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py @@ -0,0 +1,217 @@ +# -*- 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_accounts_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_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user + +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 UserServiceTransport(abc.ABC): + """Abstract transport class for UserService.""" + + 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.get_user: gapic_v1.method.wrap_method( + self.get_user, + default_timeout=None, + client_info=client_info, + ), + self.create_user: gapic_v1.method.wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: gapic_v1.method.wrap_method( + self.delete_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: gapic_v1.method.wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.list_users: gapic_v1.method.wrap_method( + self.list_users, + 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 get_user(self) -> Callable[ + [user.GetUserRequest], + Union[ + user.User, + Awaitable[user.User] + ]]: + raise NotImplementedError() + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + Union[ + gsma_user.User, + Awaitable[gsma_user.User] + ]]: + raise NotImplementedError() + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + Union[ + gsma_user.User, + Awaitable[gsma_user.User] + ]]: + raise NotImplementedError() + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + Union[ + user.ListUsersResponse, + Awaitable[user.ListUsersResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py new file mode 100644 index 000000000000..535cdabf9470 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py @@ -0,0 +1,458 @@ +# -*- 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_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user +from .base import UserServiceTransport, 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.accounts.v1.UserService", + "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.accounts.v1.UserService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class UserServiceGrpcTransport(UserServiceTransport): + """gRPC backend transport for UserService. + + Service to support user API. + + 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 get_user(self) -> Callable[ + [user.GetUserRequest], + user.User]: + r"""Return a callable for the get user method over gRPC. + + Retrieves a Merchant Center account user. + + Returns: + Callable[[~.GetUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_user' not in self._stubs: + self._stubs['get_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/GetUser', + request_serializer=user.GetUserRequest.serialize, + response_deserializer=user.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + gsma_user.User]: + r"""Return a callable for the create user method over gRPC. + + Creates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.CreateUserRequest], + ~.User]: + 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 'create_user' not in self._stubs: + self._stubs['create_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/CreateUser', + request_serializer=gsma_user.CreateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a Merchant Center account user. Executing + this method requires admin access. The user to be + deleted can't be the last admin user of that account. + Also a user is protected from deletion if it is managed + by Business Manager" + + Returns: + Callable[[~.DeleteUserRequest], + ~.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_user' not in self._stubs: + self._stubs['delete_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/DeleteUser', + request_serializer=user.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + gsma_user.User]: + r"""Return a callable for the update user method over gRPC. + + Updates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateUserRequest], + ~.User]: + 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 'update_user' not in self._stubs: + self._stubs['update_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/UpdateUser', + request_serializer=gsma_user.UpdateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + user.ListUsersResponse]: + r"""Return a callable for the list users method over gRPC. + + Lists all users of a Merchant Center account. + + Returns: + Callable[[~.ListUsersRequest], + ~.ListUsersResponse]: + 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_users' not in self._stubs: + self._stubs['list_users'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/ListUsers', + request_serializer=user.ListUsersRequest.serialize, + response_deserializer=user.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..21e6e8b4ecda --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py @@ -0,0 +1,499 @@ +# -*- 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_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user +from .base import UserServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserServiceGrpcTransport + +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.accounts.v1.UserService", + "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.accounts.v1.UserService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class UserServiceGrpcAsyncIOTransport(UserServiceTransport): + """gRPC AsyncIO backend transport for UserService. + + Service to support user API. + + 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 get_user(self) -> Callable[ + [user.GetUserRequest], + Awaitable[user.User]]: + r"""Return a callable for the get user method over gRPC. + + Retrieves a Merchant Center account user. + + Returns: + Callable[[~.GetUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_user' not in self._stubs: + self._stubs['get_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/GetUser', + request_serializer=user.GetUserRequest.serialize, + response_deserializer=user.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + Awaitable[gsma_user.User]]: + r"""Return a callable for the create user method over gRPC. + + Creates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.CreateUserRequest], + Awaitable[~.User]]: + 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 'create_user' not in self._stubs: + self._stubs['create_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/CreateUser', + request_serializer=gsma_user.CreateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a Merchant Center account user. Executing + this method requires admin access. The user to be + deleted can't be the last admin user of that account. + Also a user is protected from deletion if it is managed + by Business Manager" + + Returns: + Callable[[~.DeleteUserRequest], + 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_user' not in self._stubs: + self._stubs['delete_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/DeleteUser', + request_serializer=user.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + Awaitable[gsma_user.User]]: + r"""Return a callable for the update user method over gRPC. + + Updates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateUserRequest], + Awaitable[~.User]]: + 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 'update_user' not in self._stubs: + self._stubs['update_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/UpdateUser', + request_serializer=gsma_user.UpdateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + Awaitable[user.ListUsersResponse]]: + r"""Return a callable for the list users method over gRPC. + + Lists all users of a Merchant Center account. + + Returns: + Callable[[~.ListUsersRequest], + Awaitable[~.ListUsersResponse]]: + 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_users' not in self._stubs: + self._stubs['list_users'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1.UserService/ListUsers', + request_serializer=user.ListUsersRequest.serialize, + response_deserializer=user.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_user: self._wrap_method( + self.get_user, + default_timeout=None, + client_info=client_info, + ), + self.create_user: self._wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: self._wrap_method( + self.delete_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: self._wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.list_users: self._wrap_method( + self.list_users, + 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__ = ( + 'UserServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py new file mode 100644 index 000000000000..776d02cced2a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py @@ -0,0 +1,995 @@ +# -*- 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_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user + + +from .rest_base import _BaseUserServiceRestTransport +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 UserServiceRestInterceptor: + """Interceptor for UserService. + + 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 UserServiceRestTransport. + + .. code-block:: python + class MyCustomUserServiceInterceptor(UserServiceRestInterceptor): + def pre_create_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserServiceRestTransport(interceptor=MyCustomUserServiceInterceptor()) + client = UserServiceClient(transport=transport) + + + """ + def pre_create_user(self, request: gsma_user.CreateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_create_user(self, response: gsma_user.User) -> gsma_user.User: + """Post-rpc interceptor for create_user + + DEPRECATED. Please use the `post_create_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_create_user` interceptor runs + before the `post_create_user_with_metadata` interceptor. + """ + return response + + def post_create_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_create_user_with_metadata` + interceptor in new development instead of the `post_create_user` interceptor. + When both interceptors are used, this `post_create_user_with_metadata` interceptor runs after the + `post_create_user` interceptor. The (possibly modified) response returned by + `post_create_user` will be passed to + `post_create_user_with_metadata`. + """ + return response, metadata + + def pre_delete_user(self, request: user.DeleteUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def pre_get_user(self, request: user.GetUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_get_user(self, response: user.User) -> user.User: + """Post-rpc interceptor for get_user + + DEPRECATED. Please use the `post_get_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_get_user` interceptor runs + before the `post_get_user_with_metadata` interceptor. + """ + return response + + def post_get_user_with_metadata(self, response: user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_get_user_with_metadata` + interceptor in new development instead of the `post_get_user` interceptor. + When both interceptors are used, this `post_get_user_with_metadata` interceptor runs after the + `post_get_user` interceptor. The (possibly modified) response returned by + `post_get_user` will be passed to + `post_get_user_with_metadata`. + """ + return response, metadata + + def pre_list_users(self, request: user.ListUsersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_list_users(self, response: user.ListUsersResponse) -> user.ListUsersResponse: + """Post-rpc interceptor for list_users + + DEPRECATED. Please use the `post_list_users_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_list_users` interceptor runs + before the `post_list_users_with_metadata` interceptor. + """ + return response + + def post_list_users_with_metadata(self, response: user.ListUsersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_users + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_list_users_with_metadata` + interceptor in new development instead of the `post_list_users` interceptor. + When both interceptors are used, this `post_list_users_with_metadata` interceptor runs after the + `post_list_users` interceptor. The (possibly modified) response returned by + `post_list_users` will be passed to + `post_list_users_with_metadata`. + """ + return response, metadata + + def pre_update_user(self, request: gsma_user.UpdateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_update_user(self, response: gsma_user.User) -> gsma_user.User: + """Post-rpc interceptor for update_user + + DEPRECATED. Please use the `post_update_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_update_user` interceptor runs + before the `post_update_user_with_metadata` interceptor. + """ + return response + + def post_update_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_update_user_with_metadata` + interceptor in new development instead of the `post_update_user` interceptor. + When both interceptors are used, this `post_update_user_with_metadata` interceptor runs after the + `post_update_user` interceptor. The (possibly modified) response returned by + `post_update_user` will be passed to + `post_update_user_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class UserServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserServiceRestInterceptor + + +class UserServiceRestTransport(_BaseUserServiceRestTransport): + """REST backend synchronous transport for UserService. + + Service to support user API. + + 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[UserServiceRestInterceptor] = 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 UserServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateUser(_BaseUserServiceRestTransport._BaseCreateUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.CreateUser") + + @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: gsma_user.CreateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_user.User: + r"""Call the create user method over HTTP. + + Args: + request (~.gsma_user.CreateUserRequest): + The request object. Request message for the ``CreateUser`` 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: + ~.gsma_user.User: + The ``User`` message represents a user associated with a + Merchant Center account. It is used to manage user + permissions and access rights within the account. For + more information, see `Frequently asked questions about + people and access + levels `__. + + """ + + http_options = _BaseUserServiceRestTransport._BaseCreateUser._get_http_options() + + request, metadata = self._interceptor.pre_create_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseCreateUser._get_transcoded_request(http_options, request) + + body = _BaseUserServiceRestTransport._BaseCreateUser._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseCreateUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.UserServiceClient.CreateUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "CreateUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._CreateUser._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 = gsma_user.User() + pb_resp = gsma_user.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_user.User.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.accounts_v1.UserServiceClient.create_user", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "CreateUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteUser(_BaseUserServiceRestTransport._BaseDeleteUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.DeleteUser") + + @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: user.DeleteUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user method over HTTP. + + Args: + request (~.user.DeleteUserRequest): + The request object. Request message for the ``DeleteUser`` 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 = _BaseUserServiceRestTransport._BaseDeleteUser._get_http_options() + + request, metadata = self._interceptor.pre_delete_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseDeleteUser._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseDeleteUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.UserServiceClient.DeleteUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "DeleteUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._DeleteUser._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 _GetUser(_BaseUserServiceRestTransport._BaseGetUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.GetUser") + + @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: user.GetUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> user.User: + r"""Call the get user method over HTTP. + + Args: + request (~.user.GetUserRequest): + The request object. Request message for the ``GetUser`` 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: + ~.user.User: + The ``User`` message represents a user associated with a + Merchant Center account. It is used to manage user + permissions and access rights within the account. For + more information, see `Frequently asked questions about + people and access + levels `__. + + """ + + http_options = _BaseUserServiceRestTransport._BaseGetUser._get_http_options() + + request, metadata = self._interceptor.pre_get_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseGetUser._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseGetUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.UserServiceClient.GetUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "GetUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._GetUser._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 = user.User() + pb_resp = user.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = user.User.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.accounts_v1.UserServiceClient.get_user", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "GetUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUsers(_BaseUserServiceRestTransport._BaseListUsers, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.ListUsers") + + @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: user.ListUsersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> user.ListUsersResponse: + r"""Call the list users method over HTTP. + + Args: + request (~.user.ListUsersRequest): + The request object. Request message for the ``ListUsers`` 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: + ~.user.ListUsersResponse: + Response message for the ``ListUsers`` method. + """ + + http_options = _BaseUserServiceRestTransport._BaseListUsers._get_http_options() + + request, metadata = self._interceptor.pre_list_users(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseListUsers._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseListUsers._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.UserServiceClient.ListUsers", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "ListUsers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._ListUsers._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 = user.ListUsersResponse() + pb_resp = user.ListUsersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_users(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_users_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = user.ListUsersResponse.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.accounts_v1.UserServiceClient.list_users", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "ListUsers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUser(_BaseUserServiceRestTransport._BaseUpdateUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.UpdateUser") + + @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: gsma_user.UpdateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_user.User: + r"""Call the update user method over HTTP. + + Args: + request (~.gsma_user.UpdateUserRequest): + The request object. Request message for the ``UpdateUser`` 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: + ~.gsma_user.User: + The ``User`` message represents a user associated with a + Merchant Center account. It is used to manage user + permissions and access rights within the account. For + more information, see `Frequently asked questions about + people and access + levels `__. + + """ + + http_options = _BaseUserServiceRestTransport._BaseUpdateUser._get_http_options() + + request, metadata = self._interceptor.pre_update_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseUpdateUser._get_transcoded_request(http_options, request) + + body = _BaseUserServiceRestTransport._BaseUpdateUser._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseUpdateUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.UserServiceClient.UpdateUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "UpdateUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._UpdateUser._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 = gsma_user.User() + pb_resp = gsma_user.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_user.User.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.accounts_v1.UserServiceClient.update_user", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1.UserService", + "rpcName": "UpdateUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + gsma_user.User]: + # 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._CreateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + 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._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user(self) -> Callable[ + [user.GetUserRequest], + user.User]: + # 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._GetUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + user.ListUsersResponse]: + # 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._ListUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + gsma_user.User]: + # 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._UpdateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'UserServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py new file mode 100644 index 000000000000..8de3929910a7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py @@ -0,0 +1,298 @@ +# -*- 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 UserServiceTransport, 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_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user + + +class _BaseUserServiceRestTransport(UserServiceTransport): + """Base REST backend transport for UserService. + + 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 _BaseCreateUser: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userId" : "", } + + @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': '/accounts/v1/{parent=accounts/*}/users', + 'body': 'user', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_user.CreateUserRequest.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(_BaseUserServiceRestTransport._BaseCreateUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteUser: + 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': '/accounts/v1/{name=accounts/*/users/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user.DeleteUserRequest.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(_BaseUserServiceRestTransport._BaseDeleteUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetUser: + 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': '/accounts/v1/{name=accounts/*/users/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user.GetUserRequest.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(_BaseUserServiceRestTransport._BaseGetUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUsers: + 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': '/accounts/v1/{parent=accounts/*}/users', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user.ListUsersRequest.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(_BaseUserServiceRestTransport._BaseListUsers._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateUser: + 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': 'patch', + 'uri': '/accounts/v1/{user.name=accounts/*/users/*}', + 'body': 'user', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_user.UpdateUserRequest.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(_BaseUserServiceRestTransport._BaseUpdateUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseUserServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py new file mode 100644 index 000000000000..c79bc85f5c8c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py @@ -0,0 +1,368 @@ +# -*- 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 .accessright import ( + AccessRight, +) +from .accountissue import ( + AccountIssue, + ListAccountIssuesRequest, + ListAccountIssuesResponse, +) +from .accountrelationships import ( + AccountRelationship, + GetAccountRelationshipRequest, + ListAccountRelationshipsRequest, + ListAccountRelationshipsResponse, + UpdateAccountRelationshipRequest, +) +from .accounts import ( + Account, + CreateAndConfigureAccountRequest, + DeleteAccountRequest, + GetAccountRequest, + ListAccountsRequest, + ListAccountsResponse, + ListSubAccountsRequest, + ListSubAccountsResponse, + UpdateAccountRequest, +) +from .accountservices import ( + AccountAggregation, + AccountManagement, + AccountService, + ApproveAccountServiceRequest, + CampaignsManagement, + GetAccountServiceRequest, + Handshake, + ListAccountServicesRequest, + ListAccountServicesResponse, + LocalListingManagement, + ProductsManagement, + ProposeAccountServiceRequest, + RejectAccountServiceRequest, +) +from .autofeedsettings import ( + AutofeedSettings, + GetAutofeedSettingsRequest, + UpdateAutofeedSettingsRequest, +) +from .automaticimprovements import ( + AutomaticImageImprovements, + AutomaticImprovements, + AutomaticItemUpdates, + AutomaticShippingImprovements, + GetAutomaticImprovementsRequest, + UpdateAutomaticImprovementsRequest, +) +from .businessidentity import ( + BusinessIdentity, + GetBusinessIdentityRequest, + UpdateBusinessIdentityRequest, +) +from .businessinfo import ( + BusinessInfo, + GetBusinessInfoRequest, + UpdateBusinessInfoRequest, +) +from .checkoutsettings import ( + CheckoutSettings, + CreateCheckoutSettingsRequest, + DeleteCheckoutSettingsRequest, + GetCheckoutSettingsRequest, + UpdateCheckoutSettingsRequest, + UriSettings, +) +from .customerservice import ( + CustomerService, +) +from .developerregistration import ( + DeveloperRegistration, + GetDeveloperRegistrationRequest, + RegisterGcpRequest, + UnregisterGcpRequest, +) +from .emailpreferences import ( + EmailPreferences, + GetEmailPreferencesRequest, + UpdateEmailPreferencesRequest, +) +from .gbpaccounts import ( + GbpAccount, + LinkGbpAccountRequest, + LinkGbpAccountResponse, + ListGbpAccountsRequest, + ListGbpAccountsResponse, +) +from .homepage import ( + ClaimHomepageRequest, + GetHomepageRequest, + Homepage, + UnclaimHomepageRequest, + UpdateHomepageRequest, +) +from .lfpproviders import ( + FindLfpProvidersRequest, + FindLfpProvidersResponse, + LfpProvider, + LinkLfpProviderRequest, + LinkLfpProviderResponse, +) +from .omnichannelsettings import ( + About, + CreateOmnichannelSettingRequest, + GetOmnichannelSettingRequest, + InStock, + InventoryVerification, + LfpLink, + ListOmnichannelSettingsRequest, + ListOmnichannelSettingsResponse, + OmnichannelSetting, + OnDisplayToOrder, + Pickup, + RequestInventoryVerificationRequest, + RequestInventoryVerificationResponse, + ReviewState, + UpdateOmnichannelSettingRequest, +) +from .online_return_policy import ( + CreateOnlineReturnPolicyRequest, + DeleteOnlineReturnPolicyRequest, + GetOnlineReturnPolicyRequest, + ListOnlineReturnPoliciesRequest, + ListOnlineReturnPoliciesResponse, + OnlineReturnPolicy, +) +from .phoneverificationstate import ( + PhoneVerificationState, +) +from .programs import ( + DisableProgramRequest, + EnableProgramRequest, + GetProgramRequest, + ListProgramsRequest, + ListProgramsResponse, + Program, +) +from .regions import ( + CreateRegionRequest, + DeleteRegionRequest, + GetRegionRequest, + ListRegionsRequest, + ListRegionsResponse, + Region, + UpdateRegionRequest, +) +from .shippingsettings import ( + Address, + BusinessDayConfig, + CarrierRate, + CutoffTime, + DeliveryTime, + Distance, + GetShippingSettingsRequest, + Headers, + InsertShippingSettingsRequest, + LocationIdSet, + MinimumOrderValueTable, + RateGroup, + Row, + Service, + ShippingSettings, + Table, + TransitTable, + Value, + Warehouse, + WarehouseBasedDeliveryTime, + WarehouseCutoffTime, +) +from .termsofservice import ( + AcceptTermsOfServiceRequest, + AcceptTermsOfServiceResponse, + GetTermsOfServiceRequest, + RetrieveLatestTermsOfServiceRequest, + TermsOfService, +) +from .termsofserviceagreementstate import ( + Accepted, + GetTermsOfServiceAgreementStateRequest, + Required, + RetrieveForApplicationTermsOfServiceAgreementStateRequest, + TermsOfServiceAgreementState, +) +from .termsofservicekind import ( + TermsOfServiceKind, +) +from .user import ( + CreateUserRequest, + DeleteUserRequest, + GetUserRequest, + ListUsersRequest, + ListUsersResponse, + UpdateUserRequest, + User, +) + +__all__ = ( + 'AccessRight', + 'AccountIssue', + 'ListAccountIssuesRequest', + 'ListAccountIssuesResponse', + 'AccountRelationship', + 'GetAccountRelationshipRequest', + 'ListAccountRelationshipsRequest', + 'ListAccountRelationshipsResponse', + 'UpdateAccountRelationshipRequest', + 'Account', + 'CreateAndConfigureAccountRequest', + 'DeleteAccountRequest', + 'GetAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListSubAccountsRequest', + 'ListSubAccountsResponse', + 'UpdateAccountRequest', + 'AccountAggregation', + 'AccountManagement', + 'AccountService', + 'ApproveAccountServiceRequest', + 'CampaignsManagement', + 'GetAccountServiceRequest', + 'Handshake', + 'ListAccountServicesRequest', + 'ListAccountServicesResponse', + 'LocalListingManagement', + 'ProductsManagement', + 'ProposeAccountServiceRequest', + 'RejectAccountServiceRequest', + 'AutofeedSettings', + 'GetAutofeedSettingsRequest', + 'UpdateAutofeedSettingsRequest', + 'AutomaticImageImprovements', + 'AutomaticImprovements', + 'AutomaticItemUpdates', + 'AutomaticShippingImprovements', + 'GetAutomaticImprovementsRequest', + 'UpdateAutomaticImprovementsRequest', + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + 'CheckoutSettings', + 'CreateCheckoutSettingsRequest', + 'DeleteCheckoutSettingsRequest', + 'GetCheckoutSettingsRequest', + 'UpdateCheckoutSettingsRequest', + 'UriSettings', + 'CustomerService', + 'DeveloperRegistration', + 'GetDeveloperRegistrationRequest', + 'RegisterGcpRequest', + 'UnregisterGcpRequest', + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + 'GbpAccount', + 'LinkGbpAccountRequest', + 'LinkGbpAccountResponse', + 'ListGbpAccountsRequest', + 'ListGbpAccountsResponse', + 'ClaimHomepageRequest', + 'GetHomepageRequest', + 'Homepage', + 'UnclaimHomepageRequest', + 'UpdateHomepageRequest', + 'FindLfpProvidersRequest', + 'FindLfpProvidersResponse', + 'LfpProvider', + 'LinkLfpProviderRequest', + 'LinkLfpProviderResponse', + 'About', + 'CreateOmnichannelSettingRequest', + 'GetOmnichannelSettingRequest', + 'InStock', + 'InventoryVerification', + 'LfpLink', + 'ListOmnichannelSettingsRequest', + 'ListOmnichannelSettingsResponse', + 'OmnichannelSetting', + 'OnDisplayToOrder', + 'Pickup', + 'RequestInventoryVerificationRequest', + 'RequestInventoryVerificationResponse', + 'ReviewState', + 'UpdateOmnichannelSettingRequest', + 'CreateOnlineReturnPolicyRequest', + 'DeleteOnlineReturnPolicyRequest', + 'GetOnlineReturnPolicyRequest', + 'ListOnlineReturnPoliciesRequest', + 'ListOnlineReturnPoliciesResponse', + 'OnlineReturnPolicy', + 'PhoneVerificationState', + 'DisableProgramRequest', + 'EnableProgramRequest', + 'GetProgramRequest', + 'ListProgramsRequest', + 'ListProgramsResponse', + 'Program', + 'CreateRegionRequest', + 'DeleteRegionRequest', + 'GetRegionRequest', + 'ListRegionsRequest', + 'ListRegionsResponse', + 'Region', + 'UpdateRegionRequest', + 'Address', + 'BusinessDayConfig', + 'CarrierRate', + 'CutoffTime', + 'DeliveryTime', + 'Distance', + 'GetShippingSettingsRequest', + 'Headers', + 'InsertShippingSettingsRequest', + 'LocationIdSet', + 'MinimumOrderValueTable', + 'RateGroup', + 'Row', + 'Service', + 'ShippingSettings', + 'Table', + 'TransitTable', + 'Value', + 'Warehouse', + 'WarehouseBasedDeliveryTime', + 'WarehouseCutoffTime', + 'AcceptTermsOfServiceRequest', + 'AcceptTermsOfServiceResponse', + 'GetTermsOfServiceRequest', + 'RetrieveLatestTermsOfServiceRequest', + 'TermsOfService', + 'Accepted', + 'GetTermsOfServiceAgreementStateRequest', + 'Required', + 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + 'TermsOfServiceAgreementState', + 'TermsOfServiceKind', + 'CreateUserRequest', + 'DeleteUserRequest', + 'GetUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + 'UpdateUserRequest', + 'User', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py new file mode 100644 index 000000000000..08b75f89ef8c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py @@ -0,0 +1,61 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'AccessRight', + }, +) + + +class AccessRight(proto.Enum): + r"""The access right. + + Values: + ACCESS_RIGHT_UNSPECIFIED (0): + Default value. This value is unused. + STANDARD (1): + Standard access rights. + READ_ONLY (4): + Has access to the same read-only methods as + STANDARD, but no access to any mutating methods. + ADMIN (2): + Admin access rights. + PERFORMANCE_REPORTING (3): + Users with this right have access to + performance and insights. + API_DEVELOPER (5): + Users with this right have access to Merchant + API and its notifications. This role is only + accessible to accounts that has a developer + registration. + """ + ACCESS_RIGHT_UNSPECIFIED = 0 + STANDARD = 1 + READ_ONLY = 4 + ADMIN = 2 + PERFORMANCE_REPORTING = 3 + API_DEVELOPER = 5 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py new file mode 100644 index 000000000000..5014a9b66738 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py @@ -0,0 +1,239 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'AccountIssue', + 'ListAccountIssuesRequest', + 'ListAccountIssuesResponse', + }, +) + + +class AccountIssue(proto.Message): + r"""Issues with your Merchant Center account that can impact all your + products. For more information, see `Account-level issues in + Merchant + Center `__. + + Attributes: + name (str): + Identifier. The resource name of the account issue. Format: + ``accounts/{account}/issues/{id}``. For example, + ``accounts/123456/issues/misrepresentation-of-self-or-products-unacceptable-business-practice-policy``. + title (str): + The localized title of the issue. + severity (google.shopping.merchant_accounts_v1.types.AccountIssue.Severity): + The overall severity of the issue. + impacted_destinations (MutableSequence[google.shopping.merchant_accounts_v1.types.AccountIssue.ImpactedDestination]): + The impact this issue has on various + destinations. + detail (str): + Further localized details about the issue. + documentation_uri (str): + Link to Merchant Center Help Center providing + further information about the issue and how to + fix it. + """ + class Severity(proto.Enum): + r"""All possible issue severities. + + Values: + SEVERITY_UNSPECIFIED (0): + The severity is unknown. + CRITICAL (1): + The issue causes offers to not serve. + ERROR (2): + The issue might affect offers (in the future) + or might be an indicator of issues with offers. + SUGGESTION (3): + The issue is a suggestion for improvement. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + ERROR = 2 + SUGGESTION = 3 + + class ImpactedDestination(proto.Message): + r"""The impact of the issue on a destination. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + The impacted reporting context. + + This field is a member of `oneof`_ ``_reporting_context``. + impacts (MutableSequence[google.shopping.merchant_accounts_v1.types.AccountIssue.ImpactedDestination.Impact]): + The (negative) impact for various regions on + the given destination. + """ + + class Impact(proto.Message): + r"""The impact of the issue on a region. + + Attributes: + region_code (str): + The `CLDR region code `__ where + this issue applies. + severity (google.shopping.merchant_accounts_v1.types.AccountIssue.Severity): + The severity of the issue on the destination + and region. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + severity: 'AccountIssue.Severity' = proto.Field( + proto.ENUM, + number=2, + enum='AccountIssue.Severity', + ) + + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=types.ReportingContext.ReportingContextEnum, + ) + impacts: MutableSequence['AccountIssue.ImpactedDestination.Impact'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AccountIssue.ImpactedDestination.Impact', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=3, + enum=Severity, + ) + impacted_destinations: MutableSequence[ImpactedDestination] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=ImpactedDestination, + ) + detail: str = proto.Field( + proto.STRING, + number=5, + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListAccountIssuesRequest(proto.Message): + r"""Request message for the ``ListAccountIssues`` method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of issues. + Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of issues to + return. The service may return fewer than this + value. If unspecified, at most 50 issues will be + returned. The maximum value is 100; values above + 100 will be coerced to 100 + page_token (str): + Optional. A page token, received from a previous + ``ListAccountIssues`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListAccountIssues`` must match the call that provided the + page token. + language_code (str): + Optional. The issues in the response will have + human-readable fields in the given language. The format is + `BCP-47 `__, such as + ``en-US`` or ``sr-Latn``. If not value is provided, + ``en-US`` will be used. + time_zone (str): + Optional. The `IANA `__ + timezone used to localize times in human-readable fields. + For example 'America/Los_Angeles'. If not set, + 'America/Los_Angeles' will be used. + """ + + 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, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + time_zone: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAccountIssuesResponse(proto.Message): + r"""Response message for the ``ListAccountIssues`` method. + + Attributes: + account_issues (MutableSequence[google.shopping.merchant_accounts_v1.types.AccountIssue]): + The issues from the specified account. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + account_issues: MutableSequence['AccountIssue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccountIssue', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py new file mode 100644 index 000000000000..97dc0cdd5333 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py @@ -0,0 +1,202 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'AccountRelationship', + 'GetAccountRelationshipRequest', + 'UpdateAccountRelationshipRequest', + 'ListAccountRelationshipsRequest', + 'ListAccountRelationshipsResponse', + }, +) + + +class AccountRelationship(proto.Message): + r"""The ``AccountRelationship`` message defines a formal connection + between a merchant's account and a service provider's account. This + relationship enables the provider to offer specific services to the + business, such as product management or campaign management. It + specifies the access rights and permissions to the business's data + relevant to those services. + + Establishing an account relationship involves linking the merchant's + account with a provider's account. The provider could be another + Google account (like Google Ads or Google My Business) or a + third-party platform (such as Shopify or WooCommerce). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the account relationship. + Format: ``accounts/{account}/relationships/{relationship}``. + For example, ``accounts/123456/relationships/567890``. + provider (str): + Immutable. The provider of the service. Either the reference + to an account such as ``providers/123`` or a well-known + service provider (one of ``providers/GOOGLE_ADS`` or + ``providers/GOOGLE_BUSINESS_PROFILE``). + + This field is a member of `oneof`_ ``_provider``. + provider_display_name (str): + Output only. The human-readable display name + of the provider account. + account_id_alias (str): + Optional. An optional alias you can assign to this account + relationship. This alias acts as a convenient identifier for + your own reference and management. It must be unique among + all your account relationships with the same provider. + + For example, you might use ``account_id_alias`` to assign a + friendly name to this relationship for easier identification + in your systems. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + provider: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + provider_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + account_id_alias: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAccountRelationshipRequest(proto.Message): + r"""Request to get an account relationship. + + Attributes: + name (str): + Required. The resource name of the account relationship to + get. Format: + ``accounts/{account}/relationships/{relationship}``. For + example, ``accounts/123456/relationships/567890``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAccountRelationshipRequest(proto.Message): + r"""Request message for the ``UpdateAccountRelationship`` method. + + Attributes: + account_relationship (google.shopping.merchant_accounts_v1.types.AccountRelationship): + Required. The new version of the account + relationship. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``account_id_alias`` + """ + + account_relationship: 'AccountRelationship' = proto.Field( + proto.MESSAGE, + number=1, + message='AccountRelationship', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListAccountRelationshipsRequest(proto.Message): + r"""Request to list account relationships. + + Attributes: + parent (str): + Required. The parent account of the account relationship to + filter by. Format: ``accounts/{account}`` + page_token (str): + Optional. The token returned by the previous ``list`` + request. + page_size (int): + Optional. The maximum number of elements to return in the + response. Use for paging. If no ``page_size`` is specified, + ``100`` is used as the default value. The maximum allowed + value is ``1000``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + + +class ListAccountRelationshipsResponse(proto.Message): + r"""Response after trying to list account relationships. + + Attributes: + account_relationships (MutableSequence[google.shopping.merchant_accounts_v1.types.AccountRelationship]): + The account relationships that match your + filter. + next_page_token (str): + A page token. You can send the ``page_token`` to get the + next page. Only included in the ``list`` response if there + are more pages. + """ + + @property + def raw_page(self): + return self + + account_relationships: MutableSequence['AccountRelationship'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccountRelationship', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py new file mode 100644 index 000000000000..18b283ad6fa5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py @@ -0,0 +1,429 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import accountservices +from google.shopping.merchant_accounts_v1.types import user as gsma_user +from google.type import datetime_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'Account', + 'GetAccountRequest', + 'CreateAndConfigureAccountRequest', + 'DeleteAccountRequest', + 'UpdateAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListSubAccountsRequest', + 'ListSubAccountsResponse', + }, +) + + +class Account(proto.Message): + r"""The ``Account`` message represents a business's account within + Shopping Ads. It's the primary entity for managing product data, + settings, and interactions with Google's services and external + providers. + + Accounts can operate as standalone entities or be part of a advanced + account structure. In an advanced account setup the parent account + manages multiple sub-accounts. + + Establishing an account involves configuring attributes like the + account name, time zone, and language preferences. + + The ``Account`` message is the parent entity for many other + resources, for example, ``AccountRelationship``, ``Homepage``, + ``BusinessInfo`` and so on. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the account. Format: + ``accounts/{account}`` + account_id (int): + Output only. The ID of the account. + account_name (str): + Required. A human-readable name of the account. See `store + name `__ + and `business + name `__ + for more information. + adult_content (bool): + Optional. Whether this account contains adult + content. + + This field is a member of `oneof`_ ``_adult_content``. + test_account (bool): + Output only. Whether this is a test account. + time_zone (google.type.datetime_pb2.TimeZone): + Required. The time zone of the account. + + On writes, ``time_zone`` sets both the + ``reporting_time_zone`` and the ``display_time_zone``. + + For reads, ``time_zone`` always returns the + ``display_time_zone``. If ``display_time_zone`` doesn't + exist for your account, ``time_zone`` is empty. + + The ``version`` field is not supported, won't be set in + responses and will be silently ignored if specified in + requests. + language_code (str): + Required. The account's `BCP-47 language + code `__, such as + ``en-US`` or ``sr-Latn``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account_id: int = proto.Field( + proto.INT64, + number=2, + ) + account_name: str = proto.Field( + proto.STRING, + number=3, + ) + adult_content: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + test_account: bool = proto.Field( + proto.BOOL, + number=5, + ) + time_zone: datetime_pb2.TimeZone = proto.Field( + proto.MESSAGE, + number=6, + message=datetime_pb2.TimeZone, + ) + language_code: str = proto.Field( + proto.STRING, + number=7, + ) + + +class GetAccountRequest(proto.Message): + r"""Request message for the ``GetAccount`` method. + + Attributes: + name (str): + Required. The name of the account to retrieve. Format: + ``accounts/{account}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAndConfigureAccountRequest(proto.Message): + r"""Request message for the ``CreateAndConfigureAccount`` method. + + Attributes: + account (google.shopping.merchant_accounts_v1.types.Account): + Required. The account to be created. + user (MutableSequence[google.shopping.merchant_accounts_v1.types.CreateAndConfigureAccountRequest.AddUser]): + Optional. Users to be added to the account. + service (MutableSequence[google.shopping.merchant_accounts_v1.types.CreateAndConfigureAccountRequest.AddAccountService]): + Required. An account service between the account to be + created and the provider account is initialized as part of + the creation. At least one such service needs to be + provided. Currently exactly one of these needs to be + ``account_aggregation`` and ``accounts.createAndConfigure`` + method can be used to create a sub-account under an existing + advanced account through this method. Additional + ``account_management`` or ``product_management`` services + may be provided. + """ + + class AddUser(proto.Message): + r"""Instruction for adding a user to the account during creation. + + Attributes: + user_id (str): + Required. The email address of the user (for example, + ``john.doe@gmail.com``). + user (google.shopping.merchant_accounts_v1.types.User): + Optional. Details about the user to be added. + At the moment, only access rights may be + specified. + """ + + user_id: str = proto.Field( + proto.STRING, + number=1, + ) + user: gsma_user.User = proto.Field( + proto.MESSAGE, + number=2, + message=gsma_user.User, + ) + + class AddAccountService(proto.Message): + r"""Additional instructions to add account services during + creation of the account. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + account_aggregation (google.shopping.merchant_accounts_v1.types.AccountAggregation): + The provider is an + `aggregator `__ + for the account. Payload for service type Account + Aggregation. + + This field is a member of `oneof`_ ``service_type``. + provider (str): + Required. The provider of the service. Either the reference + to an account such as ``providers/123`` or a well-known + service provider (one of ``providers/GOOGLE_ADS`` or + ``providers/GOOGLE_BUSINESS_PROFILE``). + + This field is a member of `oneof`_ ``_provider``. + """ + + account_aggregation: accountservices.AccountAggregation = proto.Field( + proto.MESSAGE, + number=103, + oneof='service_type', + message=accountservices.AccountAggregation, + ) + provider: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + account: 'Account' = proto.Field( + proto.MESSAGE, + number=1, + message='Account', + ) + user: MutableSequence[AddUser] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AddUser, + ) + service: MutableSequence[AddAccountService] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=AddAccountService, + ) + + +class DeleteAccountRequest(proto.Message): + r"""Request message for the ``DeleteAccount`` method. + + Attributes: + name (str): + Required. The name of the account to delete. Format: + ``accounts/{account}`` + force (bool): + Optional. If set to ``true``, the account is deleted even if + it provides services to other accounts or has processed + offers. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class UpdateAccountRequest(proto.Message): + r"""Request message for the ``UpdateAccount`` method. + + Attributes: + account (google.shopping.merchant_accounts_v1.types.Account): + Required. The new version of the account. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``account_name`` + - ``adult_content`` + - ``language_code`` + - ``time_zone`` + """ + + account: 'Account' = proto.Field( + proto.MESSAGE, + number=1, + message='Account', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListAccountsRequest(proto.Message): + r"""Request message for the ``accounts.list`` method. + + Attributes: + page_size (int): + Optional. The maximum number of accounts to + return. The service may return fewer than this + value. If unspecified, at most 250 accounts are + returned. The maximum value is 500; values above + 500 are coerced to 500. + page_token (str): + Optional. A page token, received from a previous + ``accounts.list`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided in the + ``accounts.list`` request must match the call that provided + the page token. + filter (str): + Optional. Returns only accounts that match the + `filter `__. + For more details, see the `filter syntax + reference `__. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAccountsResponse(proto.Message): + r"""Response message for the ``accounts.list`` method. + + Attributes: + accounts (MutableSequence[google.shopping.merchant_accounts_v1.types.Account]): + The accounts matching the ``ListAccountsRequest``. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence['Account'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Account', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSubAccountsRequest(proto.Message): + r"""Request message for the ``ListSubAccounts`` method. + + Attributes: + provider (str): + Required. The aggregation service provider. Format: + ``accounts/{accountId}`` + page_size (int): + Optional. The maximum number of accounts to + return. The service may return fewer than this + value. If unspecified, at most 250 accounts are + returned. The maximum value is 500; values above + 500 are coerced to 500. + page_token (str): + Optional. A page token, received from a previous + ``accounts.list`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided in the + ``accounts.list`` request must match the call that provided + the page token. + """ + + provider: 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 ListSubAccountsResponse(proto.Message): + r"""Response message for the ``ListSubAccounts`` method. + + Attributes: + accounts (MutableSequence[google.shopping.merchant_accounts_v1.types.Account]): + The accounts for which the given parent + account is an aggregator. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence['Account'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Account', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.py new file mode 100644 index 000000000000..57f4ff4775da --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'AccountService', + 'GetAccountServiceRequest', + 'ListAccountServicesRequest', + 'ListAccountServicesResponse', + 'ProposeAccountServiceRequest', + 'ApproveAccountServiceRequest', + 'RejectAccountServiceRequest', + 'ProductsManagement', + 'CampaignsManagement', + 'AccountManagement', + 'AccountAggregation', + 'LocalListingManagement', + 'Handshake', + }, +) + + +class AccountService(proto.Message): + r"""The ``AccountService`` message represents a specific service that a + provider account offers to a Merchant Center account. + + ``AccountService`` defines the permissions and capabilities granted + to the provider, allowing for operations such as product management + or campaign management. + + The lifecycle of an ``AccountService`` involves a proposal phase, + where one party suggests the service, and an approval phase, where + the other party accepts or rejects it. This handshake mechanism + ensures mutual consent before any access is granted. This mechanism + safeguards both parties by ensuring that access rights are granted + appropriately and that both the business and provider are aware of + the services enabled. In scenarios where a user is an admin of both + accounts, the approval can happen automatically. + + The mutability of a service is also managed through + ``AccountService``. Some services might be immutable, for example, + if they were established through other systems or APIs, and you + cannot alter them through this API. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + products_management (google.shopping.merchant_accounts_v1.types.ProductsManagement): + Service type for managing products. This + allows the provider to handle product data on + behalf of the business, including reading and + writing product listings. It's commonly used + when the provider offers inventory management or + catalog synchronization services to keep the + business's product information up-to-date across + platforms. + + This field is a member of `oneof`_ ``service_type``. + campaigns_management (google.shopping.merchant_accounts_v1.types.CampaignsManagement): + Service type for managing advertising + campaigns. Grants the provider access to create + and manage the business's ad campaigns, + including setting up campaigns, adjusting bids, + and optimizing performance. + + This field is a member of `oneof`_ ``service_type``. + account_management (google.shopping.merchant_accounts_v1.types.AccountManagement): + Service type for account management. Enables + the provider to perform administrative actions + on the business's account, such as configuring + account settings, managing users, or updating + business information. + + This field is a member of `oneof`_ ``service_type``. + account_aggregation (google.shopping.merchant_accounts_v1.types.AccountAggregation): + Service type for account aggregation. This + enables the provider, which is an advanced + account, to manage multiple sub-accounts (client + accounts). Through this service, the advanced + account provider can perform administrative and + operational tasks across all linked + sub-accounts. + + This is useful for agencies, aggregators, or + large retailers that need centralized control + over many Merchant Center accounts. + + This field is a member of `oneof`_ ``service_type``. + local_listing_management (google.shopping.merchant_accounts_v1.types.LocalListingManagement): + Service type for local listings management. + The business group associated with the external + account id will be used to provide local + inventory to this Merchant Center account. + + This field is a member of `oneof`_ ``service_type``. + name (str): + Identifier. The resource name of the account service. + Format: ``accounts/{account}/services/{service}`` + provider (str): + Output only. The provider of the service. Either the + reference to an account such as ``providers/123`` or a + well-known service provider (one of ``providers/GOOGLE_ADS`` + or ``providers/GOOGLE_BUSINESS_PROFILE``). + + This field is a member of `oneof`_ ``_provider``. + provider_display_name (str): + Output only. The human-readable display name + of the provider account. + handshake (google.shopping.merchant_accounts_v1.types.Handshake): + Output only. Information about the state of + the service in terms of establishing it (e.g. is + it pending approval or approved). + mutability (google.shopping.merchant_accounts_v1.types.AccountService.Mutability): + Output only. Whether the service is mutable + (e.g. through Approve / Reject RPCs). A service + that was created through another system or API + might be immutable. + external_account_id (str): + Immutable. An optional, immutable identifier that Google + uses to refer to this account when communicating with the + provider. This should be the unique account ID within the + provider's system (for example, your shop ID in Shopify). + + If you have multiple accounts with the same provider - for + instance, different accounts for various regions — the + ``external_account_id`` differentiates between them, + ensuring accurate linking and integration between Google and + the provider. + """ + class Mutability(proto.Enum): + r"""The list of mutability option settings a service can have. + + Values: + MUTABILITY_UNSPECIFIED (0): + Unused default value + MUTABLE (1): + The service can be mutated without + restrictions. + IMMUTABLE (2): + The service is read-only and must not be + mutated. + """ + MUTABILITY_UNSPECIFIED = 0 + MUTABLE = 1 + IMMUTABLE = 2 + + products_management: 'ProductsManagement' = proto.Field( + proto.MESSAGE, + number=100, + oneof='service_type', + message='ProductsManagement', + ) + campaigns_management: 'CampaignsManagement' = proto.Field( + proto.MESSAGE, + number=101, + oneof='service_type', + message='CampaignsManagement', + ) + account_management: 'AccountManagement' = proto.Field( + proto.MESSAGE, + number=102, + oneof='service_type', + message='AccountManagement', + ) + account_aggregation: 'AccountAggregation' = proto.Field( + proto.MESSAGE, + number=103, + oneof='service_type', + message='AccountAggregation', + ) + local_listing_management: 'LocalListingManagement' = proto.Field( + proto.MESSAGE, + number=104, + oneof='service_type', + message='LocalListingManagement', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + provider: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + provider_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + handshake: 'Handshake' = proto.Field( + proto.MESSAGE, + number=4, + message='Handshake', + ) + mutability: Mutability = proto.Field( + proto.ENUM, + number=5, + enum=Mutability, + ) + external_account_id: str = proto.Field( + proto.STRING, + number=6, + ) + + +class GetAccountServiceRequest(proto.Message): + r"""Request to get an account service. + + Attributes: + name (str): + Required. The resource name of the account service to get. + Format: ``accounts/{account}/services/{service}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAccountServicesRequest(proto.Message): + r"""Request to list account services. + + Attributes: + parent (str): + Required. The parent account of the account service to + filter by. Format: ``accounts/{account}`` + page_token (str): + Optional. The token returned by the previous ``list`` + request. + page_size (int): + Optional. The maximum number of elements to return in the + response. Use for paging. If no ``page_size`` is specified, + ``100`` is used as the default value. The maximum allowed + value is ``1000``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + page_size: int = proto.Field( + proto.INT32, + number=5, + ) + + +class ListAccountServicesResponse(proto.Message): + r"""Response after trying to list account services. + + Attributes: + account_services (MutableSequence[google.shopping.merchant_accounts_v1.types.AccountService]): + The account services that match your filter. + next_page_token (str): + A page token. You can send the ``page_token`` to get the + next page. Only included in the ``list`` response if there + are more pages. + """ + + @property + def raw_page(self): + return self + + account_services: MutableSequence['AccountService'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccountService', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProposeAccountServiceRequest(proto.Message): + r"""Request to propose an account service. + + Attributes: + parent (str): + Required. The resource name of the parent account for the + service. Format: ``accounts/{account}`` + provider (str): + Required. The provider of the service. Either the reference + to an account such as ``providers/123`` or a well-known + service provider (one of ``providers/GOOGLE_ADS`` or + ``providers/GOOGLE_BUSINESS_PROFILE``). + account_service (google.shopping.merchant_accounts_v1.types.AccountService): + Required. The account service to propose. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + provider: str = proto.Field( + proto.STRING, + number=2, + ) + account_service: 'AccountService' = proto.Field( + proto.MESSAGE, + number=4, + message='AccountService', + ) + + +class ApproveAccountServiceRequest(proto.Message): + r"""Request to approve an account service. + + Attributes: + name (str): + Required. The resource name of the account service to + approve. Format: ``accounts/{account}/services/{service}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RejectAccountServiceRequest(proto.Message): + r"""Request to reject an account service. + + Attributes: + name (str): + Required. The resource name of the account service to + reject. Format: ``accounts/{account}/services/{service}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ProductsManagement(proto.Message): + r"""``ProductsManagement`` payload. + """ + + +class CampaignsManagement(proto.Message): + r"""``CampaignManagement`` payload. + """ + + +class AccountManagement(proto.Message): + r"""``AccountManagement`` payload. + """ + + +class AccountAggregation(proto.Message): + r"""``AccountAggregation`` payload. + """ + + +class LocalListingManagement(proto.Message): + r"""``LocalListingManagement`` payload. + """ + + +class Handshake(proto.Message): + r"""The current status of establishing of the service. + (for example, pending approval or approved). + + Attributes: + approval_state (google.shopping.merchant_accounts_v1.types.Handshake.ApprovalState): + Output only. The approval state of this + handshake. + actor (google.shopping.merchant_accounts_v1.types.Handshake.Actor): + Output only. The most recent account to modify the account + service's ``approval_status``. + """ + class ApprovalState(proto.Enum): + r"""The approal state of a handshake. + + Values: + APPROVAL_STATE_UNSPECIFIED (0): + Unspecified approval status. + PENDING (1): + The service was proposed and is waiting to be + confirmed. + ESTABLISHED (2): + Both parties have confirmed the service. + REJECTED (3): + The service proposal was rejected. + """ + APPROVAL_STATE_UNSPECIFIED = 0 + PENDING = 1 + ESTABLISHED = 2 + REJECTED = 3 + + class Actor(proto.Enum): + r"""The various actors that can be involved in a handshake. + + Values: + ACTOR_UNSPECIFIED (0): + Unspecified actor. + ACCOUNT (1): + The last change was done by the account who + has this service. + OTHER_PARTY (2): + The last change was done by the other party + who this service points to. + """ + ACTOR_UNSPECIFIED = 0 + ACCOUNT = 1 + OTHER_PARTY = 2 + + approval_state: ApprovalState = proto.Field( + proto.ENUM, + number=1, + enum=ApprovalState, + ) + actor: Actor = proto.Field( + proto.ENUM, + number=2, + enum=Actor, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py new file mode 100644 index 000000000000..25b4fa8cb1d9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py @@ -0,0 +1,111 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'AutofeedSettings', + 'GetAutofeedSettingsRequest', + 'UpdateAutofeedSettingsRequest', + }, +) + + +class AutofeedSettings(proto.Message): + r"""Collection of information related to the + `autofeed `__ + settings. + + Attributes: + name (str): + Identifier. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings``. + enable_products (bool): + Required. Enables or disables product crawling through the + autofeed for the given account. Autofeed accounts must meet + `certain + conditions `__, + which can be checked through the ``eligible`` field. The + account must **not** be a marketplace. When the autofeed is + enabled for the first time, the products usually appear + instantly. When re-enabling, it might take up to 24 hours + for products to appear. + eligible (bool): + Output only. Determines whether the business + is eligible for being enrolled into an autofeed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_products: bool = proto.Field( + proto.BOOL, + number=2, + ) + eligible: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetAutofeedSettingsRequest(proto.Message): + r"""Request message for the ``GetAutofeedSettings`` method. + + Attributes: + name (str): + Required. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAutofeedSettingsRequest(proto.Message): + r"""Request message for the ``UpdateAutofeedSettings`` method. + + Attributes: + autofeed_settings (google.shopping.merchant_accounts_v1.types.AutofeedSettings): + Required. The new version of the autofeed + setting. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + autofeed_settings: 'AutofeedSettings' = proto.Field( + proto.MESSAGE, + number=1, + message='AutofeedSettings', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py new file mode 100644 index 000000000000..fde803eb73e1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py @@ -0,0 +1,386 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'AutomaticImprovements', + 'AutomaticItemUpdates', + 'AutomaticImageImprovements', + 'AutomaticShippingImprovements', + 'GetAutomaticImprovementsRequest', + 'UpdateAutomaticImprovementsRequest', + }, +) + + +class AutomaticImprovements(proto.Message): + r"""Collection of information related to the `automatic + improvements `__ + of an account. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the automatic improvements. + Format: ``accounts/{account}/automaticImprovements``. + item_updates (google.shopping.merchant_accounts_v1.types.AutomaticItemUpdates): + Turning on `item + updates `__ + allows Google to automatically update items for you. When + item updates are on, Google uses the structured data markup + on the website and advanced data extractors to update the + price and availability of the items. When the item updates + are off, items with mismatched data aren't shown. This field + is only updated (cleared) if provided in the update mask. + + This field is a member of `oneof`_ ``_item_updates``. + image_improvements (google.shopping.merchant_accounts_v1.types.AutomaticImageImprovements): + This improvement will attempt to automatically correct + submitted images if they don't meet the `image + requirements `__, + for example, removing overlays. If successful, the image + will be replaced and approved. This improvement is only + applied to images of disapproved offers. For more + information see: `Automatic image + improvements `__ + This field is only updated (cleared) if provided in the + update mask. + + This field is a member of `oneof`_ ``_image_improvements``. + shipping_improvements (google.shopping.merchant_accounts_v1.types.AutomaticShippingImprovements): + Not available for `advanced + accounts `__. + By turning on `automatic shipping + improvements `__, + you are allowing Google to improve the accuracy of your + delivery times shown to shoppers using Google. More accurate + delivery times, especially when faster, typically lead to + better conversion rates. Google will improve your estimated + delivery times based on various factors: + + - Delivery address of an order + - Current handling time and shipping time settings + - Estimated weekdays or business days + - Parcel tracking data This field is only updated (cleared) + if provided in the update mask. + + This field is a member of `oneof`_ ``_shipping_improvements``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + item_updates: 'AutomaticItemUpdates' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='AutomaticItemUpdates', + ) + image_improvements: 'AutomaticImageImprovements' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='AutomaticImageImprovements', + ) + shipping_improvements: 'AutomaticShippingImprovements' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='AutomaticShippingImprovements', + ) + + +class AutomaticItemUpdates(proto.Message): + r"""Turning on `item + updates `__ + allows Google to automatically update items for you. When item + updates are on, Google uses the structured data markup on the + website and advanced data extractors to update the price and + availability of the items. When the item updates are off, items with + mismatched data aren't shown. + + Attributes: + account_item_updates_settings (google.shopping.merchant_accounts_v1.types.AutomaticItemUpdates.ItemUpdatesAccountLevelSettings): + Optional. Determines which attributes of the + items should be automatically updated. If this + field is not present and provided in the update + mask, then the settings will be deleted. If + there are no settings for subaccount, they are + inherited from aggregator. + effective_allow_price_updates (bool): + Output only. The effective value of allow_price_updates. If + account_item_updates_settings is present, then this value is + the same. Otherwise, it represents the inherited value of + the parent account. The default value is true if no settings + are present. Read-only. + effective_allow_availability_updates (bool): + Output only. The effective value of + allow_availability_updates. If account_item_updates_settings + is present, then this value is the same. Otherwise, it + represents the inherited value of the parent account. The + default value is true if no settings are present. Read-only. + effective_allow_strict_availability_updates (bool): + Output only. The effective value of + allow_strict_availability_updates. If + account_item_updates_settings is present, then this value is + the same. Otherwise, it represents the inherited value of + the parent account. The default value is true if no settings + are present. Read-only. + effective_allow_condition_updates (bool): + Output only. The effective value of allow_condition_updates. + If account_item_updates_settings is present, then this value + is the same. Otherwise, it represents the inherited value of + the parent account. The default value is true if no settings + are present. Read-only. + """ + + class ItemUpdatesAccountLevelSettings(proto.Message): + r"""Settings for the Automatic Item Updates. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_price_updates (bool): + If price updates are enabled, Google always + updates the active price with the crawled + information. + + This field is a member of `oneof`_ ``_allow_price_updates``. + allow_availability_updates (bool): + If availability updates are enabled, any previous + availability values get overwritten if Google finds an + out-of-stock annotation on the offer's page. If additionally + ``allow_strict_availability_updates`` field is set to true, + values get overwritten if Google finds an in-stock + annotation on the offer’s page. + + This field is a member of `oneof`_ ``_allow_availability_updates``. + allow_strict_availability_updates (bool): + If ``allow_availability_updates`` is enabled, items are + automatically updated in all your Shopping target countries. + By default, availability updates will only be applied to + items that are 'out of stock' on your website but 'in stock' + on Shopping. Set this to true to also update items that are + 'in stock' on your website, but 'out of stock' on Google + Shopping. In order for this field to have an effect, you + must also set ``allow_availability_updates``. + + This field is a member of `oneof`_ ``_allow_strict_availability_updates``. + allow_condition_updates (bool): + If condition updates are enabled, Google + always updates item condition with the condition + detected from the details of your product. + + This field is a member of `oneof`_ ``_allow_condition_updates``. + """ + + allow_price_updates: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + allow_availability_updates: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + allow_strict_availability_updates: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + allow_condition_updates: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + account_item_updates_settings: ItemUpdatesAccountLevelSettings = proto.Field( + proto.MESSAGE, + number=1, + message=ItemUpdatesAccountLevelSettings, + ) + effective_allow_price_updates: bool = proto.Field( + proto.BOOL, + number=2, + ) + effective_allow_availability_updates: bool = proto.Field( + proto.BOOL, + number=3, + ) + effective_allow_strict_availability_updates: bool = proto.Field( + proto.BOOL, + number=4, + ) + effective_allow_condition_updates: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class AutomaticImageImprovements(proto.Message): + r"""This improvement will attempt to automatically correct submitted + images if they don't meet the `image + requirements `__, + for example, removing overlays. If successful, the image will be + replaced and approved. This improvement is only applied to images of + disapproved offers. For more information see: `Automatic image + improvements `__ + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + account_image_improvements_settings (google.shopping.merchant_accounts_v1.types.AutomaticImageImprovements.ImageImprovementsAccountLevelSettings): + Optional. Determines how the images should be + automatically updated. If this field is not + present and provided in the update mask, then + the settings will be deleted. If there are no + settings for subaccount, they are inherited from + aggregator. + + This field is a member of `oneof`_ ``_account_image_improvements_settings``. + effective_allow_automatic_image_improvements (bool): + Output only. The effective value of + allow_automatic_image_improvements. If + account_image_improvements_settings is present, then this + value is the same. Otherwise, it represents the inherited + value of the parent account. Read-only. + """ + + class ImageImprovementsAccountLevelSettings(proto.Message): + r"""Settings for the Automatic Image Improvements. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_automatic_image_improvements (bool): + Enables automatic image improvements. + + This field is a member of `oneof`_ ``_allow_automatic_image_improvements``. + """ + + allow_automatic_image_improvements: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + account_image_improvements_settings: ImageImprovementsAccountLevelSettings = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=ImageImprovementsAccountLevelSettings, + ) + effective_allow_automatic_image_improvements: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class AutomaticShippingImprovements(proto.Message): + r"""Not available for `advanced + accounts `__. By + turning on `automatic shipping + improvements `__, + you are allowing Google to improve the accuracy of your delivery + times shown to shoppers using Google. More accurate delivery times, + especially when faster, typically lead to better conversion rates. + Google will improve your estimated delivery times based on various + factors: + + - Delivery address of an order + - Current handling time and shipping time settings + - Estimated weekdays or business days + - Parcel tracking data + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_shipping_improvements (bool): + Enables automatic shipping improvements. + + This field is a member of `oneof`_ ``_allow_shipping_improvements``. + """ + + allow_shipping_improvements: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +class GetAutomaticImprovementsRequest(proto.Message): + r"""Request message for the ``GetAutomaticImprovements`` method. + + Attributes: + name (str): + Required. The resource name of the automatic improvements. + Format: ``accounts/{account}/automaticImprovements`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAutomaticImprovementsRequest(proto.Message): + r"""Request message for the ``UpdateAutomaticImprovements`` method. + + Attributes: + automatic_improvements (google.shopping.merchant_accounts_v1.types.AutomaticImprovements): + Required. The new version of the automatic + imrovements. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following fields + are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``item_updates`` + - ``item_updates.account_level_settings`` + - ``image_improvements`` + - ``image_improvements.account_level_settings`` + - ``shipping_improvements`` + - ``shipping_improvements.allow_shipping_improvements`` + """ + + automatic_improvements: 'AutomaticImprovements' = proto.Field( + proto.MESSAGE, + number=1, + message='AutomaticImprovements', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py new file mode 100644 index 000000000000..55adc191417b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py @@ -0,0 +1,215 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + }, +) + + +class BusinessIdentity(proto.Message): + r"""Collection of information related to the `identity of a + business `__. + + Attributes: + name (str): + Identifier. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity`` + promotions_consent (google.shopping.merchant_accounts_v1.types.BusinessIdentity.PromotionsConsent): + Required. Whether the identity attributes may + be used for promotions. + black_owned (google.shopping.merchant_accounts_v1.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being black-owned. This optional field will only be + available for businesses with the business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + women_owned (google.shopping.merchant_accounts_v1.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being women-owned. This optional field will only be + available for businesses with a business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + veteran_owned (google.shopping.merchant_accounts_v1.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being veteran-owned. This optional field will only be + available for businesses with a business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + latino_owned (google.shopping.merchant_accounts_v1.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being latino-owned. This optional field will only be + available for businesses with the business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + small_business (google.shopping.merchant_accounts_v1.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as a small business. This optional field will only be + available for businesses with a business country set to + ``US``. It is also not applicable for marketplaces. + """ + class PromotionsConsent(proto.Enum): + r"""All possible settings regarding promotions related to the + business identity. + + Values: + PROMOTIONS_CONSENT_UNSPECIFIED (0): + Default value indicating that no selection + was made. + PROMOTIONS_CONSENT_GIVEN (1): + Indicates that the account consented to + having their business identity used for + promotions. + PROMOTIONS_CONSENT_DENIED (2): + Indicates that the account did not consent to + having their business identity used for + promotions. + """ + PROMOTIONS_CONSENT_UNSPECIFIED = 0 + PROMOTIONS_CONSENT_GIVEN = 1 + PROMOTIONS_CONSENT_DENIED = 2 + + class IdentityAttribute(proto.Message): + r"""All information related to an identity attribute. + + Attributes: + identity_declaration (google.shopping.merchant_accounts_v1.types.BusinessIdentity.IdentityAttribute.IdentityDeclaration): + Required. The declaration of identity for + this attribute. + """ + class IdentityDeclaration(proto.Enum): + r"""All possible settings regarding the declaration of an + identity. + + Values: + IDENTITY_DECLARATION_UNSPECIFIED (0): + Default value indicating that no selection + was made. + SELF_IDENTIFIES_AS (1): + Indicates that the account identifies with + the attribute. + DOES_NOT_SELF_IDENTIFY_AS (2): + Indicates that the account does not identify + with the attribute. + """ + IDENTITY_DECLARATION_UNSPECIFIED = 0 + SELF_IDENTIFIES_AS = 1 + DOES_NOT_SELF_IDENTIFY_AS = 2 + + identity_declaration: 'BusinessIdentity.IdentityAttribute.IdentityDeclaration' = proto.Field( + proto.ENUM, + number=1, + enum='BusinessIdentity.IdentityAttribute.IdentityDeclaration', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + promotions_consent: PromotionsConsent = proto.Field( + proto.ENUM, + number=2, + enum=PromotionsConsent, + ) + black_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=3, + message=IdentityAttribute, + ) + women_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=4, + message=IdentityAttribute, + ) + veteran_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=5, + message=IdentityAttribute, + ) + latino_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=6, + message=IdentityAttribute, + ) + small_business: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=7, + message=IdentityAttribute, + ) + + +class GetBusinessIdentityRequest(proto.Message): + r"""Request message for the ``GetBusinessIdentity`` method. + + Attributes: + name (str): + Required. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity``. For + example, ``accounts/123456/businessIdentity``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateBusinessIdentityRequest(proto.Message): + r"""Request message for the ``UpdateBusinessIdentity`` method. + + Attributes: + business_identity (google.shopping.merchant_accounts_v1.types.BusinessIdentity): + Required. The new version of the business + identity. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``black_owned`` + - ``latino_owned`` + - ``promotions_consent`` + - ``small_business`` + - ``veteran_owned`` + - ``women_owned`` + """ + + business_identity: 'BusinessIdentity' = proto.Field( + proto.MESSAGE, + number=1, + message='BusinessIdentity', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py new file mode 100644 index 000000000000..2438cbe06be4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py @@ -0,0 +1,164 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import customerservice +from google.shopping.merchant_accounts_v1.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + }, +) + + +class BusinessInfo(proto.Message): + r"""The ``BusinessInfo`` message contains essential information about a + business. + + This message captures key business details such as physical address, + customer service contacts, and region-specific identifiers. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the business info. Format: + ``accounts/{account}/businessInfo`` + address (google.type.postal_address_pb2.PostalAddress): + Optional. The address of the business. Only ``region_code``, + ``address_lines``, ``postal_code``, ``administrative_area`` + and ``locality`` fields are supported. All other fields are + ignored. + + This field is a member of `oneof`_ ``_address``. + phone (google.type.phone_number_pb2.PhoneNumber): + Output only. The phone number of the + business. + + This field is a member of `oneof`_ ``_phone``. + phone_verification_state (google.shopping.merchant_accounts_v1.types.PhoneVerificationState): + Output only. The phone verification state of + the business. + + This field is a member of `oneof`_ ``_phone_verification_state``. + customer_service (google.shopping.merchant_accounts_v1.types.CustomerService): + Optional. The customer service of the + business. + + This field is a member of `oneof`_ ``_customer_service``. + korean_business_registration_number (str): + Optional. The 10-digit `Korean business registration + number `__ + separated with dashes in the format: XXX-XX-XXXXX. + + This field is a member of `oneof`_ ``_korean_business_registration_number``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + address: postal_address_pb2.PostalAddress = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=postal_address_pb2.PostalAddress, + ) + phone: phone_number_pb2.PhoneNumber = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=phone_number_pb2.PhoneNumber, + ) + phone_verification_state: phoneverificationstate.PhoneVerificationState = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=phoneverificationstate.PhoneVerificationState, + ) + customer_service: customerservice.CustomerService = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message=customerservice.CustomerService, + ) + korean_business_registration_number: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + +class GetBusinessInfoRequest(proto.Message): + r"""Request message for the ``GetBusinessInfo`` method. + + Attributes: + name (str): + Required. The resource name of the business info. Format: + ``accounts/{account}/businessInfo``. For example, + ``accounts/123456/businessInfo``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateBusinessInfoRequest(proto.Message): + r"""Request message for the ``UpdateBusinessInfo`` method. + + Attributes: + business_info (google.shopping.merchant_accounts_v1.types.BusinessInfo): + Required. The new version of the business + info. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``address`` + - ``customer_service`` + - ``korean_business_registration_number`` + """ + + business_info: 'BusinessInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='BusinessInfo', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py new file mode 100644 index 000000000000..9175c01b1307 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py @@ -0,0 +1,317 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'GetCheckoutSettingsRequest', + 'CreateCheckoutSettingsRequest', + 'UpdateCheckoutSettingsRequest', + 'DeleteCheckoutSettingsRequest', + 'CheckoutSettings', + 'UriSettings', + }, +) + + +class GetCheckoutSettingsRequest(proto.Message): + r"""Request message for ``GetCheckoutSettings`` method. + + Attributes: + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateCheckoutSettingsRequest(proto.Message): + r"""Request message for the ``CreateCheckoutSettings`` method. + + Attributes: + parent (str): + Required. The merchant account for which the + ``CheckoutSettings`` will be created. + checkout_settings (google.shopping.merchant_accounts_v1.types.CheckoutSettings): + Required. The ``CheckoutSettings`` object to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + checkout_settings: 'CheckoutSettings' = proto.Field( + proto.MESSAGE, + number=2, + message='CheckoutSettings', + ) + + +class UpdateCheckoutSettingsRequest(proto.Message): + r"""Request message for the ``UpdateCheckoutSettings`` method. + + Attributes: + checkout_settings (google.shopping.merchant_accounts_v1.types.CheckoutSettings): + Required. The updated version of the ``CheckoutSettings``. + The ``name`` field is used to identify the + ``CheckoutSettings``. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following fields + are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``eligible_destinations`` + - ``uri_settings`` + """ + + checkout_settings: 'CheckoutSettings' = proto.Field( + proto.MESSAGE, + number=1, + message='CheckoutSettings', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteCheckoutSettingsRequest(proto.Message): + r"""Request message for the ``DeleteCheckoutSettings`` method. + + Attributes: + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CheckoutSettings(proto.Message): + r"""`CheckoutSettings `__ + for a specific merchant. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the program configuration + settings. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + uri_settings (google.shopping.merchant_accounts_v1.types.UriSettings): + URI settings for cart or checkout URL. + + This field is a member of `oneof`_ ``_uri_settings``. + eligible_destinations (MutableSequence[google.shopping.type.types.Destination.DestinationEnum]): + Optional. The destinations (also known as `Marketing + methods `__) + to which the checkout program applies, valid destination + values are ``SHOPPING_ADS``, ``FREE_LISTINGS`` + enrollment_state (google.shopping.merchant_accounts_v1.types.CheckoutSettings.CheckoutEnrollmentState): + Output only. Reflects the merchant enrollment state in + ``Checkout`` program. + + This field is a member of `oneof`_ ``_enrollment_state``. + review_state (google.shopping.merchant_accounts_v1.types.CheckoutSettings.CheckoutReviewState): + Output only. Reflects the merchant review state in + ``Checkout`` program. This is set based on the data quality + reviews of the URL provided by the merchant. A merchant with + enrollment state as ``ENROLLED`` can be in the following + review states: ``IN_REVIEW``, ``APPROVED`` or + ``DISAPPROVED``. A merchant must be in an + ``enrollment_state`` of ``ENROLLED`` before a review can + begin for the merchant.For more details, check the help + center doc. + + This field is a member of `oneof`_ ``_review_state``. + effective_uri_settings (google.shopping.merchant_accounts_v1.types.UriSettings): + Output only. The effective value of ``uri_settings`` for a + given merchant. If account level settings are present then + this value will be a copy of url settings. Otherwise, it + will have the value of the parent account (for only + marketplace sellers). + effective_enrollment_state (google.shopping.merchant_accounts_v1.types.CheckoutSettings.CheckoutEnrollmentState): + Output only. The effective value of enrollment_state for a + given merchant ID. If account level settings are present + then this value will be a copy of the account level + settings. Otherwise, it will have the value of the parent + account (for only marketplace sellers). + + This field is a member of `oneof`_ ``_effective_enrollment_state``. + effective_review_state (google.shopping.merchant_accounts_v1.types.CheckoutSettings.CheckoutReviewState): + Output only. The effective value of ``review_state`` for a + given merchant ID. If account level settings are present + then this value will be a copy of the account level + settings. Otherwise, it will have the value of the parent + account (for only marketplace sellers). + + This field is a member of `oneof`_ ``_effective_review_state``. + """ + class CheckoutEnrollmentState(proto.Enum): + r"""Enum indicating the enrollment state of merchant in ``Checkout`` + program. + + Values: + CHECKOUT_ENROLLMENT_STATE_UNSPECIFIED (0): + Default enrollment state when enrollment + state is not specified. + INACTIVE (1): + Merchant has not enrolled into the program. + ENROLLED (2): + Merchant has enrolled into the program by + providing either an account level URL or + checkout URLs as part of their feed. + OPTED_OUT (3): + Merchant has previously enrolled but opted + out of the program. + """ + CHECKOUT_ENROLLMENT_STATE_UNSPECIFIED = 0 + INACTIVE = 1 + ENROLLED = 2 + OPTED_OUT = 3 + + class CheckoutReviewState(proto.Enum): + r"""Enum indicating the review state of merchant in ``Checkout`` + program. + + Values: + CHECKOUT_REVIEW_STATE_UNSPECIFIED (0): + Default review state when review state is not + specified. + IN_REVIEW (1): + Merchant provided URLs are being reviewed for + data quality issues. + APPROVED (2): + Merchant account has been approved. Indicates + the data quality checks have passed. + DISAPPROVED (3): + Merchant account has been disapproved due to + data quality issues. + """ + CHECKOUT_REVIEW_STATE_UNSPECIFIED = 0 + IN_REVIEW = 1 + APPROVED = 2 + DISAPPROVED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri_settings: 'UriSettings' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='UriSettings', + ) + eligible_destinations: MutableSequence[types.Destination.DestinationEnum] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=types.Destination.DestinationEnum, + ) + enrollment_state: CheckoutEnrollmentState = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum=CheckoutEnrollmentState, + ) + review_state: CheckoutReviewState = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=CheckoutReviewState, + ) + effective_uri_settings: 'UriSettings' = proto.Field( + proto.MESSAGE, + number=5, + message='UriSettings', + ) + effective_enrollment_state: CheckoutEnrollmentState = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=CheckoutEnrollmentState, + ) + effective_review_state: CheckoutReviewState = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=CheckoutReviewState, + ) + + +class UriSettings(proto.Message): + r"""URL settings for cart or checkout URL. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + checkout_uri_template (str): + Checkout URL template. When the placeholders are expanded + will redirect the buyer to the merchant checkout page with + the item in the cart. For more details, check the `help + center + doc `__ + + This field is a member of `oneof`_ ``uri_template``. + cart_uri_template (str): + Cart URL template. When the placeholders are expanded will + redirect the buyer to the cart page on the merchant website + with the selected item in cart. For more details, check the + `help center + doc `__ + + This field is a member of `oneof`_ ``uri_template``. + """ + + checkout_uri_template: str = proto.Field( + proto.STRING, + number=1, + oneof='uri_template', + ) + cart_uri_template: str = proto.Field( + proto.STRING, + number=2, + oneof='uri_template', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py new file mode 100644 index 000000000000..c34d9eab4e24 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py @@ -0,0 +1,74 @@ +# -*- 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.type import phone_number_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'CustomerService', + }, +) + + +class CustomerService(proto.Message): + r"""Customer service information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Optional. The URI where customer service may + be found. + + This field is a member of `oneof`_ ``_uri``. + email (str): + Optional. The email address where customer + service may be reached. + + This field is a member of `oneof`_ ``_email``. + phone (google.type.phone_number_pb2.PhoneNumber): + Optional. The phone number where customer + service may be called. + + This field is a member of `oneof`_ ``_phone``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + email: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + phone: phone_number_pb2.PhoneNumber = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=phone_number_pb2.PhoneNumber, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py new file mode 100644 index 000000000000..bf865ae956db --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py @@ -0,0 +1,123 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'DeveloperRegistration', + 'RegisterGcpRequest', + 'UnregisterGcpRequest', + 'GetDeveloperRegistrationRequest', + }, +) + + +class DeveloperRegistration(proto.Message): + r"""Represents a developer registration owned by a Merchant + account. + + Attributes: + name (str): + Identifier. The ``name`` (ID) of the developer registration. + Generated by the Content API upon creation of a new + ``DeveloperRegistration``. The ``account`` represents the + merchant ID of the merchant that owns the registration. + gcp_ids (MutableSequence[str]): + Output only. The GCP ids attached to this + developer registration + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + gcp_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class RegisterGcpRequest(proto.Message): + r"""Request message for the RegisterGCP method. + + Attributes: + name (str): + Required. The name of the developer registration to be + created for the merchant account that the GCP will be + registered with. Format: + ``accounts/{account}/developerRegistration`` + developer_email (str): + Immutable. If the developer email provided is + associated with a user in the merchant account + provided, the user will be updated to have "API + developer" access type and the email preference + corresponding to that user will be updated to + have the new "API notifications" preference. If + the developer email provided is not associated + with any user we will just add it as a contact. + The email preference corresponding to that + contact will have the new "API notifications" + preference + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + developer_email: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UnregisterGcpRequest(proto.Message): + r"""Request message for the UnregisterGCP method. + + Attributes: + name (str): + Required. The name of the developer registration to be + created for the merchant account that the GCP will be + registered with. Format: + ``accounts/{account}/developerRegistration`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDeveloperRegistrationRequest(proto.Message): + r"""Request message for the GetDeveloperRegistration method. + + Attributes: + name (str): + Required. The ``name`` (ID) of the developer registration. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py new file mode 100644 index 000000000000..792e2661f2f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py @@ -0,0 +1,126 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + }, +) + + +class EmailPreferences(proto.Message): + r"""The categories of notifications the user opted into / opted + out of. The email preferences do not include mandatory + announcements as users can't opt out of them. + + Attributes: + name (str): + Identifier. The name of the EmailPreferences. + The endpoint is only supported for the + authenticated user. + news_and_tips (google.shopping.merchant_accounts_v1.types.EmailPreferences.OptInState): + Optional. Updates on new features, tips and + best practices. + """ + class OptInState(proto.Enum): + r"""Opt in state of the email preference. + + Values: + OPT_IN_STATE_UNSPECIFIED (0): + Opt-in status is not specified. + OPTED_OUT (1): + User has opted out of receiving this type of + email. + OPTED_IN (2): + User has opted in to receiving this type of + email. + UNCONFIRMED (3): + User has opted in to receiving this type of + email and the confirmation email has been sent, + but user has not yet confirmed the opt in + (applies only to certain countries). + """ + OPT_IN_STATE_UNSPECIFIED = 0 + OPTED_OUT = 1 + OPTED_IN = 2 + UNCONFIRMED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + news_and_tips: OptInState = proto.Field( + proto.ENUM, + number=2, + enum=OptInState, + ) + + +class GetEmailPreferencesRequest(proto.Message): + r"""Request message for GetEmailPreferences method. + + Attributes: + name (str): + Required. The name of the ``EmailPreferences`` resource. + Format: + ``accounts/{account}/users/{email}/emailPreferences`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEmailPreferencesRequest(proto.Message): + r"""Request message for UpdateEmailPreferences method. + + Attributes: + email_preferences (google.shopping.merchant_accounts_v1.types.EmailPreferences): + Required. Email Preferences to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``news_and_tips`` + """ + + email_preferences: 'EmailPreferences' = proto.Field( + proto.MESSAGE, + number=1, + message='EmailPreferences', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py new file mode 100644 index 000000000000..0e923f851a24 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py @@ -0,0 +1,198 @@ +# -*- 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.protobuf import empty_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'GbpAccount', + 'ListGbpAccountsRequest', + 'ListGbpAccountsResponse', + 'LinkGbpAccountRequest', + 'LinkGbpAccountResponse', + }, +) + + +class GbpAccount(proto.Message): + r"""Collection of information related to a Google Business + Profile (GBP) account. + + Attributes: + name (str): + Identifier. The resource name of the GBP account. Format: + ``accounts/{account}/gbpAccount/{gbp_account}`` + gbp_account_id (str): + The id of the GBP account. + type_ (google.shopping.merchant_accounts_v1.types.GbpAccount.Type): + The type of the Business Profile. + gbp_account_name (str): + The name of the Business Profile. + For personal accounts: Email id of the owner. + For Business accounts: Name of the Business + Account. + listing_count (int): + Number of listings under this account. + """ + class Type(proto.Enum): + r"""The type of the GBP account. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + USER (1): + The GBP account is a user account. + BUSINESS_ACCOUNT (2): + The GBP account is a business account. + """ + TYPE_UNSPECIFIED = 0 + USER = 1 + BUSINESS_ACCOUNT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + gbp_account_id: str = proto.Field( + proto.STRING, + number=2, + ) + type_: Type = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + gbp_account_name: str = proto.Field( + proto.STRING, + number=5, + ) + listing_count: int = proto.Field( + proto.INT64, + number=6, + ) + + +class ListGbpAccountsRequest(proto.Message): + r"""Request message for the ListGbpAccounts method. + + Attributes: + parent (str): + Required. The name of the parent resource under which the + GBP accounts are listed. Format: ``accounts/{account}``. + page_size (int): + Optional. The maximum number of ``GbpAccount`` resources to + return. The service returns fewer than this value if the + number of gbp accounts is less that than the ``pageSize``. + The default value is 50. The maximum value is 1000; If a + value higher than the maximum is specified, then the + ``pageSize`` will default to the maximum. + page_token (str): + Optional. A page token, received from a previous + ``ListGbpAccounts`` call. Provide the page token to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListGbpAccounts`` must match the call that provided the + page token. + """ + + 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 ListGbpAccountsResponse(proto.Message): + r"""Response message for the ListGbpAccounts method. + + Attributes: + gbp_accounts (MutableSequence[google.shopping.merchant_accounts_v1.types.GbpAccount]): + The GBP accounts from the specified merchant + in the specified country. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + gbp_accounts: MutableSequence['GbpAccount'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GbpAccount', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkGbpAccountRequest(proto.Message): + r"""Request message for the LinkGbpAccount method. + + Attributes: + parent (str): + Required. The name of the parent resource to which the GBP + account is linked. Format: ``accounts/{account}``. + gbp_email (str): + Required. The email address of the Business + Profile account. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + gbp_email: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkGbpAccountResponse(proto.Message): + r"""Response message for the LinkGbpAccount method. + + Attributes: + response (google.protobuf.empty_pb2.Empty): + Empty response. + """ + + response: empty_pb2.Empty = proto.Field( + proto.MESSAGE, + number=1, + message=empty_pb2.Empty, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py new file mode 100644 index 000000000000..d83372bb01da --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py @@ -0,0 +1,163 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'Homepage', + 'GetHomepageRequest', + 'UpdateHomepageRequest', + 'ClaimHomepageRequest', + 'UnclaimHomepageRequest', + }, +) + + +class Homepage(proto.Message): + r"""The ``Homepage`` message represents a business's store homepage + within the system. + + A business's homepage is the primary domain where customers interact + with their store. + + The homepage can be claimed and verified as a proof of ownership and + allows the business to unlock features that require a verified + website. For more information, see `Understanding online store URL + verification `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the store's homepage. + Format: ``accounts/{account}/homepage`` + uri (str): + Required. The URI (typically a URL) of the + store's homepage. + + This field is a member of `oneof`_ ``_uri``. + claimed (bool): + Output only. Whether the homepage is claimed. + See + https://support.google.com/merchants/answer/176793. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + claimed: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetHomepageRequest(proto.Message): + r"""Request message for the ``GetHomepage`` method. + + Attributes: + name (str): + Required. The name of the homepage to retrieve. Format: + ``accounts/{account}/homepage`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateHomepageRequest(proto.Message): + r"""Request message for the ``UpdateHomepage`` method. + + Attributes: + homepage (google.shopping.merchant_accounts_v1.types.Homepage): + Required. The new version of the homepage. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``uri`` + """ + + homepage: 'Homepage' = proto.Field( + proto.MESSAGE, + number=1, + message='Homepage', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ClaimHomepageRequest(proto.Message): + r"""Request message for the ``ClaimHomepage`` method. + + Attributes: + name (str): + Required. The name of the homepage to claim. Format: + ``accounts/{account}/homepage`` + overwrite (bool): + Optional. When set to ``true``, this option removes any + existing claim on the requested website from any other + account to the account making the request, effectively + replacing the previous claim. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + overwrite: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class UnclaimHomepageRequest(proto.Message): + r"""Request message for the ``UnclaimHomepage`` method. + + Attributes: + name (str): + Required. The name of the homepage to unclaim. Format: + ``accounts/{account}/homepage`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py new file mode 100644 index 000000000000..221b564d97bf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py @@ -0,0 +1,172 @@ +# -*- 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.protobuf import empty_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'LfpProvider', + 'FindLfpProvidersRequest', + 'FindLfpProvidersResponse', + 'LinkLfpProviderRequest', + 'LinkLfpProviderResponse', + }, +) + + +class LfpProvider(proto.Message): + r"""Collection of information related to a Local Feed Partnership + (LFP) provider. + + Attributes: + name (str): + Identifier. The resource name of the LFP provider. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}`` + region_code (str): + Output only. Region code defined by + `CLDR `__. + display_name (str): + The display name of the LFP provider. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class FindLfpProvidersRequest(proto.Message): + r"""Request message for the FindLfpProviders method. + + Attributes: + parent (str): + Required. The name of the parent resource under which the + LFP providers are found. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. + page_size (int): + Optional. The maximum number of ``LfpProvider`` resources to + return. The service returns fewer than this value if the + number of lfp providers is less that than the ``pageSize``. + The default value is 50. The maximum value is 1000; If a + value higher than the maximum is specified, then the + ``pageSize`` will default to the maximum. + page_token (str): + Optional. A page token, received from a previous + ``FindLfpProviders`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``FindLfpProviders`` must match the call that provided the + page token. + """ + + 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 FindLfpProvidersResponse(proto.Message): + r"""Response message for the FindLfpProviders method. + + Attributes: + lfp_providers (MutableSequence[google.shopping.merchant_accounts_v1.types.LfpProvider]): + The LFP providers from the specified merchant + in the specified country. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + lfp_providers: MutableSequence['LfpProvider'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LfpProvider', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkLfpProviderRequest(proto.Message): + r"""Request message for the LinkLfpProvider method. + + Attributes: + name (str): + Required. The name of the LFP provider resource to link. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. + The ``lfp_provider`` is the LFP provider ID. + external_account_id (str): + Required. The external account ID by which + this merchant is known to the LFP provider. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + external_account_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkLfpProviderResponse(proto.Message): + r"""Response message for the LinkLfpProvider method. + + Attributes: + response (google.protobuf.empty_pb2.Empty): + Empty response. + """ + + response: empty_pb2.Empty = proto.Field( + proto.MESSAGE, + number=1, + message=empty_pb2.Empty, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py new file mode 100644 index 000000000000..85ec2ef18d8e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py @@ -0,0 +1,548 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'OmnichannelSetting', + 'ReviewState', + 'InStock', + 'Pickup', + 'LfpLink', + 'OnDisplayToOrder', + 'About', + 'InventoryVerification', + 'GetOmnichannelSettingRequest', + 'ListOmnichannelSettingsRequest', + 'ListOmnichannelSettingsResponse', + 'CreateOmnichannelSettingRequest', + 'UpdateOmnichannelSettingRequest', + 'RequestInventoryVerificationRequest', + 'RequestInventoryVerificationResponse', + }, +) + + +class OmnichannelSetting(proto.Message): + r"""Collection of information related to the omnichannel settings + of a merchant. + + Attributes: + name (str): + Identifier. The resource name of the omnichannel setting. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + region_code (str): + Required. Immutable. Region code defined by + `CLDR `__. Must be provided in + the Create method, and is immutable. + lsf_type (google.shopping.merchant_accounts_v1.types.OmnichannelSetting.LsfType): + Required. The Local Store Front type for this + country. + in_stock (google.shopping.merchant_accounts_v1.types.InStock): + Optional. The InStock URI and state for this + country. + pickup (google.shopping.merchant_accounts_v1.types.Pickup): + Optional. The Pickup URI and state for this + country. + lfp_link (google.shopping.merchant_accounts_v1.types.LfpLink): + Output only. The established link to a LFP + provider. + odo (google.shopping.merchant_accounts_v1.types.OnDisplayToOrder): + Optional. The On Display to Order (ODO) + policy URI and state for this country. + about (google.shopping.merchant_accounts_v1.types.About): + Optional. The about page URI and state for + this country. + inventory_verification (google.shopping.merchant_accounts_v1.types.InventoryVerification): + Optional. The inventory verification contact + and state for this country. + """ + class LsfType(proto.Enum): + r"""The product page experience type, which is also called the Local + Store Front (LSF) type. Check the `HC + article `__ for + more details. + + Values: + LSF_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + GHLSF (1): + Google-Hosted Local Store Front. Check the `HC + article `__ + for more details. + MHLSF_BASIC (2): + Merchant-Hosted Local Store Front Basic. Check the `HC + article `__ + for more details. + MHLSF_FULL (3): + Merchant-Hosted Local Store Front Full. Check the `HC + article `__ + for more details. + """ + LSF_TYPE_UNSPECIFIED = 0 + GHLSF = 1 + MHLSF_BASIC = 2 + MHLSF_FULL = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + lsf_type: LsfType = proto.Field( + proto.ENUM, + number=12, + enum=LsfType, + ) + in_stock: 'InStock' = proto.Field( + proto.MESSAGE, + number=13, + message='InStock', + ) + pickup: 'Pickup' = proto.Field( + proto.MESSAGE, + number=14, + message='Pickup', + ) + lfp_link: 'LfpLink' = proto.Field( + proto.MESSAGE, + number=5, + message='LfpLink', + ) + odo: 'OnDisplayToOrder' = proto.Field( + proto.MESSAGE, + number=6, + message='OnDisplayToOrder', + ) + about: 'About' = proto.Field( + proto.MESSAGE, + number=7, + message='About', + ) + inventory_verification: 'InventoryVerification' = proto.Field( + proto.MESSAGE, + number=8, + message='InventoryVerification', + ) + + +class ReviewState(proto.Message): + r"""The state of a omnichannel setting related review process. + """ + class State(proto.Enum): + r"""The state of the review process. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The review process has concluded + successfully. The reviewed item is active. + FAILED (2): + The review process failed. + RUNNING (3): + The review process is running. + ACTION_REQUIRED (4): + The review process is waiting for the + merchant to take action. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + FAILED = 2 + RUNNING = 3 + ACTION_REQUIRED = 4 + + +class InStock(proto.Message): + r"""Collection of information related to InStock. + + Attributes: + uri (str): + Optional. Product landing page URI. It is only used for the + review of MHLSF in-stock serving. This URI domain should + match with the business's homepage. Required to be empty if + the lsf_type is GHLSF, and required when the lsf_type is + MHLSF_FULL or MHLSF_BASIC. + state (google.shopping.merchant_accounts_v1.types.ReviewState.State): + Output only. The state of the in-stock + serving. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class Pickup(proto.Message): + r"""Collection of information related to Pickup. + + Attributes: + uri (str): + Required. Pickup product page URI. It is only + used for the review of pickup serving. This URI + domain should match with the business's + homepage. + state (google.shopping.merchant_accounts_v1.types.ReviewState.State): + Output only. The state of the pickup serving. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class LfpLink(proto.Message): + r"""Collection of information related to the LFP link. + + Attributes: + lfp_provider (str): + Required. The resource name of the LFP provider. Format: + ``lfpProviders/{lfp_provider}`` + external_account_id (str): + Required. The account ID by which this + merchant is known to the LFP provider. + state (google.shopping.merchant_accounts_v1.types.ReviewState.State): + Output only. The state of the LFP link. + """ + + lfp_provider: str = proto.Field( + proto.STRING, + number=1, + ) + external_account_id: str = proto.Field( + proto.STRING, + number=2, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=3, + enum='ReviewState.State', + ) + + +class OnDisplayToOrder(proto.Message): + r"""Collection of information related to the on display to order + (`ODO `__). + + Attributes: + uri (str): + Required. The on display to order (ODO) + policy URI. + state (google.shopping.merchant_accounts_v1.types.ReviewState.State): + Output only. The state of the URI. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class About(proto.Message): + r"""Collection of information related to the about page + (`impressum `__). + + Attributes: + uri (str): + Required. The about page URI. + state (google.shopping.merchant_accounts_v1.types.ReviewState.State): + Output only. The state of the URI. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class InventoryVerification(proto.Message): + r"""Collection of information related to `inventory + verification `__. + + Attributes: + state (google.shopping.merchant_accounts_v1.types.InventoryVerification.State): + Output only. The state of the inventory + verification process. + contact (str): + Required. The name of the contact for the + inventory verification process. + contact_email (str): + Required. The email address of the contact + for the inventory verification process. + contact_state (google.shopping.merchant_accounts_v1.types.ReviewState.State): + Output only. The state of the contact + verification. + """ + class State(proto.Enum): + r"""The state of the `inventory + verification `__ + process. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTION_REQUIRED (1): + When the merchant needs to initiate the + inventory verification process. The next state + is INACTIVE. + INACTIVE (5): + When the merchant is ready to request + inventory verification. + RUNNING (2): + The inventory verification process is + running. If the merchant is rejected, the next + state is INACTIVE. + SUCCEEDED (3): + The inventory verification process succeeded. + SUSPENDED (4): + When merchant fails the inventory + verification process and all attempts are + exhausted. + """ + STATE_UNSPECIFIED = 0 + ACTION_REQUIRED = 1 + INACTIVE = 5 + RUNNING = 2 + SUCCEEDED = 3 + SUSPENDED = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + contact: str = proto.Field( + proto.STRING, + number=2, + ) + contact_email: str = proto.Field( + proto.STRING, + number=3, + ) + contact_state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=4, + enum='ReviewState.State', + ) + + +class GetOmnichannelSettingRequest(proto.Message): + r"""Request message for the GetOmnichannelSettings method. + + Attributes: + name (str): + Required. The name of the omnichannel setting to retrieve. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOmnichannelSettingsRequest(proto.Message): + r"""Request message for the ListOmnichannelSettings method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + omnichannel settings. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of omnichannel + settings to return. The service may return fewer + than this value. If unspecified, at most 50 + omnichannel settings will be returned. The + maximum value is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListOmnichannelSettings`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListOmnichannelSettings`` must match the call that + provided the page token. + """ + + 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 ListOmnichannelSettingsResponse(proto.Message): + r"""Response message for the ListOmnichannelSettings method. + + Attributes: + omnichannel_settings (MutableSequence[google.shopping.merchant_accounts_v1.types.OmnichannelSetting]): + The omnichannel settings from the specified + merchant. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + omnichannel_settings: MutableSequence['OmnichannelSetting'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OmnichannelSetting', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateOmnichannelSettingRequest(proto.Message): + r"""Request message for the CreateOmnichannelSetting method. + + Attributes: + parent (str): + Required. The parent resource where this omnichannel setting + will be created. Format: ``accounts/{account}`` + omnichannel_setting (google.shopping.merchant_accounts_v1.types.OmnichannelSetting): + Required. The omnichannel setting to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + omnichannel_setting: 'OmnichannelSetting' = proto.Field( + proto.MESSAGE, + number=2, + message='OmnichannelSetting', + ) + + +class UpdateOmnichannelSettingRequest(proto.Message): + r"""Request message for the UpdateOmnichannelSetting method. + + Attributes: + omnichannel_setting (google.shopping.merchant_accounts_v1.types.OmnichannelSetting): + Required. The omnichannel setting to update. + + The omnichannel setting's ``name`` field is used to identify + the omnichannel setting to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + + The following fields are supported in snake_case only: + + - ``lsf_type`` + - ``in_stock`` + - ``pickup`` + - ``odo`` + - ``about`` + - ``inventory_verification`` + + Full replacement with wildcard ``*``\ is supported, while + empty/implied update mask is not. + """ + + omnichannel_setting: 'OmnichannelSetting' = proto.Field( + proto.MESSAGE, + number=1, + message='OmnichannelSetting', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class RequestInventoryVerificationRequest(proto.Message): + r"""Request message for the RequestInventoryVerification method. + + Attributes: + name (str): + Required. The name of the omnichannel setting to request + inventory verification. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RequestInventoryVerificationResponse(proto.Message): + r"""Response message for the RequestInventoryVerification method. + + Attributes: + omnichannel_setting (google.shopping.merchant_accounts_v1.types.OmnichannelSetting): + The omnichannel setting that was updated. + """ + + omnichannel_setting: 'OmnichannelSetting' = proto.Field( + proto.MESSAGE, + number=1, + message='OmnichannelSetting', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py new file mode 100644 index 000000000000..d5a0f2c452f0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py @@ -0,0 +1,541 @@ +# -*- 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 date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'GetOnlineReturnPolicyRequest', + 'CreateOnlineReturnPolicyRequest', + 'DeleteOnlineReturnPolicyRequest', + 'ListOnlineReturnPoliciesRequest', + 'ListOnlineReturnPoliciesResponse', + 'OnlineReturnPolicy', + }, +) + + +class GetOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``GetOnlineReturnPolicy`` method. + + Attributes: + name (str): + Required. The name of the return policy to retrieve. Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``CreateOnlineReturnPolicy`` method. + + Attributes: + parent (str): + Required. The Merchant Center account for which the return + policy will be created. Format: ``accounts/{account}`` + online_return_policy (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy): + Required. The return policy object to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + online_return_policy: 'OnlineReturnPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='OnlineReturnPolicy', + ) + + +class DeleteOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``DeleteOnlineReturnPolicy`` method. + + Attributes: + name (str): + Required. The name of the return policy to delete. Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOnlineReturnPoliciesRequest(proto.Message): + r"""Request message for the ``ListOnlineReturnPolicies`` method. + + Attributes: + parent (str): + Required. The Merchant Center account for which to list + return policies. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of ``OnlineReturnPolicy`` + resources to return. The service returns fewer than this + value if the number of return policies for the given + business is less that than the ``pageSize``. The default + value is 10. The maximum value is 100; If a value higher + than the maximum is specified, then the ``pageSize`` will + default to the maximum + page_token (str): + Optional. A page token, received from a previous + ``ListOnlineReturnPolicies`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListOnlineReturnPolicies`` must match the call that + provided the page token. The token returned as + [nextPageToken][google.shopping.merchant.accounts.v1.ListOnlineReturnPoliciesResponse.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 ListOnlineReturnPoliciesResponse(proto.Message): + r"""Response message for the ``ListOnlineReturnPolicies`` method. + + Attributes: + online_return_policies (MutableSequence[google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy]): + The retrieved return policies. + 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 + + online_return_policies: MutableSequence['OnlineReturnPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OnlineReturnPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OnlineReturnPolicy(proto.Message): + r"""`Online return + policy `__ + object. This is currently used to represent return policies for ads + and free listings programs. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The name of the ``OnlineReturnPolicy`` resource. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + return_policy_id (str): + Output only. Return policy ID generated by + Google. + label (str): + Optional. Immutable. This field represents the unique + user-defined label of the return policy for the given + country. It is important to note that the same label cannot + be used in different return policies for the same country. + If not given, policies will be automatically treated as the + 'default' for the country. When using label, you are + creating an exception policy in that country to assign a + custom return policy to certain product groups, follow the + instructions provided in the [Return policy label] + (https://support.google.com/merchants/answer/9445425). The + label can contain up to 50 characters. + countries (MutableSequence[str]): + Required. Immutable. The countries of sale + where the return policy applies. The values must + be a valid 2 letter ISO 3166 code. + policy (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.Policy): + Optional. The return policy. + seasonal_overrides (MutableSequence[google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.SeasonalOverride]): + Optional. Overrides to the general policy for + orders placed during a specific set of time + intervals. + restocking_fee (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.RestockingFee): + Optional. The restocking fee that applies to + all return reason categories. This would be + treated as a free restocking fee if the value is + not set. + return_methods (MutableSequence[google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.ReturnMethod]): + Optional. The return methods of how customers + can return an item. This value is required to + not be empty unless the type of return policy is + noReturns. + item_conditions (MutableSequence[google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.ItemCondition]): + Optional. The item conditions accepted for + returns must not be empty unless the type of + return policy is 'noReturns'. + return_shipping_fee (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.ReturnShippingFee): + Optional. The return shipping fee. Should be + set only when customer need to download and + print the return label. + return_policy_uri (str): + Required. The return policy uri. This can + used by Google to do a sanity check for the + policy. It must be a valid URL. + accept_defective_only (bool): + Optional. This field specifies if business + only accepts defective products for returns. + + This field is a member of `oneof`_ ``_accept_defective_only``. + process_refund_days (int): + Optional. The field specifies the number of + days it takes for business to process refunds. + + This field is a member of `oneof`_ ``_process_refund_days``. + accept_exchange (bool): + Optional. This field specifies if business + allows customers to exchange products. + + This field is a member of `oneof`_ ``_accept_exchange``. + return_label_source (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.ReturnLabelSource): + Optional. The field specifies the return + label source. + + This field is a member of `oneof`_ ``_return_label_source``. + """ + class ReturnMethod(proto.Enum): + r"""The available return methods. + + Values: + RETURN_METHOD_UNSPECIFIED (0): + Default value. This value is unused. + BY_MAIL (1): + Return by mail. + IN_STORE (2): + Return in store. + AT_A_KIOSK (3): + Return at a kiosk. + """ + RETURN_METHOD_UNSPECIFIED = 0 + BY_MAIL = 1 + IN_STORE = 2 + AT_A_KIOSK = 3 + + class ItemCondition(proto.Enum): + r"""The available item conditions. + + Values: + ITEM_CONDITION_UNSPECIFIED (0): + Default value. This value is unused. + NEW (1): + New. + USED (2): + Used. + """ + ITEM_CONDITION_UNSPECIFIED = 0 + NEW = 1 + USED = 2 + + class ReturnLabelSource(proto.Enum): + r"""The available return label sources. + + Values: + RETURN_LABEL_SOURCE_UNSPECIFIED (0): + Default value. This value is unused. + DOWNLOAD_AND_PRINT (1): + Download and print. + IN_THE_PACKAGE (2): + Label include in the package. + CUSTOMER_RESPONSIBILITY (3): + Customer to provide. + """ + RETURN_LABEL_SOURCE_UNSPECIFIED = 0 + DOWNLOAD_AND_PRINT = 1 + IN_THE_PACKAGE = 2 + CUSTOMER_RESPONSIBILITY = 3 + + class ReturnShippingFee(proto.Message): + r"""The return shipping fee. This can either be a fixed fee or a + boolean to indicate that the customer pays the actual shipping + cost. + + Attributes: + type_ (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.ReturnShippingFee.Type): + Required. Type of return shipping fee. + fixed_fee (google.shopping.type.types.Price): + Fixed return shipping fee amount. This value is only + applicable when type is ``FIXED``. We will treat the return + shipping fee as free if type is ``FIXED`` and this value is + not set. + """ + class Type(proto.Enum): + r"""Return shipping fee types. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + FIXED (1): + The return shipping fee is a fixed value. + CUSTOMER_PAYING_ACTUAL_FEE (2): + Customers will pay the actual return shipping + fee. + """ + TYPE_UNSPECIFIED = 0 + FIXED = 1 + CUSTOMER_PAYING_ACTUAL_FEE = 2 + + type_: 'OnlineReturnPolicy.ReturnShippingFee.Type' = proto.Field( + proto.ENUM, + number=1, + enum='OnlineReturnPolicy.ReturnShippingFee.Type', + ) + fixed_fee: types.Price = proto.Field( + proto.MESSAGE, + number=2, + message=types.Price, + ) + + class RestockingFee(proto.Message): + r"""The restocking fee. This can be a flat fee or a micro + percent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + fixed_fee (google.shopping.type.types.Price): + Fixed restocking fee. + + This field is a member of `oneof`_ ``type``. + micro_percent (int): + Percent of total price in micros. 15,000,000 + means 15% of the total price would be charged. + + This field is a member of `oneof`_ ``type``. + """ + + fixed_fee: types.Price = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=types.Price, + ) + micro_percent: int = proto.Field( + proto.INT32, + number=2, + oneof='type', + ) + + class Policy(proto.Message): + r"""The available policies. + + Attributes: + type_ (google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy.Policy.Type): + Policy type. + days (int): + The number of days items can be returned after delivery, + where one day is defined as 24 hours after the delivery + timestamp. Required for ``NUMBER_OF_DAYS_AFTER_DELIVERY`` + returns. + """ + class Type(proto.Enum): + r"""Return policy types. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + NUMBER_OF_DAYS_AFTER_DELIVERY (1): + The number of days within which a return is + valid after delivery. + NO_RETURNS (2): + No returns. + LIFETIME_RETURNS (3): + Life time returns. + """ + TYPE_UNSPECIFIED = 0 + NUMBER_OF_DAYS_AFTER_DELIVERY = 1 + NO_RETURNS = 2 + LIFETIME_RETURNS = 3 + + type_: 'OnlineReturnPolicy.Policy.Type' = proto.Field( + proto.ENUM, + number=1, + enum='OnlineReturnPolicy.Policy.Type', + ) + days: int = proto.Field( + proto.INT64, + number=2, + ) + + class SeasonalOverride(proto.Message): + r""" + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + return_days (int): + Number of days (from the delivery date) that + the product can be returned. + + This field is a member of `oneof`_ ``return_window``. + return_until_date (google.type.date_pb2.Date): + Fixed end date until which the product can be + returned. + + This field is a member of `oneof`_ ``return_window``. + label (str): + Required. Display name of this seasonal + override in Merchant Center. + start_date (google.type.date_pb2.Date): + Required. Defines the date range when this seasonal override + applies. Both start_date and end_date are inclusive. The + dates of the seasonal overrides should not overlap. + end_date (google.type.date_pb2.Date): + Required. seasonal override end date + (inclusive). + """ + + return_days: int = proto.Field( + proto.INT32, + number=5, + oneof='return_window', + ) + return_until_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=6, + oneof='return_window', + message=date_pb2.Date, + ) + label: str = proto.Field( + proto.STRING, + number=1, + ) + start_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + end_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + return_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + label: str = proto.Field( + proto.STRING, + number=3, + ) + countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + policy: Policy = proto.Field( + proto.MESSAGE, + number=5, + message=Policy, + ) + seasonal_overrides: MutableSequence[SeasonalOverride] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=SeasonalOverride, + ) + restocking_fee: RestockingFee = proto.Field( + proto.MESSAGE, + number=6, + message=RestockingFee, + ) + return_methods: MutableSequence[ReturnMethod] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=ReturnMethod, + ) + item_conditions: MutableSequence[ItemCondition] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ItemCondition, + ) + return_shipping_fee: ReturnShippingFee = proto.Field( + proto.MESSAGE, + number=9, + message=ReturnShippingFee, + ) + return_policy_uri: str = proto.Field( + proto.STRING, + number=10, + ) + accept_defective_only: bool = proto.Field( + proto.BOOL, + number=11, + optional=True, + ) + process_refund_days: int = proto.Field( + proto.INT32, + number=12, + optional=True, + ) + accept_exchange: bool = proto.Field( + proto.BOOL, + number=13, + optional=True, + ) + return_label_source: ReturnLabelSource = proto.Field( + proto.ENUM, + number=15, + optional=True, + enum=ReturnLabelSource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py new file mode 100644 index 000000000000..46605ab3ba80 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py @@ -0,0 +1,47 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'PhoneVerificationState', + }, +) + + +class PhoneVerificationState(proto.Enum): + r"""The phone verification state. + + Values: + PHONE_VERIFICATION_STATE_UNSPECIFIED (0): + Default value. This value is unused. + PHONE_VERIFICATION_STATE_VERIFIED (1): + The phone is verified. + PHONE_VERIFICATION_STATE_UNVERIFIED (2): + The phone is unverified. + """ + PHONE_VERIFICATION_STATE_UNSPECIFIED = 0 + PHONE_VERIFICATION_STATE_VERIFIED = 1 + PHONE_VERIFICATION_STATE_UNVERIFIED = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py new file mode 100644 index 000000000000..cbe5f7f7f447 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py @@ -0,0 +1,264 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'Program', + 'GetProgramRequest', + 'ListProgramsRequest', + 'ListProgramsResponse', + 'EnableProgramRequest', + 'DisableProgramRequest', + }, +) + + +class Program(proto.Message): + r"""Defines participation in a given program for the specified account. + + Programs provide a mechanism for adding functionality to a Merchant + Center accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a business's store to be shown + across Google for free. + + The following list is the available set of program resource IDs + accessible through the API: + + - ``free-listings`` + - ``shopping-ads`` + - ``youtube-shopping-checkout`` + + Attributes: + name (str): + Identifier. The resource name of the program. Format: + ``accounts/{account}/programs/{program}`` + documentation_uri (str): + Output only. The URL of a Merchant Center + help page describing the program. + state (google.shopping.merchant_accounts_v1.types.Program.State): + Output only. The participation state of the + account in the program. + active_region_codes (MutableSequence[str]): + Output only. The regions in which the account is actively + participating in the program. Active regions are defined as + those where all program requirements affecting the regions + have been met. + + Region codes are defined by + `CLDR `__. This is either a + country where the program applies specifically to that + country or ``001`` when the program applies globally. + unmet_requirements (MutableSequence[google.shopping.merchant_accounts_v1.types.Program.Requirement]): + Output only. The requirements that the + account has not yet satisfied that are affecting + participation in the program. + """ + class State(proto.Enum): + r"""Possible program participation states for the account. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + NOT_ELIGIBLE (1): + The account is not eligible to participate in + the program. + ELIGIBLE (2): + The account is eligible to participate in the + program. + ENABLED (3): + The program is enabled for the account. + """ + STATE_UNSPECIFIED = 0 + NOT_ELIGIBLE = 1 + ELIGIBLE = 2 + ENABLED = 3 + + class Requirement(proto.Message): + r"""Defines a requirement specified for participation in the + program. + + Attributes: + title (str): + Output only. Name of the requirement. + documentation_uri (str): + Output only. The URL of a help page + describing the requirement. + affected_region_codes (MutableSequence[str]): + Output only. The regions that are currently affected by this + requirement not being met. + + Region codes are defined by + `CLDR `__. This is either a + country where the program applies specifically to that + country or ``001`` when the program applies globally. + """ + + title: str = proto.Field( + proto.STRING, + number=1, + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=2, + ) + affected_region_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + active_region_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + unmet_requirements: MutableSequence[Requirement] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Requirement, + ) + + +class GetProgramRequest(proto.Message): + r"""Request message for the GetProgram method. + + Attributes: + name (str): + Required. The name of the program to retrieve. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProgramsRequest(proto.Message): + r"""Request message for the ListPrograms method. + + Attributes: + parent (str): + Required. The name of the account for which to retrieve all + programs. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of programs to + return in a single response. If unspecified (or + 0), a default size of 1000 is used. The maximum + value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + Optional. A continuation token, received from a previous + ``ListPrograms`` call. Provide this to retrieve the next + page. + """ + + 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 ListProgramsResponse(proto.Message): + r"""Response message for the ListPrograms method. + + Attributes: + programs (MutableSequence[google.shopping.merchant_accounts_v1.types.Program]): + The programs for the given account. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + programs: MutableSequence['Program'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Program', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class EnableProgramRequest(proto.Message): + r"""Request message for the EnableProgram method. + + Attributes: + name (str): + Required. The name of the program for which to enable + participation for the given account. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableProgramRequest(proto.Message): + r"""Request message for the DisableProgram method. + + Attributes: + name (str): + Required. The name of the program for which to disable + participation for the given account. Format: + ``accounts/{account}/programs/{program}``. For example, + ``accounts/123456/programs/free-listings``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py new file mode 100644 index 000000000000..64e05a85b688 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py @@ -0,0 +1,323 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'GetRegionRequest', + 'CreateRegionRequest', + 'UpdateRegionRequest', + 'DeleteRegionRequest', + 'ListRegionsRequest', + 'ListRegionsResponse', + 'Region', + }, +) + + +class GetRegionRequest(proto.Message): + r"""Request message for the ``GetRegion`` method. + + Attributes: + name (str): + Required. The name of the region to retrieve. Format: + ``accounts/{account}/regions/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateRegionRequest(proto.Message): + r"""Request message for the ``CreateRegion`` method. + + Attributes: + parent (str): + Required. The account to create a region for. Format: + ``accounts/{account}`` + region_id (str): + Required. The identifier for the region, + unique over all regions of the same account. + region (google.shopping.merchant_accounts_v1.types.Region): + Required. The region to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + region_id: str = proto.Field( + proto.STRING, + number=2, + ) + region: 'Region' = proto.Field( + proto.MESSAGE, + number=3, + message='Region', + ) + + +class UpdateRegionRequest(proto.Message): + r"""Request message for the ``UpdateRegion`` method. + + Attributes: + region (google.shopping.merchant_accounts_v1.types.Region): + Required. The updated region. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The comma-separated field mask indicating the + fields to update. Example: + ``"displayName,postalCodeArea.regionCode"``. + """ + + region: 'Region' = proto.Field( + proto.MESSAGE, + number=1, + message='Region', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteRegionRequest(proto.Message): + r"""Request message for the ``DeleteRegion`` method. + + Attributes: + name (str): + Required. The name of the region to delete. Format: + ``accounts/{account}/regions/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRegionsRequest(proto.Message): + r"""Request message for the ``ListRegions`` method. + + Attributes: + parent (str): + Required. The account to list regions for. Format: + ``accounts/{account}`` + page_size (int): + Optional. The maximum number of regions to + return. The service may return fewer than this + value. If unspecified, at most 50 regions will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListRegions`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListRegions`` must match the call that provided the page + token. + """ + + 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 ListRegionsResponse(proto.Message): + r"""Response message for the ``ListRegions`` method. + + Attributes: + regions (MutableSequence[google.shopping.merchant_accounts_v1.types.Region]): + The regions from the specified business. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + regions: MutableSequence['Region'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Region', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Region(proto.Message): + r"""Represents a geographic region that you can use as a target with + both the ``RegionalInventory`` and ``ShippingSettings`` services. + You can define regions as collections of either postal codes or, in + some countries, using predefined geotargets. For more information, + see `Set up + regions `__ + for more information. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the region. Format: + ``accounts/{account}/regions/{region}`` + display_name (str): + Optional. The display name of the region. + + This field is a member of `oneof`_ ``_display_name``. + postal_code_area (google.shopping.merchant_accounts_v1.types.Region.PostalCodeArea): + Optional. A list of postal codes that defines + the region area. + geotarget_area (google.shopping.merchant_accounts_v1.types.Region.GeoTargetArea): + Optional. A list of geotargets that defines + the region area. + regional_inventory_eligible (google.protobuf.wrappers_pb2.BoolValue): + Output only. Indicates if the region is + eligible for use in the Regional Inventory + configuration. + shipping_eligible (google.protobuf.wrappers_pb2.BoolValue): + Output only. Indicates if the region is + eligible for use in the Shipping Services + configuration. + """ + + class PostalCodeArea(proto.Message): + r"""A list of postal codes that defines the region area. Note: All + regions defined using postal codes are accessible through the + account's ``ShippingSettings.postalCodeGroups`` resource. + + Attributes: + region_code (str): + Required. `CLDR territory + code `__ + or the country the postal code group applies to. + postal_codes (MutableSequence[google.shopping.merchant_accounts_v1.types.Region.PostalCodeArea.PostalCodeRange]): + Required. A range of postal codes. + """ + + class PostalCodeRange(proto.Message): + r"""A range of postal codes that defines the region area. + + Attributes: + begin (str): + Required. A postal code or a pattern of the form prefix\* + denoting the inclusive lower bound of the range defining the + area. Examples values: ``94108``, ``9410*``, ``9*``. + end (str): + Optional. A postal code or a pattern of the form ``prefix*`` + denoting the inclusive upper bound of the range defining the + area. It must have the same length as postalCodeRangeBegin: + if postalCodeRangeBegin is a postal code then + postalCodeRangeEnd must be a postal code too; if + postalCodeRangeBegin is a pattern then postalCodeRangeEnd + must be a pattern with the same prefix length. Optional: if + not set, then the area is defined as being all the postal + codes matching postalCodeRangeBegin. + """ + + begin: str = proto.Field( + proto.STRING, + number=1, + ) + end: str = proto.Field( + proto.STRING, + number=2, + ) + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + postal_codes: MutableSequence['Region.PostalCodeArea.PostalCodeRange'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Region.PostalCodeArea.PostalCodeRange', + ) + + class GeoTargetArea(proto.Message): + r"""A list of geotargets that defines the region area. + + Attributes: + geotarget_criteria_ids (MutableSequence[int]): + Required. A non-empty list of `location + IDs `__. + They must all be of the same location type (for example, + state). + """ + + geotarget_criteria_ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + postal_code_area: PostalCodeArea = proto.Field( + proto.MESSAGE, + number=3, + message=PostalCodeArea, + ) + geotarget_area: GeoTargetArea = proto.Field( + proto.MESSAGE, + number=4, + message=GeoTargetArea, + ) + regional_inventory_eligible: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.BoolValue, + ) + shipping_eligible: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.BoolValue, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py new file mode 100644 index 000000000000..d9428c926229 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py @@ -0,0 +1,1496 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'ShippingSettings', + 'Service', + 'Distance', + 'Warehouse', + 'WarehouseCutoffTime', + 'Address', + 'DeliveryTime', + 'CutoffTime', + 'BusinessDayConfig', + 'WarehouseBasedDeliveryTime', + 'RateGroup', + 'Table', + 'TransitTable', + 'MinimumOrderValueTable', + 'Headers', + 'LocationIdSet', + 'Row', + 'Value', + 'CarrierRate', + 'GetShippingSettingsRequest', + 'InsertShippingSettingsRequest', + }, +) + + +class ShippingSettings(proto.Message): + r"""The Merchant Center account's `shipping + settings `__. + The ``ShippingSettings`` resource lets you retrieve and update the + shipping settings of your advanced account and all its associated + sub-accounts. + + Attributes: + name (str): + Identifier. The resource name of the shipping settings. + Format: ``accounts/{account}/shippingSettings``. For + example, ``accounts/123456/shippingSettings``. + services (MutableSequence[google.shopping.merchant_accounts_v1.types.Service]): + Optional. The target account's list of + services. + warehouses (MutableSequence[google.shopping.merchant_accounts_v1.types.Warehouse]): + Optional. A list of warehouses which can be referred to in + ``services``. + etag (str): + Required. This field helps avoid async issues. It ensures + that the shipping setting data doesn't change between the + ``get`` call and the ``insert`` call. The user should follow + these steps: + + 1. Set the etag field as an empty string for the initial + shipping setting creation. + + 2. After the initial creation, call the ``get`` method to + obtain an etag and the current shipping setting data + before calling ``insert``. + + 3. Modify the shipping setting information. + + 4. Call the ``insert`` method with the shipping setting + information and the etag obtained in step 2. + + 5. If the shipping setting data changes between step 2 and + step 4, the insert request will fail because the etag + changes every time the shipping setting data changes. In + this case, the user should repeat steps 2-4 with the new + etag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + services: MutableSequence['Service'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Service', + ) + warehouses: MutableSequence['Warehouse'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Warehouse', + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Service(proto.Message): + r"""Shipping service. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + service_name (str): + Required. Free-form name of the service. Must + be unique within target account. + + This field is a member of `oneof`_ ``_service_name``. + active (bool): + Required. A boolean exposing the active + status of the shipping service. + + This field is a member of `oneof`_ ``_active``. + delivery_countries (MutableSequence[str]): + Required. The CLDR territory code of the + countries to which the service applies. + currency_code (str): + Required. The CLDR code of the currency to + which this service applies. Must match that of + the prices in rate groups. + + This field is a member of `oneof`_ ``_currency_code``. + delivery_time (google.shopping.merchant_accounts_v1.types.DeliveryTime): + Required. Time spent in various aspects from + order to the delivery of the product. + + This field is a member of `oneof`_ ``_delivery_time``. + rate_groups (MutableSequence[google.shopping.merchant_accounts_v1.types.RateGroup]): + Optional. Shipping rate group definitions. Only the last one + is allowed to have an empty ``applicable_shipping_labels``, + which means "everything else". The other + ``applicable_shipping_labels`` must not overlap. + shipment_type (google.shopping.merchant_accounts_v1.types.Service.ShipmentType): + Optional. Type of locations this service + ships orders to. + + This field is a member of `oneof`_ ``_shipment_type``. + minimum_order_value (google.shopping.type.types.Price): + Optional. Minimum order value for this service. If set, + indicates that customers will have to spend at least this + amount. All prices within a service must have the same + currency. Cannot be set together with + ``minimum_order_value_table``. + + This field is a member of `oneof`_ ``_minimum_order_value``. + minimum_order_value_table (google.shopping.merchant_accounts_v1.types.MinimumOrderValueTable): + Optional. Table of per store minimum order values for the + pickup fulfillment type. Cannot be set together with + ``minimum_order_value``. + + This field is a member of `oneof`_ ``_minimum_order_value_table``. + store_config (google.shopping.merchant_accounts_v1.types.Service.StoreConfig): + A list of stores your products are delivered + from. This is only valid for the local delivery + shipment type. + + This field is a member of `oneof`_ ``_store_config``. + loyalty_programs (MutableSequence[google.shopping.merchant_accounts_v1.types.Service.LoyaltyProgram]): + Optional. Loyalty programs that this shipping + service is limited to. + """ + class ShipmentType(proto.Enum): + r"""Shipment type of shipping service. + + Values: + SHIPMENT_TYPE_UNSPECIFIED (0): + This service did not specify shipment type. + DELIVERY (1): + This service ships orders to an address + chosen by the customer. + LOCAL_DELIVERY (2): + This service ships orders to an address + chosen by the customer. The order is shipped + from a local store near by. + COLLECTION_POINT (3): + This service ships orders to an address + chosen by the customer. The order is shipped + from a collection point. + """ + SHIPMENT_TYPE_UNSPECIFIED = 0 + DELIVERY = 1 + LOCAL_DELIVERY = 2 + COLLECTION_POINT = 3 + + class StoreConfig(proto.Message): + r"""A list of stores your products are delivered from. This is + only valid for the local delivery shipment type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + store_service_type (google.shopping.merchant_accounts_v1.types.Service.StoreConfig.StoreServiceType): + Indicates whether all stores, or selected + stores, listed by this business provide local + delivery. + + This field is a member of `oneof`_ ``_store_service_type``. + store_codes (MutableSequence[str]): + Optional. A list of store codes that provide local delivery. + If empty, then ``all_stores`` must be true. + cutoff_config (google.shopping.merchant_accounts_v1.types.Service.StoreConfig.CutoffConfig): + Configs related to local delivery ends for + the day. + + This field is a member of `oneof`_ ``_cutoff_config``. + service_radius (google.shopping.merchant_accounts_v1.types.Distance): + Maximum delivery radius. + This is only required for the local delivery + shipment type. + + This field is a member of `oneof`_ ``_service_radius``. + """ + class StoreServiceType(proto.Enum): + r"""Indicates whether all stores, or selected stores, listed by + the business provide local delivery. + + Values: + STORE_SERVICE_TYPE_UNSPECIFIED (0): + Did not specify store service type. + ALL_STORES (1): + Indicates whether all stores, current and + future, listed by this business provide local + delivery. + SELECTED_STORES (2): + Indicates that only the stores listed in ``store_codes`` are + eligible for local delivery. + """ + STORE_SERVICE_TYPE_UNSPECIFIED = 0 + ALL_STORES = 1 + SELECTED_STORES = 2 + + class CutoffConfig(proto.Message): + r"""Configs related to local delivery ends for the day. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + local_cutoff_time (google.shopping.merchant_accounts_v1.types.Service.StoreConfig.CutoffConfig.LocalCutoffTime): + Time that local delivery ends for the day. + + This field is a member of `oneof`_ ``_local_cutoff_time``. + store_close_offset_hours (int): + Only valid with local delivery fulfillment. Represents + cutoff time as the number of hours before store closing. + Mutually exclusive with ``local_cutoff_time``. + + This field is a member of `oneof`_ ``_store_close_offset_hours``. + no_delivery_post_cutoff (bool): + Businesses can opt-out of showing n+1 day local delivery + when they have a shipping service configured to n day local + delivery. For example, if the shipping service defines + same-day delivery, and it's past the cut-off, setting this + field to ``true`` results in the calculated shipping service + rate returning ``NO_DELIVERY_POST_CUTOFF``. In the same + example, setting this field to ``false`` results in the + calculated shipping time being one day. This is only for + local delivery. + + This field is a member of `oneof`_ ``_no_delivery_post_cutoff``. + """ + + class LocalCutoffTime(proto.Message): + r"""Time that local delivery ends for the day. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hour (int): + Hour local delivery orders must be placed by + to process the same day. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + Minute local delivery orders must be placed + by to process the same day. + + This field is a member of `oneof`_ ``_minute``. + """ + + hour: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + minute: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + local_cutoff_time: 'Service.StoreConfig.CutoffConfig.LocalCutoffTime' = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message='Service.StoreConfig.CutoffConfig.LocalCutoffTime', + ) + store_close_offset_hours: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + no_delivery_post_cutoff: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + + store_service_type: 'Service.StoreConfig.StoreServiceType' = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum='Service.StoreConfig.StoreServiceType', + ) + store_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + cutoff_config: 'Service.StoreConfig.CutoffConfig' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Service.StoreConfig.CutoffConfig', + ) + service_radius: 'Distance' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='Distance', + ) + + class LoyaltyProgram(proto.Message): + r"""`Loyalty + program `__ + provided by a business. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + program_label (str): + This is the loyalty program label set in your + loyalty program settings in Merchant Center. + This sub-attribute allows Google to map your + loyalty program to eligible offers. + + This field is a member of `oneof`_ ``_program_label``. + loyalty_program_tiers (MutableSequence[google.shopping.merchant_accounts_v1.types.Service.LoyaltyProgram.LoyaltyProgramTiers]): + Optional. Loyalty program tier of this + shipping service. + """ + + class LoyaltyProgramTiers(proto.Message): + r"""Subset of a business's loyalty program. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tier_label (str): + The tier label [tier_label] sub-attribute differentiates + offer level benefits between each tier. This value is also + set in your program settings in Merchant Center, and is + required for data source changes even if your loyalty + program only has 1 tier. + + This field is a member of `oneof`_ ``_tier_label``. + """ + + tier_label: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + program_label: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + loyalty_program_tiers: MutableSequence['Service.LoyaltyProgram.LoyaltyProgramTiers'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Service.LoyaltyProgram.LoyaltyProgramTiers', + ) + + service_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + active: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + delivery_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + currency_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + delivery_time: 'DeliveryTime' = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message='DeliveryTime', + ) + rate_groups: MutableSequence['RateGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='RateGroup', + ) + shipment_type: ShipmentType = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=ShipmentType, + ) + minimum_order_value: types.Price = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message=types.Price, + ) + minimum_order_value_table: 'MinimumOrderValueTable' = proto.Field( + proto.MESSAGE, + number=9, + optional=True, + message='MinimumOrderValueTable', + ) + store_config: StoreConfig = proto.Field( + proto.MESSAGE, + number=10, + optional=True, + message=StoreConfig, + ) + loyalty_programs: MutableSequence[LoyaltyProgram] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=LoyaltyProgram, + ) + + +class Distance(proto.Message): + r"""Maximum delivery radius. + This is only required for the local delivery shipment type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (int): + Integer value of distance. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_accounts_v1.types.Distance.Unit): + Unit can differ based on country, it is + parameterized to include miles and kilometers. + + This field is a member of `oneof`_ ``_unit``. + """ + class Unit(proto.Enum): + r"""Unit can differ based on country, it is parameterized to + include miles and kilometers. + + Values: + UNIT_UNSPECIFIED (0): + Unit unspecified + MILES (1): + Unit in miles + KILOMETERS (2): + Unit in kilometers + """ + UNIT_UNSPECIFIED = 0 + MILES = 1 + KILOMETERS = 2 + + value: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + unit: Unit = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum=Unit, + ) + + +class Warehouse(proto.Message): + r"""A fulfillment warehouse, which stores and handles inventory. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The name of the warehouse. Must be + unique within account. + + This field is a member of `oneof`_ ``_name``. + shipping_address (google.shopping.merchant_accounts_v1.types.Address): + Required. Shipping address of the warehouse. + + This field is a member of `oneof`_ ``_shipping_address``. + cutoff_time (google.shopping.merchant_accounts_v1.types.WarehouseCutoffTime): + Required. The latest time of day that an + order can be accepted and begin processing. + Later orders will be processed in the next day. + The time is based on the warehouse postal code. + + This field is a member of `oneof`_ ``_cutoff_time``. + handling_days (int): + Required. The number of days it takes for + this warehouse to pack up and ship an item. This + is on the warehouse level, but can be overridden + on the offer level based on the attributes of an + item. + + This field is a member of `oneof`_ ``_handling_days``. + business_day_config (google.shopping.merchant_accounts_v1.types.BusinessDayConfig): + Business days of the warehouse. + If not set, will be Monday to Friday by default. + + This field is a member of `oneof`_ ``_business_day_config``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + shipping_address: 'Address' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='Address', + ) + cutoff_time: 'WarehouseCutoffTime' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='WarehouseCutoffTime', + ) + handling_days: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + business_day_config: 'BusinessDayConfig' = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message='BusinessDayConfig', + ) + + +class WarehouseCutoffTime(proto.Message): + r"""The latest time of day that an order can be accepted and + begin processing. Later orders will be processed in the next + day. The time is based on the warehouse postal code. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hour (int): + Required. Hour of the cutoff time until which + an order has to be placed to be processed in the + same day by the warehouse. Hour is based on the + timezone of warehouse. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + Required. Minute of the cutoff time until + which an order has to be placed to be processed + in the same day by the warehouse. Minute is + based on the timezone of warehouse. + + This field is a member of `oneof`_ ``_minute``. + """ + + hour: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + minute: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class Address(proto.Message): + r"""Shipping address of the warehouse. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + street_address (str): + Street-level part of the address. For example: + ``111w 31st Street``. + + This field is a member of `oneof`_ ``_street_address``. + city (str): + Required. City, town or commune. May also + include dependent localities or sublocalities + (For example neighborhoods or suburbs). + + This field is a member of `oneof`_ ``_city``. + administrative_area (str): + Required. Top-level administrative + subdivision of the country. For example, a state + like California ("CA") or a province like Quebec + ("QC"). + + This field is a member of `oneof`_ ``_administrative_area``. + postal_code (str): + Required. Postal code or ZIP (For example + "94043"). + + This field is a member of `oneof`_ ``_postal_code``. + region_code (str): + Required. `CLDR country + code `__ + (For example "US"). + + This field is a member of `oneof`_ ``_region_code``. + """ + + street_address: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + city: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + administrative_area: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + postal_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + region_code: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + +class DeliveryTime(proto.Message): + r"""Time spent in various aspects from order to the delivery of + the product. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_transit_days (int): + Minimum number of business days that is spent in transit. 0 + means same day delivery, 1 means next day delivery. Either + ``min_transit_days``, ``max_transit_days`` or + ``transit_time_table`` must be set, but not both. + + This field is a member of `oneof`_ ``_min_transit_days``. + max_transit_days (int): + Maximum number of business days that is spent in transit. 0 + means same day delivery, 1 means next day delivery. Must be + greater than or equal to ``min_transit_days``. + + This field is a member of `oneof`_ ``_max_transit_days``. + cutoff_time (google.shopping.merchant_accounts_v1.types.CutoffTime): + Business days cutoff time definition. + If not configured the cutoff time will be + defaulted to 8AM PST. + + This field is a member of `oneof`_ ``_cutoff_time``. + min_handling_days (int): + Minimum number of business days spent before an order is + shipped. 0 means same day shipped, 1 means next day shipped. + 'min_handling_days' and 'max_handling_days' should be either + set or not set at the same time. + + This field is a member of `oneof`_ ``_min_handling_days``. + max_handling_days (int): + Maximum number of business days spent before an order is + shipped. 0 means same day shipped, 1 means next day shipped. + Must be greater than or equal to ``min_handling_days``. + 'min_handling_days' and 'max_handling_days' should be either + set or not set at the same time. + + This field is a member of `oneof`_ ``_max_handling_days``. + transit_time_table (google.shopping.merchant_accounts_v1.types.TransitTable): + Transit time table, number of business days spent in transit + based on row and column dimensions. Either + ``min_transit_days``, ``max_transit_days`` or + ``transit_time_table`` can be set, but not both. + + This field is a member of `oneof`_ ``_transit_time_table``. + handling_business_day_config (google.shopping.merchant_accounts_v1.types.BusinessDayConfig): + The business days during which orders can be + handled. If not provided, Monday to Friday + business days will be assumed. + + This field is a member of `oneof`_ ``_handling_business_day_config``. + transit_business_day_config (google.shopping.merchant_accounts_v1.types.BusinessDayConfig): + The business days during which orders can be + in-transit. If not provided, Monday to Friday + business days will be assumed. + + This field is a member of `oneof`_ ``_transit_business_day_config``. + warehouse_based_delivery_times (MutableSequence[google.shopping.merchant_accounts_v1.types.WarehouseBasedDeliveryTime]): + Optional. Indicates that the delivery time should be + calculated per warehouse (shipping origin location) based on + the settings of the selected carrier. When set, no other + transit time related field in [delivery + time][google.shopping.merchant.accounts.v1.DeliveryTime] + should be set. + """ + + min_transit_days: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + max_transit_days: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + cutoff_time: 'CutoffTime' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='CutoffTime', + ) + min_handling_days: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + max_handling_days: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + transit_time_table: 'TransitTable' = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message='TransitTable', + ) + handling_business_day_config: 'BusinessDayConfig' = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message='BusinessDayConfig', + ) + transit_business_day_config: 'BusinessDayConfig' = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message='BusinessDayConfig', + ) + warehouse_based_delivery_times: MutableSequence['WarehouseBasedDeliveryTime'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='WarehouseBasedDeliveryTime', + ) + + +class CutoffTime(proto.Message): + r"""Business days cutoff time definition. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hour (int): + Required. Hour of the cutoff time until which + an order has to be placed to be processed in the + same day. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + Required. Minute of the cutoff time until + which an order has to be placed to be processed + in the same day. + + This field is a member of `oneof`_ ``_minute``. + time_zone (str): + Required. `Timezone + identifier `__ + For example "Europe/Zurich". + + This field is a member of `oneof`_ ``_time_zone``. + """ + + hour: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + minute: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + time_zone: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class BusinessDayConfig(proto.Message): + r"""Business days of the warehouse. + + Attributes: + business_days (MutableSequence[google.shopping.merchant_accounts_v1.types.BusinessDayConfig.Weekday]): + Required. Regular business days. + May not be empty. + """ + class Weekday(proto.Enum): + r""" + + Values: + WEEKDAY_UNSPECIFIED (0): + No description available. + MONDAY (1): + No description available. + TUESDAY (2): + No description available. + WEDNESDAY (3): + No description available. + THURSDAY (4): + No description available. + FRIDAY (5): + No description available. + SATURDAY (6): + No description available. + SUNDAY (7): + No description available. + """ + WEEKDAY_UNSPECIFIED = 0 + MONDAY = 1 + TUESDAY = 2 + WEDNESDAY = 3 + THURSDAY = 4 + FRIDAY = 5 + SATURDAY = 6 + SUNDAY = 7 + + business_days: MutableSequence[Weekday] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=Weekday, + ) + + +class WarehouseBasedDeliveryTime(proto.Message): + r"""Indicates that the delivery time should be calculated per warehouse + (shipping origin location) based on the settings of the selected + carrier. When set, no other transit time related field in + ``delivery_time`` should be set. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + carrier (str): + Required. Carrier, such as ``"UPS"`` or ``"Fedex"``. + `supported + carriers `__ + + This field is a member of `oneof`_ ``_carrier``. + carrier_service (str): + Required. Carrier service, such as ``"ground"`` or + ``"2 days"``. The name of the service must be in the + eddSupportedServices list. + + This field is a member of `oneof`_ ``_carrier_service``. + warehouse (str): + Required. Warehouse name. This should match + [warehouse][google.shopping.merchant.accounts.v1.Warehouse]. + + This field is a member of `oneof`_ ``_warehouse``. + """ + + carrier: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + carrier_service: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + warehouse: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class RateGroup(proto.Message): + r"""Shipping rate group definitions. Only the last one is allowed to + have an empty ``applicable_shipping_labels``, which means + "everything else". The other ``applicable_shipping_labels`` must not + overlap. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + applicable_shipping_labels (MutableSequence[str]): + Required. A list of `shipping + labels `__ + defining the products to which this rate group applies to. + This is a disjunction: only one of the labels has to match + for the rate group to apply. May only be empty for the last + rate group of a service. + single_value (google.shopping.merchant_accounts_v1.types.Value): + The value of the rate group (For example flat rate $10). Can + only be set if ``main_table`` and ``subtables`` are not set. + + This field is a member of `oneof`_ ``_single_value``. + main_table (google.shopping.merchant_accounts_v1.types.Table): + A table defining the rate group, when ``single_value`` is + not expressive enough. Can only be set if ``single_value`` + is not set. + + This field is a member of `oneof`_ ``_main_table``. + subtables (MutableSequence[google.shopping.merchant_accounts_v1.types.Table]): + Optional. A list of subtables referred to by ``main_table``. + Can only be set if ``main_table`` is set. + carrier_rates (MutableSequence[google.shopping.merchant_accounts_v1.types.CarrierRate]): + Optional. A list of carrier rates that can be referred to by + ``main_table`` or ``single_value``. + name (str): + Optional. Name of the rate group. + If set has to be unique within shipping service. + + This field is a member of `oneof`_ ``_name``. + """ + + applicable_shipping_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + single_value: 'Value' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='Value', + ) + main_table: 'Table' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Table', + ) + subtables: MutableSequence['Table'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Table', + ) + carrier_rates: MutableSequence['CarrierRate'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='CarrierRate', + ) + name: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + +class Table(proto.Message): + r"""A table defining the rate group, when ``single_value`` is not + expressive enough. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the table. Required for subtables, + ignored for the main table. + + This field is a member of `oneof`_ ``_name``. + row_headers (google.shopping.merchant_accounts_v1.types.Headers): + Required. Headers of the table's rows. + + This field is a member of `oneof`_ ``_row_headers``. + column_headers (google.shopping.merchant_accounts_v1.types.Headers): + Headers of the table's columns. Optional: if + not set then the table has only one dimension. + + This field is a member of `oneof`_ ``_column_headers``. + rows (MutableSequence[google.shopping.merchant_accounts_v1.types.Row]): + Required. The list of rows that constitute the table. Must + have the same length as ``row_headers``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + row_headers: 'Headers' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='Headers', + ) + column_headers: 'Headers' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Headers', + ) + rows: MutableSequence['Row'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Row', + ) + + +class TransitTable(proto.Message): + r"""Transit time table, number of business days spent in transit based + on row and column dimensions. Either ``min_transit_days``, + ``max_transit_days`` or ``transit_time_table`` can be set, but not + both. + + Attributes: + postal_code_group_names (MutableSequence[str]): + Required. A list of region names + [Region.name][google.shopping.merchant.accounts.v1.Region.name] + . The last value can be ``"all other locations"``. Example: + ``["zone 1", "zone 2", "all other locations"]``. The + referred postal code groups must match the delivery country + of the service. + transit_time_labels (MutableSequence[str]): + Required. A list of transit time labels. The last value can + be ``"all other labels"``. Example: + ``["food", "electronics", "all other labels"]``. + rows (MutableSequence[google.shopping.merchant_accounts_v1.types.TransitTable.TransitTimeRow]): + Required. If there's only one dimension set of + ``postal_code_group_names`` or ``transit_time_labels``, + there are multiple rows each with one value for that + dimension. If there are two dimensions, each row corresponds + to a ``postal_code_group_names``, and columns (values) to a + ``transit_time_labels``. + """ + + class TransitTimeRow(proto.Message): + r"""If there's only one dimension set of ``postal_code_group_names`` or + ``transit_time_labels``, there are multiple rows each with one value + for that dimension. If there are two dimensions, each row + corresponds to a ``postal_code_group_names``, and columns (values) + to a ``transit_time_labels``. + + Attributes: + values (MutableSequence[google.shopping.merchant_accounts_v1.types.TransitTable.TransitTimeRow.TransitTimeValue]): + Required. Transit time range (min-max) in + business days. + """ + + class TransitTimeValue(proto.Message): + r"""Transit time range (min-max) in business days. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_transit_days (int): + Minimum transit time range in business days. + 0 means same day delivery, 1 means next day + delivery. + + This field is a member of `oneof`_ ``_min_transit_days``. + max_transit_days (int): + Must be greater than or equal to ``min_transit_days``. + + This field is a member of `oneof`_ ``_max_transit_days``. + """ + + min_transit_days: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + max_transit_days: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + values: MutableSequence['TransitTable.TransitTimeRow.TransitTimeValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TransitTable.TransitTimeRow.TransitTimeValue', + ) + + postal_code_group_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + transit_time_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + rows: MutableSequence[TransitTimeRow] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TransitTimeRow, + ) + + +class MinimumOrderValueTable(proto.Message): + r"""Table of per store minimum order values for the pickup + fulfillment type. + + Attributes: + store_code_set_with_movs (MutableSequence[google.shopping.merchant_accounts_v1.types.MinimumOrderValueTable.StoreCodeSetWithMov]): + Required. A list of store code sets sharing + the same minimum order value (MOV). At least two + sets are required and the last one must be + empty, which signifies 'MOV for all other + stores'. Each store code can only appear once + across all the sets. All prices within a service + must have the same currency. + """ + + class StoreCodeSetWithMov(proto.Message): + r"""A list of store code sets sharing the same minimum order + value. At least two sets are required and the last one must be + empty, which signifies 'MOV for all other stores'. + Each store code can only appear once across all the sets. All + prices within a service must have the same currency. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + store_codes (MutableSequence[str]): + Optional. A list of unique store codes or + empty for the catch all. + value (google.shopping.type.types.Price): + The minimum order value for the given stores. + + This field is a member of `oneof`_ ``_value``. + """ + + store_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + value: types.Price = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=types.Price, + ) + + store_code_set_with_movs: MutableSequence[StoreCodeSetWithMov] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=StoreCodeSetWithMov, + ) + + +class Headers(proto.Message): + r"""A non-empty list of row or column headers for a table. Exactly one + of ``prices``, ``weights``, ``num_items``, + ``postal_code_group_names``, or ``location`` must be set. + + Attributes: + prices (MutableSequence[google.shopping.type.types.Price]): + Required. A list of inclusive order price upper bounds. The + last price's value can be infinity by setting price + amount_micros = -1. For example + ``[{"amount_micros": 10000000, "currency_code": "USD"}, {"amount_micros": 500000000, "currency_code": "USD"}, {"amount_micros": -1, "currency_code": "USD"}]`` + represents the headers "<= $10", "<= $500", and "> $500". + All prices within a service must have the same currency. + Must be non-empty. Must be positive except -1. Can only be + set if all other fields are not set. + weights (MutableSequence[google.shopping.type.types.Weight]): + Required. A list of inclusive order weight upper bounds. The + last weight's value can be infinity by setting price + amount_micros = -1. For example + ``[{"amount_micros": 10000000, "unit": "kg"}, {"amount_micros": 50000000, "unit": "kg"}, {"amount_micros": -1, "unit": "kg"}]`` + represents the headers "<= 10kg", "<= 50kg", and "> 50kg". + All weights within a service must have the same unit. Must + be non-empty. Must be positive except -1. Can only be set if + all other fields are not set. + number_of_items (MutableSequence[str]): + Required. A list of inclusive number of items upper bounds. + The last value can be ``"infinity"``. For example + ``["10", "50", "infinity"]`` represents the headers "<= 10 + items", "<= 50 items", and "> 50 items". Must be non-empty. + Can only be set if all other fields are not set. + postal_code_group_names (MutableSequence[str]): + Required. A list of postal group names. The last value can + be ``"all other locations"``. Example: + ``["zone 1", "zone 2", "all other locations"]``. The + referred postal code groups must match the delivery country + of the service. Must be non-empty. Can only be set if all + other fields are not set. + locations (MutableSequence[google.shopping.merchant_accounts_v1.types.LocationIdSet]): + Required. A list of location ID sets. Must be + non-empty. Can only be set if all other fields + are not set. + """ + + prices: MutableSequence[types.Price] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=types.Price, + ) + weights: MutableSequence[types.Weight] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=types.Weight, + ) + number_of_items: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + postal_code_group_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + locations: MutableSequence['LocationIdSet'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='LocationIdSet', + ) + + +class LocationIdSet(proto.Message): + r"""A list of location ID sets. Must be non-empty. Can only be + set if all other fields are not set. + + Attributes: + location_ids (MutableSequence[str]): + Required. A non-empty list of `location + IDs `__. + They must all be of the same location type (For example, + state). + """ + + location_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class Row(proto.Message): + r"""Include a list of cells. + + Attributes: + cells (MutableSequence[google.shopping.merchant_accounts_v1.types.Value]): + Required. The list of cells that constitute the row. Must + have the same length as ``columnHeaders`` for + two-dimensional tables, a length of 1 for one-dimensional + tables. + """ + + cells: MutableSequence['Value'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Value', + ) + + +class Value(proto.Message): + r"""The single value of a rate group or the value of a rate group + table's cell. Exactly one of ``no_shipping``, ``flat_rate``, + ``price_percentage``, ``carrier_rateName``, ``subtable_name`` must + be set. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + no_shipping (bool): + If true, then the product can't be shipped. + Must be true when set, can only be set if all + other fields are not set. + + This field is a member of `oneof`_ ``_no_shipping``. + flat_rate (google.shopping.type.types.Price): + A flat rate. Can only be set if all other + fields are not set. + + This field is a member of `oneof`_ ``_flat_rate``. + price_percentage (str): + A percentage of the price represented as a number in decimal + notation (For example, ``"5.4"``). Can only be set if all + other fields are not set. + + This field is a member of `oneof`_ ``_price_percentage``. + carrier_rate (str): + The name of a carrier rate referring to a + carrier rate defined in the same rate group. Can + only be set if all other fields are not set. + + This field is a member of `oneof`_ ``_carrier_rate``. + subtable (str): + The name of a subtable. Can only be set in + table cells (For example, not for single + values), and only if all other fields are not + set. + + This field is a member of `oneof`_ ``_subtable``. + """ + + no_shipping: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + flat_rate: types.Price = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=types.Price, + ) + price_percentage: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + carrier_rate: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + subtable: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + +class CarrierRate(proto.Message): + r"""A list of carrier rates that can be referred to by ``main_table`` or + ``single_value``. Supported carrier services are defined in + https://support.google.com/merchants/answer/12577710?ref_topic=12570808&sjid=10662598224319463032-NC#zippy=%2Cdelivery-cost-rate-type%2Ccarrier-rate-au-de-uk-and-us-only. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the carrier rate. Must be + unique per rate group. + + This field is a member of `oneof`_ ``_name``. + carrier (str): + Required. Carrier service, such as ``"UPS"`` or ``"Fedex"``. + + This field is a member of `oneof`_ ``_carrier``. + carrier_service (str): + Required. Carrier service, such as ``"ground"`` or + ``"2 days"``. + + This field is a member of `oneof`_ ``_carrier_service``. + origin_postal_code (str): + Required. Shipping origin for this carrier + rate. + + This field is a member of `oneof`_ ``_origin_postal_code``. + percentage_adjustment (str): + Optional. Multiplicative shipping rate modifier as a number + in decimal notation. Can be negative. For example ``"5.4"`` + increases the rate by 5.4%, ``"-3"`` decreases the rate by + 3%. + + This field is a member of `oneof`_ ``_percentage_adjustment``. + flat_adjustment (google.shopping.type.types.Price): + Optional. Additive shipping rate modifier. Can be negative. + For example + ``{ "amount_micros": 1, "currency_code" : "USD" }`` adds $1 + to the rate, + ``{ "amount_micros": -3, "currency_code" : "USD" }`` removes + $3 from the rate. + + This field is a member of `oneof`_ ``_flat_adjustment``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + carrier: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + carrier_service: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + origin_postal_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + percentage_adjustment: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + flat_adjustment: types.Price = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=types.Price, + ) + + +class GetShippingSettingsRequest(proto.Message): + r"""Request message for the ``GetShippingSetting`` method. + + Attributes: + name (str): + Required. The name of the shipping setting to retrieve. + Format: ``accounts/{account}/shippingsettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InsertShippingSettingsRequest(proto.Message): + r"""Request message for the ``InsertShippingSetting`` method. + + Attributes: + parent (str): + Required. The account for which this shipping setting will + be inserted. If you are using an advanced account, you must + specify the unique identifier of the sub-account for which + you want to insert the shipping setting. Format: + ``accounts/{ACCOUNT_ID}`` + shipping_setting (google.shopping.merchant_accounts_v1.types.ShippingSettings): + Required. The new version of the account. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + shipping_setting: 'ShippingSettings' = proto.Field( + proto.MESSAGE, + number=2, + message='ShippingSettings', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py new file mode 100644 index 000000000000..4313b1734be3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py @@ -0,0 +1,192 @@ +# -*- 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_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'TermsOfService', + 'GetTermsOfServiceRequest', + 'RetrieveLatestTermsOfServiceRequest', + 'AcceptTermsOfServiceRequest', + 'AcceptTermsOfServiceResponse', + }, +) + + +class TermsOfService(proto.Message): + r"""The ``TermsOfService`` message represents a specific version of the + terms of service that merchants must accept to access certain + features or services. For more information, see `Terms of + Service `__. + + This message is important for the onboarding process, ensuring that + merchants agree to the necessary legal agreements for using the + service. Merchants can retrieve the latest terms of service for a + given ``kind`` and ``region`` through + ``RetrieveLatestTermsOfService``, and accept them as required + through ``AcceptTermsOfService``. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + region_code (str): + Region code as defined by + `CLDR `__. This is either a + country where the ToS applies specifically to that country + or ``001`` when the same ``TermsOfService`` can be signed in + any country. However note that when signing a ToS that + applies globally we still expect that a specific country is + provided (this should be merchant business country or + program country of participation). + kind (google.shopping.merchant_accounts_v1.types.TermsOfServiceKind): + The Kind this terms of service version + applies to. + file_uri (str): + URI for terms of service file that needs to + be displayed to signing users. + + This field is a member of `oneof`_ ``_file_uri``. + external (bool): + Whether this terms of service version is + external. External terms of service versions can + only be agreed through external processes and + not directly by the merchant through UI or API. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + kind: termsofservicekind.TermsOfServiceKind = proto.Field( + proto.ENUM, + number=3, + enum=termsofservicekind.TermsOfServiceKind, + ) + file_uri: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + external: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class GetTermsOfServiceRequest(proto.Message): + r"""Request message for the ``GetTermsOfService`` method. + + Attributes: + name (str): + Required. The resource name of the terms of service version. + Format: ``termsOfService/{version}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RetrieveLatestTermsOfServiceRequest(proto.Message): + r"""Request message for the ``RetrieveLatestTermsOfService`` method. + + Attributes: + region_code (str): + Required. Region code as defined by + `CLDR `__. This is either a + country when the ToS applies specifically to that country or + 001 when it applies globally. + kind (google.shopping.merchant_accounts_v1.types.TermsOfServiceKind): + Required. The Kind this terms of service + version applies to. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + kind: termsofservicekind.TermsOfServiceKind = proto.Field( + proto.ENUM, + number=2, + enum=termsofservicekind.TermsOfServiceKind, + ) + + +class AcceptTermsOfServiceRequest(proto.Message): + r"""Request message for the ``AcceptTermsOfService`` method. + + Attributes: + name (str): + Required. The resource name of the terms of service version. + Format: ``termsOfService/{version}`` + account (str): + Required. The account for which to accept the ToS. Format: + ``accounts/{account}`` + region_code (str): + Required. Region code as defined by + `CLDR `__. This is either a + country when the ToS applies specifically to that country or + 001 when it applies globally. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: str = proto.Field( + proto.STRING, + number=2, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AcceptTermsOfServiceResponse(proto.Message): + r"""Response message for the ``AcceptTermsOfService`` method. + + Attributes: + terms_of_service_agreement_state (google.shopping.merchant_accounts_v1.types.TermsOfServiceAgreementState): + The agreement state after accepting the ToS. + """ + + terms_of_service_agreement_state: termsofserviceagreementstate.TermsOfServiceAgreementState = proto.Field( + proto.MESSAGE, + number=1, + message=termsofserviceagreementstate.TermsOfServiceAgreementState, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py new file mode 100644 index 000000000000..61cee91adc5a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py @@ -0,0 +1,220 @@ +# -*- 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_accounts_v1.types import termsofservicekind +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'TermsOfServiceAgreementState', + 'Accepted', + 'Required', + 'GetTermsOfServiceAgreementStateRequest', + 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + }, +) + + +class TermsOfServiceAgreementState(proto.Message): + r"""This resource represents the agreement state for a given account and + terms of service kind. The state is as follows: + + - If the business has accepted a terms of service, + [``accepted``][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty + - If the business must sign a terms of service, + [``required``][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both ``required`` and ``accepted`` can be present. In this + case the ``accepted`` terms of services will have an expiration date + set in the + [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The ``required`` terms of services need to be accepted before + ``valid_until`` in order for the account to continue having a valid + agreement. When accepting new terms of services we expect + third-party providers to display the text associated with the given + terms of service agreement (the url to the file containing the text + is added in the Required message below as + [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done by calling + accept on the + [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. ``valid_until`` field. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the terms of service + version. Format: + ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` + The identifier format is: + ``{[TermsOfServiceKind][google.shopping.merchant.accounts.v1.TermsOfServiceKind]}-{country}`` + For example, an identifier could be: ``MERCHANT_CENTER-EU`` + or ``MERCHANT_CENTER-US``. + region_code (str): + Required. Region code as defined by + https://cldr.unicode.org/. This is the country + the current state applies to. + terms_of_service_kind (google.shopping.merchant_accounts_v1.types.TermsOfServiceKind): + Required. Terms of Service kind associated + with the particular version. + accepted (google.shopping.merchant_accounts_v1.types.Accepted): + Optional. The accepted terms of service of this kind and for + the associated region_code + + This field is a member of `oneof`_ ``_accepted``. + required (google.shopping.merchant_accounts_v1.types.Required): + Optional. The required terms of service + + This field is a member of `oneof`_ ``_required``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + terms_of_service_kind: termsofservicekind.TermsOfServiceKind = proto.Field( + proto.ENUM, + number=3, + enum=termsofservicekind.TermsOfServiceKind, + ) + accepted: 'Accepted' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='Accepted', + ) + required: 'Required' = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message='Required', + ) + + +class Accepted(proto.Message): + r"""Describes the `accepted terms of + service `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + terms_of_service (str): + Required. The accepted + [termsOfService][google.shopping.merchant.accounts.v1.TermsOfService]. + accepted_by (str): + Required. The account where the acceptance + was recorded. This can be the account itself or, + in the case of subaccounts, the advanced + account. + valid_until (google.type.date_pb2.Date): + Optional. When set, it states that the accepted + ``TermsOfService`` is only valid until the end of this date + (in UTC). A new one must be accepted before then. The + information of the required ``TermsOfService`` is found in + the ``Required`` message. + + This field is a member of `oneof`_ ``_valid_until``. + """ + + terms_of_service: str = proto.Field( + proto.STRING, + number=1, + ) + accepted_by: str = proto.Field( + proto.STRING, + number=2, + ) + valid_until: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=date_pb2.Date, + ) + + +class Required(proto.Message): + r"""Describes the terms of service which are required to be + accepted. + + Attributes: + terms_of_service (str): + Required. The ``TermsOfService`` that need to be accepted. + tos_file_uri (str): + Required. Full URL to the terms of service file. This field + is the same as ``TermsOfService.file_uri``, it is added here + for convenience only. + """ + + terms_of_service: str = proto.Field( + proto.STRING, + number=1, + ) + tos_file_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTermsOfServiceAgreementStateRequest(proto.Message): + r"""Request message for the ``GetTermsOfServiceAgreementState`` method. + + Attributes: + name (str): + Required. The resource name of the terms of service version. + Format: + ``accounts/{account}/termsOfServiceAgreementStates/{identifier}`` + The identifier format is: ``{TermsOfServiceKind}-{country}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RetrieveForApplicationTermsOfServiceAgreementStateRequest(proto.Message): + r"""Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` method. + + Attributes: + parent (str): + Required. The account for which to get a + TermsOfServiceAgreementState Format: ``accounts/{account}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py new file mode 100644 index 000000000000..407306d2393e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py @@ -0,0 +1,44 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'TermsOfServiceKind', + }, +) + + +class TermsOfServiceKind(proto.Enum): + r"""The TermsOfService Kind. + + Values: + TERMS_OF_SERVICE_KIND_UNSPECIFIED (0): + Default value. This value is unused. + MERCHANT_CENTER (1): + Merchant Center application. + """ + TERMS_OF_SERVICE_KIND_UNSPECIFIED = 0 + MERCHANT_CENTER = 1 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py new file mode 100644 index 000000000000..6d773870e188 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py @@ -0,0 +1,255 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.types import accessright + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1', + manifest={ + 'User', + 'GetUserRequest', + 'CreateUserRequest', + 'DeleteUserRequest', + 'UpdateUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + }, +) + + +class User(proto.Message): + r"""The ``User`` message represents a user associated with a Merchant + Center account. It is used to manage user permissions and access + rights within the account. For more information, see `Frequently + asked questions about people and access + levels `__. + + Attributes: + name (str): + Identifier. The resource name of the user. Format: + ``accounts/{account}/user/{email}`` + + Use ``me`` to refer to your own email address, for example + ``accounts/{account}/users/me``. + state (google.shopping.merchant_accounts_v1.types.User.State): + Output only. The state of the user. + access_rights (MutableSequence[google.shopping.merchant_accounts_v1.types.AccessRight]): + Required. The `access + rights `__ + the user has. + """ + class State(proto.Enum): + r"""The possible states of a user. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + PENDING (1): + The user is pending confirmation. In this + state, the user first needs to accept the + invitation before performing other actions. + VERIFIED (2): + The user is verified. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + VERIFIED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + access_rights: MutableSequence[accessright.AccessRight] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=accessright.AccessRight, + ) + + +class GetUserRequest(proto.Message): + r"""Request message for the ``GetUser`` method. + + Attributes: + name (str): + Required. The name of the user to retrieve. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to retrieve the user corresponding to + the caller by using ``me`` rather than an email address as + in ``accounts/{account}/users/me``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserRequest(proto.Message): + r"""Request message for the ``CreateUser`` method. + + Attributes: + parent (str): + Required. The resource name of the account for which a user + will be created. Format: ``accounts/{account}`` + user_id (str): + Required. The email address of the user (for example, + ``john.doe@gmail.com``). + user (google.shopping.merchant_accounts_v1.types.User): + Optional. The user to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_id: str = proto.Field( + proto.STRING, + number=2, + ) + user: 'User' = proto.Field( + proto.MESSAGE, + number=3, + message='User', + ) + + +class DeleteUserRequest(proto.Message): + r"""Request message for the ``DeleteUser`` method. + + Attributes: + name (str): + Required. The name of the user to delete. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to delete the user corresponding to the + caller by using ``me`` rather than an email address as in + ``accounts/{account}/users/me``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateUserRequest(proto.Message): + r"""Request message for the ``UpdateUser`` method. + + Attributes: + user (google.shopping.merchant_accounts_v1.types.User): + Required. The new version of the user. + + Use ``me`` to refer to your own email address, for example + ``accounts/{account}/users/me``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``access_rights`` + """ + + user: 'User' = proto.Field( + proto.MESSAGE, + number=1, + message='User', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListUsersRequest(proto.Message): + r"""Request message for the ``ListUsers`` method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of users. + Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of users to + return. The service may return fewer than this + value. If unspecified, at most 50 users will be + returned. The maximum value is 100; values above + 100 will be coerced to 100 + page_token (str): + Optional. A page token, received from a previous + ``ListUsers`` call. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + ``ListUsers`` must match the call that provided the page + token. + """ + + 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 ListUsersResponse(proto.Message): + r"""Response message for the ``ListUsers`` method. + + Attributes: + users (MutableSequence[google.shopping.merchant_accounts_v1.types.User]): + The users from the specified account. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + users: MutableSequence['User'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='User', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini b/owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/noxfile.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/noxfile.py new file mode 100644 index 000000000000..cc47a9500d4c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts" + +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-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py new file mode 100644 index 000000000000..8fb44a4733a0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_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 ListAccountIssues +# 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-accounts + + +# [START merchantapi_v1_generated_AccountIssueService_ListAccountIssues_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_accounts_v1 + + +async def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1.AccountIssueServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountIssueService_ListAccountIssues_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py new file mode 100644 index 000000000000..f5fcfc763f42 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_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 ListAccountIssues +# 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-accounts + + +# [START merchantapi_v1_generated_AccountIssueService_ListAccountIssues_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_accounts_v1 + + +def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1.AccountIssueServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountIssueService_ListAccountIssues_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py new file mode 100644 index 000000000000..a7d76cdb5626 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccountRelationship +# 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-accounts + + +# [START merchantapi_v1_generated_AccountRelationshipsService_GetAccountRelationship_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_accounts_v1 + + +async def sample_get_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRelationshipRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account_relationship(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountRelationshipsService_GetAccountRelationship_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py new file mode 100644 index 000000000000..199e4bf670b9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccountRelationship +# 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-accounts + + +# [START merchantapi_v1_generated_AccountRelationshipsService_GetAccountRelationship_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_accounts_v1 + + +def sample_get_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRelationshipRequest( + name="name_value", + ) + + # Make the request + response = client.get_account_relationship(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountRelationshipsService_GetAccountRelationship_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py new file mode 100644 index 000000000000..d58a3c0d9335 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_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 ListAccountRelationships +# 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-accounts + + +# [START merchantapi_v1_generated_AccountRelationshipsService_ListAccountRelationships_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_accounts_v1 + + +async def sample_list_account_relationships(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountRelationshipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_relationships(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountRelationshipsService_ListAccountRelationships_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py new file mode 100644 index 000000000000..9c42c8bbf028 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_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 ListAccountRelationships +# 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-accounts + + +# [START merchantapi_v1_generated_AccountRelationshipsService_ListAccountRelationships_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_accounts_v1 + + +def sample_list_account_relationships(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountRelationshipsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_relationships(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountRelationshipsService_ListAccountRelationships_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py new file mode 100644 index 000000000000..1d2e031bf727 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAccountRelationship +# 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-accounts + + +# [START merchantapi_v1_generated_AccountRelationshipsService_UpdateAccountRelationship_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_accounts_v1 + + +async def sample_update_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAccountRelationshipRequest( + ) + + # Make the request + response = await client.update_account_relationship(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountRelationshipsService_UpdateAccountRelationship_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py new file mode 100644 index 000000000000..a99debfd3f32 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAccountRelationship +# 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-accounts + + +# [START merchantapi_v1_generated_AccountRelationshipsService_UpdateAccountRelationship_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_accounts_v1 + + +def sample_update_account_relationship(): + # Create a client + client = merchant_accounts_v1.AccountRelationshipsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAccountRelationshipRequest( + ) + + # Make the request + response = client.update_account_relationship(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountRelationshipsService_UpdateAccountRelationship_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py new file mode 100644 index 000000000000..971a3cd38579 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ApproveAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_ApproveAccountService_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_accounts_v1 + + +async def sample_approve_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ApproveAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.approve_account_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_ApproveAccountService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py new file mode 100644 index 000000000000..88cb87d95677 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ApproveAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_ApproveAccountService_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_accounts_v1 + + +def sample_approve_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ApproveAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = client.approve_account_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_ApproveAccountService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py new file mode 100644 index 000000000000..698f3bfd7cb6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_GetAccountService_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_accounts_v1 + + +async def sample_get_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_GetAccountService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py new file mode 100644 index 000000000000..dca783a86e5b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_GetAccountService_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_accounts_v1 + + +def sample_get_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_account_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_GetAccountService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py new file mode 100644 index 000000000000..1fce7de9d205 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_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 ListAccountServices +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_ListAccountServices_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_accounts_v1 + + +async def sample_list_account_services(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_services(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_ListAccountServices_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py new file mode 100644 index 000000000000..c6e6ed79b99a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_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 ListAccountServices +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_ListAccountServices_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_accounts_v1 + + +def sample_list_account_services(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountServicesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_services(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_ListAccountServices_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py new file mode 100644 index 000000000000..245c455ea081 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_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 ProposeAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_ProposeAccountService_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_accounts_v1 + + +async def sample_propose_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ProposeAccountServiceRequest( + parent="parent_value", + provider="provider_value", + ) + + # Make the request + response = await client.propose_account_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_ProposeAccountService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py new file mode 100644 index 000000000000..0f4420636ae7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_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 ProposeAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_ProposeAccountService_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_accounts_v1 + + +def sample_propose_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ProposeAccountServiceRequest( + parent="parent_value", + provider="provider_value", + ) + + # Make the request + response = client.propose_account_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountServicesService_ProposeAccountService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py new file mode 100644 index 000000000000..f69e96033d0f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_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 RejectAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_RejectAccountService_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_accounts_v1 + + +async def sample_reject_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RejectAccountServiceRequest( + name="name_value", + ) + + # Make the request + await client.reject_account_service(request=request) + + +# [END merchantapi_v1_generated_AccountServicesService_RejectAccountService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py new file mode 100644 index 000000000000..02941ba67dd1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_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 RejectAccountService +# 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-accounts + + +# [START merchantapi_v1_generated_AccountServicesService_RejectAccountService_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_accounts_v1 + + +def sample_reject_account_service(): + # Create a client + client = merchant_accounts_v1.AccountServicesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RejectAccountServiceRequest( + name="name_value", + ) + + # Make the request + client.reject_account_service(request=request) + + +# [END merchantapi_v1_generated_AccountServicesService_RejectAccountService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py new file mode 100644 index 000000000000..9736b95cf246 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_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 CreateAndConfigureAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_CreateAndConfigureAccount_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_accounts_v1 + + +async def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = await client.create_and_configure_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountsService_CreateAndConfigureAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py new file mode 100644 index 000000000000..76bb07735374 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_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 CreateAndConfigureAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_CreateAndConfigureAccount_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_accounts_v1 + + +def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = client.create_and_configure_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountsService_CreateAndConfigureAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py new file mode 100644 index 000000000000..9c8fa5bc83a7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_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 DeleteAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_DeleteAccount_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_accounts_v1 + + +async def sample_delete_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_account(request=request) + + +# [END merchantapi_v1_generated_AccountsService_DeleteAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py new file mode 100644 index 000000000000..619c35397c14 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_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 DeleteAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_DeleteAccount_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_accounts_v1 + + +def sample_delete_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_account(request=request) + + +# [END merchantapi_v1_generated_AccountsService_DeleteAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py new file mode 100644 index 000000000000..c698de6753ff --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_GetAccount_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_accounts_v1 + + +async def sample_get_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountsService_GetAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py new file mode 100644 index 000000000000..c621891021c0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_GetAccount_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_accounts_v1 + + +def sample_get_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountsService_GetAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py new file mode 100644 index 000000000000..557b084f0c99 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAccounts +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_ListAccounts_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_accounts_v1 + + +async def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountsService_ListAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py new file mode 100644 index 000000000000..3c9675b646da --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAccounts +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_ListAccounts_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_accounts_v1 + + +def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountsService_ListAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py new file mode 100644 index 000000000000..875a5ad51d19 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_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 ListSubAccounts +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_ListSubAccounts_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_accounts_v1 + + +async def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountsService_ListSubAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py new file mode 100644 index 000000000000..eb527d0050e6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_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 ListSubAccounts +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_ListSubAccounts_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_accounts_v1 + + +def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_AccountsService_ListSubAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py new file mode 100644 index 000000000000..0037edddf41c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_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 UpdateAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_UpdateAccount_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_accounts_v1 + + +async def sample_update_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = await client.update_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountsService_UpdateAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py new file mode 100644 index 000000000000..31da1d961689 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_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 UpdateAccount +# 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-accounts + + +# [START merchantapi_v1_generated_AccountsService_UpdateAccount_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_accounts_v1 + + +def sample_update_account(): + # Create a client + client = merchant_accounts_v1.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = client.update_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AccountsService_UpdateAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py new file mode 100644 index 000000000000..a93e750d761b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1_generated_AutofeedSettingsService_GetAutofeedSettings_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_accounts_v1 + + +async def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutofeedSettingsService_GetAutofeedSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py new file mode 100644 index 000000000000..5adaf3fe29de --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1_generated_AutofeedSettingsService_GetAutofeedSettings_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_accounts_v1 + + +def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutofeedSettingsService_GetAutofeedSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py new file mode 100644 index 000000000000..7e9cf0bab2c6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1_generated_AutofeedSettingsService_UpdateAutofeedSettings_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_accounts_v1 + + +async def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = await client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutofeedSettingsService_UpdateAutofeedSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py new file mode 100644 index 000000000000..8e1c98c4800c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1_generated_AutofeedSettingsService_UpdateAutofeedSettings_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_accounts_v1 + + +def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutofeedSettingsService_UpdateAutofeedSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py new file mode 100644 index 000000000000..78827f6f6263 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1_generated_AutomaticImprovementsService_GetAutomaticImprovements_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_accounts_v1 + + +async def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutomaticImprovementsService_GetAutomaticImprovements_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py new file mode 100644 index 000000000000..a1e0e45146c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1_generated_AutomaticImprovementsService_GetAutomaticImprovements_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_accounts_v1 + + +def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutomaticImprovementsService_GetAutomaticImprovements_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py new file mode 100644 index 000000000000..ae53e1faf8b5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_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_accounts_v1 + + +async def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = await client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py new file mode 100644 index 000000000000..eb916008b7e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_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_accounts_v1 + + +def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py new file mode 100644 index 000000000000..d9b664f92913 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessIdentityService_GetBusinessIdentity_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_accounts_v1 + + +async def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessIdentityService_GetBusinessIdentity_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py new file mode 100644 index 000000000000..ce01fb2d6573 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessIdentityService_GetBusinessIdentity_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_accounts_v1 + + +def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessIdentityService_GetBusinessIdentity_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py new file mode 100644 index 000000000000..3aedd450caaa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessIdentityService_UpdateBusinessIdentity_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_accounts_v1 + + +async def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + business_identity = merchant_accounts_v1.BusinessIdentity() + business_identity.promotions_consent = "PROMOTIONS_CONSENT_DENIED" + + request = merchant_accounts_v1.UpdateBusinessIdentityRequest( + business_identity=business_identity, + ) + + # Make the request + response = await client.update_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessIdentityService_UpdateBusinessIdentity_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py new file mode 100644 index 000000000000..b19fd7db0c10 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessIdentityService_UpdateBusinessIdentity_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_accounts_v1 + + +def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1.BusinessIdentityServiceClient() + + # Initialize request argument(s) + business_identity = merchant_accounts_v1.BusinessIdentity() + business_identity.promotions_consent = "PROMOTIONS_CONSENT_DENIED" + + request = merchant_accounts_v1.UpdateBusinessIdentityRequest( + business_identity=business_identity, + ) + + # Make the request + response = client.update_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessIdentityService_UpdateBusinessIdentity_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py new file mode 100644 index 000000000000..f10f574b0aa9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessInfo +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessInfoService_GetBusinessInfo_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_accounts_v1 + + +async def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessInfoService_GetBusinessInfo_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py new file mode 100644 index 000000000000..aaecdc2ac1bc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessInfo +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessInfoService_GetBusinessInfo_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_accounts_v1 + + +def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessInfoService_GetBusinessInfo_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py new file mode 100644 index 000000000000..140effde75de --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessInfo +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessInfoService_UpdateBusinessInfo_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_accounts_v1 + + +async def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateBusinessInfoRequest( + ) + + # Make the request + response = await client.update_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessInfoService_UpdateBusinessInfo_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py new file mode 100644 index 000000000000..987ae656dc17 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessInfo +# 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-accounts + + +# [START merchantapi_v1_generated_BusinessInfoService_UpdateBusinessInfo_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_accounts_v1 + + +def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateBusinessInfoRequest( + ) + + # Make the request + response = client.update_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_BusinessInfoService_UpdateBusinessInfo_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py new file mode 100644 index 000000000000..d0c558661bee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_CreateCheckoutSettings_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_accounts_v1 + + +async def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_CheckoutSettingsService_CreateCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py new file mode 100644 index 000000000000..07c893752feb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_CreateCheckoutSettings_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_accounts_v1 + + +def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_CheckoutSettingsService_CreateCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py new file mode 100644 index 000000000000..f33ae7d54bc3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_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 DeleteCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_accounts_v1 + + +async def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + await client.delete_checkout_settings(request=request) + + +# [END merchantapi_v1_generated_CheckoutSettingsService_DeleteCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py new file mode 100644 index 000000000000..f2a38986ccb7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_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 DeleteCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_accounts_v1 + + +def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + client.delete_checkout_settings(request=request) + + +# [END merchantapi_v1_generated_CheckoutSettingsService_DeleteCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py new file mode 100644 index 000000000000..02389b6ffae9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_GetCheckoutSettings_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_accounts_v1 + + +async def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_CheckoutSettingsService_GetCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py new file mode 100644 index 000000000000..08f2a0064f0e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_GetCheckoutSettings_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_accounts_v1 + + +def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_CheckoutSettingsService_GetCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py new file mode 100644 index 000000000000..284590d07f9b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_UpdateCheckoutSettings_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_accounts_v1 + + +async def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = await client.update_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_CheckoutSettingsService_UpdateCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py new file mode 100644 index 000000000000..80bb71fb2105 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1_generated_CheckoutSettingsService_UpdateCheckoutSettings_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_accounts_v1 + + +def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = client.update_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_CheckoutSettingsService_UpdateCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py new file mode 100644 index 000000000000..39d9d5ff43f6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDeveloperRegistration +# 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-accounts + + +# [START merchantapi_v1_generated_DeveloperRegistrationService_GetDeveloperRegistration_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_accounts_v1 + + +async def sample_get_developer_registration(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetDeveloperRegistrationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_developer_registration(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_DeveloperRegistrationService_GetDeveloperRegistration_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py new file mode 100644 index 000000000000..dc2acbdee568 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDeveloperRegistration +# 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-accounts + + +# [START merchantapi_v1_generated_DeveloperRegistrationService_GetDeveloperRegistration_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_accounts_v1 + + +def sample_get_developer_registration(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetDeveloperRegistrationRequest( + name="name_value", + ) + + # Make the request + response = client.get_developer_registration(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_DeveloperRegistrationService_GetDeveloperRegistration_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py new file mode 100644 index 000000000000..0f09220cae7d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RegisterGcp +# 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-accounts + + +# [START merchantapi_v1_generated_DeveloperRegistrationService_RegisterGcp_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_accounts_v1 + + +async def sample_register_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RegisterGcpRequest( + name="name_value", + ) + + # Make the request + response = await client.register_gcp(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_DeveloperRegistrationService_RegisterGcp_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py new file mode 100644 index 000000000000..1abf35592a42 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RegisterGcp +# 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-accounts + + +# [START merchantapi_v1_generated_DeveloperRegistrationService_RegisterGcp_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_accounts_v1 + + +def sample_register_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RegisterGcpRequest( + name="name_value", + ) + + # Make the request + response = client.register_gcp(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_DeveloperRegistrationService_RegisterGcp_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py new file mode 100644 index 000000000000..5aec9c179d6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_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 UnregisterGcp +# 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-accounts + + +# [START merchantapi_v1_generated_DeveloperRegistrationService_UnregisterGcp_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_accounts_v1 + + +async def sample_unregister_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnregisterGcpRequest( + name="name_value", + ) + + # Make the request + await client.unregister_gcp(request=request) + + +# [END merchantapi_v1_generated_DeveloperRegistrationService_UnregisterGcp_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py new file mode 100644 index 000000000000..df00b9908cfc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_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 UnregisterGcp +# 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-accounts + + +# [START merchantapi_v1_generated_DeveloperRegistrationService_UnregisterGcp_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_accounts_v1 + + +def sample_unregister_gcp(): + # Create a client + client = merchant_accounts_v1.DeveloperRegistrationServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnregisterGcpRequest( + name="name_value", + ) + + # Make the request + client.unregister_gcp(request=request) + + +# [END merchantapi_v1_generated_DeveloperRegistrationService_UnregisterGcp_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py new file mode 100644 index 000000000000..3b07a84fa8d4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEmailPreferences +# 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-accounts + + +# [START merchantapi_v1_generated_EmailPreferencesService_GetEmailPreferences_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_accounts_v1 + + +async def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_EmailPreferencesService_GetEmailPreferences_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py new file mode 100644 index 000000000000..0e33e0656c02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEmailPreferences +# 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-accounts + + +# [START merchantapi_v1_generated_EmailPreferencesService_GetEmailPreferences_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_accounts_v1 + + +def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = client.get_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_EmailPreferencesService_GetEmailPreferences_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py new file mode 100644 index 000000000000..a9a78c0dfa85 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEmailPreferences +# 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-accounts + + +# [START merchantapi_v1_generated_EmailPreferencesService_UpdateEmailPreferences_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_accounts_v1 + + +async def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = await client.update_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_EmailPreferencesService_UpdateEmailPreferences_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py new file mode 100644 index 000000000000..19633b4b61f3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEmailPreferences +# 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-accounts + + +# [START merchantapi_v1_generated_EmailPreferencesService_UpdateEmailPreferences_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_accounts_v1 + + +def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = client.update_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_EmailPreferencesService_UpdateEmailPreferences_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py new file mode 100644 index 000000000000..b866b3ea4d28 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_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 LinkGbpAccount +# 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-accounts + + +# [START merchantapi_v1_generated_GbpAccountsService_LinkGbpAccount_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_accounts_v1 + + +async def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = await client.link_gbp_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_GbpAccountsService_LinkGbpAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py new file mode 100644 index 000000000000..73af9dccb2ba --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_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 LinkGbpAccount +# 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-accounts + + +# [START merchantapi_v1_generated_GbpAccountsService_LinkGbpAccount_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_accounts_v1 + + +def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = client.link_gbp_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_GbpAccountsService_LinkGbpAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py new file mode 100644 index 000000000000..3bd3ffe6bac5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_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 ListGbpAccounts +# 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-accounts + + +# [START merchantapi_v1_generated_GbpAccountsService_ListGbpAccounts_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_accounts_v1 + + +async def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_GbpAccountsService_ListGbpAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py new file mode 100644 index 000000000000..e5b77c07a1d1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_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 ListGbpAccounts +# 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-accounts + + +# [START merchantapi_v1_generated_GbpAccountsService_ListGbpAccounts_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_accounts_v1 + + +def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_GbpAccountsService_ListGbpAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py new file mode 100644 index 000000000000..08be3dc472d4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClaimHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_ClaimHomepage_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_accounts_v1 + + +async def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.claim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_ClaimHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py new file mode 100644 index 000000000000..4b93148fb7b6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClaimHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_ClaimHomepage_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_accounts_v1 + + +def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.claim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_ClaimHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py new file mode 100644 index 000000000000..e557a9653348 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_GetHomepage_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_accounts_v1 + + +async def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_GetHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py new file mode 100644 index 000000000000..797ac6839393 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_GetHomepage_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_accounts_v1 + + +def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.get_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_GetHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py new file mode 100644 index 000000000000..e116d7ea53ce --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UnclaimHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_UnclaimHomepage_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_accounts_v1 + + +async def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.unclaim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_UnclaimHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py new file mode 100644 index 000000000000..86ec842a4f30 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UnclaimHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_UnclaimHomepage_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_accounts_v1 + + +def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.unclaim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_UnclaimHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py new file mode 100644 index 000000000000..e657325b63dd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_UpdateHomepage_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_accounts_v1 + + +async def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateHomepageRequest( + ) + + # Make the request + response = await client.update_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_UpdateHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py new file mode 100644 index 000000000000..fd3789878af7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHomepage +# 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-accounts + + +# [START merchantapi_v1_generated_HomepageService_UpdateHomepage_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_accounts_v1 + + +def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateHomepageRequest( + ) + + # Make the request + response = client.update_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_HomepageService_UpdateHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py new file mode 100644 index 000000000000..130ce88ee27f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_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 FindLfpProviders +# 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-accounts + + +# [START merchantapi_v1_generated_LfpProvidersService_FindLfpProviders_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_accounts_v1 + + +async def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_LfpProvidersService_FindLfpProviders_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py new file mode 100644 index 000000000000..7e7b40fda8c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_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 FindLfpProviders +# 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-accounts + + +# [START merchantapi_v1_generated_LfpProvidersService_FindLfpProviders_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_accounts_v1 + + +def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_LfpProvidersService_FindLfpProviders_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py new file mode 100644 index 000000000000..8bdbf372a019 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_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 LinkLfpProvider +# 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-accounts + + +# [START merchantapi_v1_generated_LfpProvidersService_LinkLfpProvider_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_accounts_v1 + + +async def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = await client.link_lfp_provider(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_LfpProvidersService_LinkLfpProvider_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py new file mode 100644 index 000000000000..fc20a6119121 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_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 LinkLfpProvider +# 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-accounts + + +# [START merchantapi_v1_generated_LfpProvidersService_LinkLfpProvider_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_accounts_v1 + + +def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = client.link_lfp_provider(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_LfpProvidersService_LinkLfpProvider_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py new file mode 100644 index 000000000000..aa89ec9d84f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py @@ -0,0 +1,57 @@ +# -*- 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 CreateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_CreateOmnichannelSetting_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_accounts_v1 + + +async def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_CreateOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py new file mode 100644 index 000000000000..397b6f95fb15 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py @@ -0,0 +1,57 @@ +# -*- 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 CreateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_CreateOmnichannelSetting_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_accounts_v1 + + +def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_CreateOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py new file mode 100644 index 000000000000..9ec09e00c715 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_GetOmnichannelSetting_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_accounts_v1 + + +async def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_GetOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py new file mode 100644 index 000000000000..d06400da7599 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_GetOmnichannelSetting_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_accounts_v1 + + +def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_GetOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py new file mode 100644 index 000000000000..ccac85f36535 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_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 ListOmnichannelSettings +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_accounts_v1 + + +async def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_ListOmnichannelSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py new file mode 100644 index 000000000000..aa574da76582 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_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 ListOmnichannelSettings +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_accounts_v1 + + +def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_ListOmnichannelSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py new file mode 100644 index 000000000000..b0adcc91e837 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RequestInventoryVerification +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_RequestInventoryVerification_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_accounts_v1 + + +async def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = await client.request_inventory_verification(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_RequestInventoryVerification_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py new file mode 100644 index 000000000000..819df52af8c3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RequestInventoryVerification +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_RequestInventoryVerification_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_accounts_v1 + + +def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = client.request_inventory_verification(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_RequestInventoryVerification_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py new file mode 100644 index 000000000000..b3c5fc549905 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_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 UpdateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_accounts_v1 + + +async def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py new file mode 100644 index 000000000000..8af9205dce34 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_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 UpdateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_accounts_v1 + + +def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py new file mode 100644 index 000000000000..d93aa2ec03db --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py @@ -0,0 +1,57 @@ +# -*- 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 CreateOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_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_accounts_v1 + + +async def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1.OnlineReturnPolicy() + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = await client.create_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py new file mode 100644 index 000000000000..38ee982ab218 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py @@ -0,0 +1,57 @@ +# -*- 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 CreateOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_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_accounts_v1 + + +def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1.OnlineReturnPolicy() + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = client.create_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py new file mode 100644 index 000000000000..460d97e52486 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_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 DeleteOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_accounts_v1 + + +async def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + await client.delete_online_return_policy(request=request) + + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py new file mode 100644 index 000000000000..685a6d62feeb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_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 DeleteOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_accounts_v1 + + +def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + client.delete_online_return_policy(request=request) + + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py new file mode 100644 index 000000000000..892d7848d29f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_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_accounts_v1 + + +async def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py new file mode 100644 index 000000000000..190382bd888d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_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_accounts_v1 + + +def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py new file mode 100644 index 000000000000..7bec6af8ac86 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_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 ListOnlineReturnPolicies +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_accounts_v1 + + +async def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py new file mode 100644 index 000000000000..9d006b56654d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_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 ListOnlineReturnPolicies +# 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-accounts + + +# [START merchantapi_v1_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_accounts_v1 + + +def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py new file mode 100644 index 000000000000..e8db2b4084fe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableProgram +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_DisableProgram_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_accounts_v1 + + +async def sample_disable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.disable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ProgramsService_DisableProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py new file mode 100644 index 000000000000..a77f8c86d2c7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableProgram +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_DisableProgram_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_accounts_v1 + + +def sample_disable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.disable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ProgramsService_DisableProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py new file mode 100644 index 000000000000..c466f7bfaf5a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableProgram +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_EnableProgram_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_accounts_v1 + + +async def sample_enable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.enable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ProgramsService_EnableProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py new file mode 100644 index 000000000000..de70cd63243a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableProgram +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_EnableProgram_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_accounts_v1 + + +def sample_enable_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.enable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ProgramsService_EnableProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py new file mode 100644 index 000000000000..48257a84882b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProgram +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_GetProgram_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_accounts_v1 + + +async def sample_get_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.get_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ProgramsService_GetProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py new file mode 100644 index 000000000000..adb871d39162 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProgram +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_GetProgram_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_accounts_v1 + + +def sample_get_program(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = client.get_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ProgramsService_GetProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py new file mode 100644 index 000000000000..21430c49946a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_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 ListPrograms +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_ListPrograms_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_accounts_v1 + + +async def sample_list_programs(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_ProgramsService_ListPrograms_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py new file mode 100644 index 000000000000..f15852625c38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_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 ListPrograms +# 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-accounts + + +# [START merchantapi_v1_generated_ProgramsService_ListPrograms_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_accounts_v1 + + +def sample_list_programs(): + # Create a client + client = merchant_accounts_v1.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_ProgramsService_ListPrograms_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py new file mode 100644 index 000000000000..8fd054452698 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_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 CreateRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_CreateRegion_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_accounts_v1 + + +async def sample_create_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = await client.create_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionsService_CreateRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py new file mode 100644 index 000000000000..f4381a78a417 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_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 CreateRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_CreateRegion_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_accounts_v1 + + +def sample_create_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = client.create_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionsService_CreateRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py new file mode 100644 index 000000000000..d59990180b9c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_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 DeleteRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_DeleteRegion_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_accounts_v1 + + +async def sample_delete_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + await client.delete_region(request=request) + + +# [END merchantapi_v1_generated_RegionsService_DeleteRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py new file mode 100644 index 000000000000..ec2325c15c63 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_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 DeleteRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_DeleteRegion_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_accounts_v1 + + +def sample_delete_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + client.delete_region(request=request) + + +# [END merchantapi_v1_generated_RegionsService_DeleteRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py new file mode 100644 index 000000000000..2211254f6f70 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_GetRegion_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_accounts_v1 + + +async def sample_get_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionsService_GetRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py new file mode 100644 index 000000000000..2de8e50ca472 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_GetRegion_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_accounts_v1 + + +def sample_get_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = client.get_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionsService_GetRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py new file mode 100644 index 000000000000..55502ef7dab2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_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 ListRegions +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_ListRegions_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_accounts_v1 + + +async def sample_list_regions(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_RegionsService_ListRegions_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py new file mode 100644 index 000000000000..6cc8c56c1bf7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_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 ListRegions +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_ListRegions_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_accounts_v1 + + +def sample_list_regions(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_RegionsService_ListRegions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py new file mode 100644 index 000000000000..42a68daabeb5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_UpdateRegion_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_accounts_v1 + + +async def sample_update_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateRegionRequest( + ) + + # Make the request + response = await client.update_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionsService_UpdateRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py new file mode 100644 index 000000000000..1ced0569f6a4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRegion +# 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-accounts + + +# [START merchantapi_v1_generated_RegionsService_UpdateRegion_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_accounts_v1 + + +def sample_update_region(): + # Create a client + client = merchant_accounts_v1.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.UpdateRegionRequest( + ) + + # Make the request + response = client.update_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_RegionsService_UpdateRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py new file mode 100644 index 000000000000..9594ea496e8d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetShippingSettings +# 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-accounts + + +# [START merchantapi_v1_generated_ShippingSettingsService_GetShippingSettings_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_accounts_v1 + + +async def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ShippingSettingsService_GetShippingSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py new file mode 100644 index 000000000000..d19e87705984 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetShippingSettings +# 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-accounts + + +# [START merchantapi_v1_generated_ShippingSettingsService_GetShippingSettings_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_accounts_v1 + + +def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ShippingSettingsService_GetShippingSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py new file mode 100644 index 000000000000..59e93d835938 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_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 InsertShippingSettings +# 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-accounts + + +# [START merchantapi_v1_generated_ShippingSettingsService_InsertShippingSettings_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_accounts_v1 + + +async def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = await client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ShippingSettingsService_InsertShippingSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py new file mode 100644 index 000000000000..f8c0955031f0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_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 InsertShippingSettings +# 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-accounts + + +# [START merchantapi_v1_generated_ShippingSettingsService_InsertShippingSettings_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_accounts_v1 + + +def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1.ShippingSettingsServiceClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_ShippingSettingsService_InsertShippingSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py new file mode 100644 index 000000000000..edc403cc8f95 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_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_accounts_v1 + + +async def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py new file mode 100644 index 000000000000..72c0f9b8a225 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_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_accounts_v1 + + +def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py new file mode 100644 index 000000000000..7537760d2b29 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveForApplicationTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_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_accounts_v1 + + +async def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py new file mode 100644 index 000000000000..d97090242a98 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveForApplicationTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_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_accounts_v1 + + +def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py new file mode 100644 index 000000000000..fdaf630dca9d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py @@ -0,0 +1,54 @@ +# -*- 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 AcceptTermsOfService +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceService_AcceptTermsOfService_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_accounts_v1 + + +async def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + response = await client.accept_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceService_AcceptTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py new file mode 100644 index 000000000000..02ffee04ce99 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py @@ -0,0 +1,54 @@ +# -*- 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 AcceptTermsOfService +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceService_AcceptTermsOfService_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_accounts_v1 + + +def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + response = client.accept_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceService_AcceptTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py new file mode 100644 index 000000000000..e409c2788ecd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfService +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceService_GetTermsOfService_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_accounts_v1 + + +async def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceService_GetTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py new file mode 100644 index 000000000000..eeebc4c1bfe9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfService +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceService_GetTermsOfService_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_accounts_v1 + + +def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceService_GetTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py new file mode 100644 index 000000000000..3fcfd9f40128 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_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 RetrieveLatestTermsOfService +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceService_RetrieveLatestTermsOfService_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_accounts_v1 + + +async def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = await client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceService_RetrieveLatestTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py new file mode 100644 index 000000000000..b5d964d8e873 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_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 RetrieveLatestTermsOfService +# 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-accounts + + +# [START merchantapi_v1_generated_TermsOfServiceService_RetrieveLatestTermsOfService_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_accounts_v1 + + +def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_TermsOfServiceService_RetrieveLatestTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py new file mode 100644 index 000000000000..73590f7fd971 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_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 CreateUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_CreateUser_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_accounts_v1 + + +async def sample_create_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_UserService_CreateUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py new file mode 100644 index 000000000000..80b0185e4a7d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_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 CreateUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_CreateUser_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_accounts_v1 + + +def sample_create_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_UserService_CreateUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py new file mode 100644 index 000000000000..d9a5f0d06d3e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_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 DeleteUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_DeleteUser_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_accounts_v1 + + +async def sample_delete_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + +# [END merchantapi_v1_generated_UserService_DeleteUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py new file mode 100644 index 000000000000..525d0f86bbb2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_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 DeleteUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_DeleteUser_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_accounts_v1 + + +def sample_delete_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + +# [END merchantapi_v1_generated_UserService_DeleteUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py new file mode 100644 index 000000000000..d78241f91a22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_GetUser_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_accounts_v1 + + +async def sample_get_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_UserService_GetUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py new file mode 100644 index 000000000000..e405560d6802 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_GetUser_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_accounts_v1 + + +def sample_get_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_UserService_GetUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py new file mode 100644 index 000000000000..f2b727350461 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_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 ListUsers +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_ListUsers_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_accounts_v1 + + +async def sample_list_users(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1_generated_UserService_ListUsers_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py new file mode 100644 index 000000000000..5573fb313981 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_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 ListUsers +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_ListUsers_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_accounts_v1 + + +def sample_list_users(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1_generated_UserService_ListUsers_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py new file mode 100644 index 000000000000..88530902bdbc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_UpdateUser_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_accounts_v1 + + +async def sample_update_user(): + # Create a client + client = merchant_accounts_v1.UserServiceAsyncClient() + + # Initialize request argument(s) + user = merchant_accounts_v1.User() + user.access_rights = ['API_DEVELOPER'] + + request = merchant_accounts_v1.UpdateUserRequest( + user=user, + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_UserService_UpdateUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py new file mode 100644 index 000000000000..52cef06d8594 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# 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-accounts + + +# [START merchantapi_v1_generated_UserService_UpdateUser_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_accounts_v1 + + +def sample_update_user(): + # Create a client + client = merchant_accounts_v1.UserServiceClient() + + # Initialize request argument(s) + user = merchant_accounts_v1.User() + user.access_rights = ['API_DEVELOPER'] + + request = merchant_accounts_v1.UpdateUserRequest( + user=user, + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1_generated_UserService_UpdateUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json new file mode 100644 index 000000000000..3ac0cbaa9859 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json @@ -0,0 +1,11347 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.accounts.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-accounts", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountIssueServiceAsyncClient", + "shortName": "AccountIssueServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountIssueServiceAsyncClient.list_account_issues", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountIssueService.ListAccountIssues", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountIssueService", + "shortName": "AccountIssueService" + }, + "shortName": "ListAccountIssues" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountIssuesRequest" + }, + { + "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_accounts_v1.services.account_issue_service.pagers.ListAccountIssuesAsyncPager", + "shortName": "list_account_issues" + }, + "description": "Sample for ListAccountIssues", + "file": "merchantapi_v1_generated_account_issue_service_list_account_issues_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountIssueService_ListAccountIssues_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_account_issue_service_list_account_issues_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountIssueServiceClient", + "shortName": "AccountIssueServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountIssueServiceClient.list_account_issues", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountIssueService.ListAccountIssues", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountIssueService", + "shortName": "AccountIssueService" + }, + "shortName": "ListAccountIssues" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountIssuesRequest" + }, + { + "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_accounts_v1.services.account_issue_service.pagers.ListAccountIssuesPager", + "shortName": "list_account_issues" + }, + "description": "Sample for ListAccountIssues", + "file": "merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountIssueService_ListAccountIssues_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_account_issue_service_list_account_issues_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceAsyncClient", + "shortName": "AccountRelationshipsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceAsyncClient.get_account_relationship", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService.GetAccountRelationship", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "shortName": "AccountRelationshipsService" + }, + "shortName": "GetAccountRelationship" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAccountRelationshipRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AccountRelationship", + "shortName": "get_account_relationship" + }, + "description": "Sample for GetAccountRelationship", + "file": "merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountRelationshipsService_GetAccountRelationship_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceClient", + "shortName": "AccountRelationshipsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceClient.get_account_relationship", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService.GetAccountRelationship", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "shortName": "AccountRelationshipsService" + }, + "shortName": "GetAccountRelationship" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAccountRelationshipRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AccountRelationship", + "shortName": "get_account_relationship" + }, + "description": "Sample for GetAccountRelationship", + "file": "merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountRelationshipsService_GetAccountRelationship_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceAsyncClient", + "shortName": "AccountRelationshipsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceAsyncClient.list_account_relationships", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService.ListAccountRelationships", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "shortName": "AccountRelationshipsService" + }, + "shortName": "ListAccountRelationships" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsRequest" + }, + { + "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_accounts_v1.services.account_relationships_service.pagers.ListAccountRelationshipsAsyncPager", + "shortName": "list_account_relationships" + }, + "description": "Sample for ListAccountRelationships", + "file": "merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountRelationshipsService_ListAccountRelationships_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_account_relationships_service_list_account_relationships_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceClient", + "shortName": "AccountRelationshipsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceClient.list_account_relationships", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService.ListAccountRelationships", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "shortName": "AccountRelationshipsService" + }, + "shortName": "ListAccountRelationships" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountRelationshipsRequest" + }, + { + "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_accounts_v1.services.account_relationships_service.pagers.ListAccountRelationshipsPager", + "shortName": "list_account_relationships" + }, + "description": "Sample for ListAccountRelationships", + "file": "merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountRelationshipsService_ListAccountRelationships_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_account_relationships_service_list_account_relationships_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceAsyncClient", + "shortName": "AccountRelationshipsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceAsyncClient.update_account_relationship", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService.UpdateAccountRelationship", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "shortName": "AccountRelationshipsService" + }, + "shortName": "UpdateAccountRelationship" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAccountRelationshipRequest" + }, + { + "name": "account_relationship", + "type": "google.shopping.merchant_accounts_v1.types.AccountRelationship" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.AccountRelationship", + "shortName": "update_account_relationship" + }, + "description": "Sample for UpdateAccountRelationship", + "file": "merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountRelationshipsService_UpdateAccountRelationship_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceClient", + "shortName": "AccountRelationshipsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountRelationshipsServiceClient.update_account_relationship", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService.UpdateAccountRelationship", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", + "shortName": "AccountRelationshipsService" + }, + "shortName": "UpdateAccountRelationship" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAccountRelationshipRequest" + }, + { + "name": "account_relationship", + "type": "google.shopping.merchant_accounts_v1.types.AccountRelationship" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.AccountRelationship", + "shortName": "update_account_relationship" + }, + "description": "Sample for UpdateAccountRelationship", + "file": "merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountRelationshipsService_UpdateAccountRelationship_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient", + "shortName": "AccountServicesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient.approve_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.ApproveAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "ApproveAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ApproveAccountServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AccountService", + "shortName": "approve_account_service" + }, + "description": "Sample for ApproveAccountService", + "file": "merchantapi_v1_generated_account_services_service_approve_account_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_ApproveAccountService_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_services_service_approve_account_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient", + "shortName": "AccountServicesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient.approve_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.ApproveAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "ApproveAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ApproveAccountServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AccountService", + "shortName": "approve_account_service" + }, + "description": "Sample for ApproveAccountService", + "file": "merchantapi_v1_generated_account_services_service_approve_account_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_ApproveAccountService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_services_service_approve_account_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient", + "shortName": "AccountServicesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient.get_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.GetAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "GetAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAccountServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AccountService", + "shortName": "get_account_service" + }, + "description": "Sample for GetAccountService", + "file": "merchantapi_v1_generated_account_services_service_get_account_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_GetAccountService_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_services_service_get_account_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient", + "shortName": "AccountServicesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient.get_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.GetAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "GetAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAccountServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AccountService", + "shortName": "get_account_service" + }, + "description": "Sample for GetAccountService", + "file": "merchantapi_v1_generated_account_services_service_get_account_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_GetAccountService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_services_service_get_account_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient", + "shortName": "AccountServicesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient.list_account_services", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.ListAccountServices", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "ListAccountServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountServicesRequest" + }, + { + "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_accounts_v1.services.account_services_service.pagers.ListAccountServicesAsyncPager", + "shortName": "list_account_services" + }, + "description": "Sample for ListAccountServices", + "file": "merchantapi_v1_generated_account_services_service_list_account_services_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_ListAccountServices_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_account_services_service_list_account_services_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient", + "shortName": "AccountServicesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient.list_account_services", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.ListAccountServices", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "ListAccountServices" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountServicesRequest" + }, + { + "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_accounts_v1.services.account_services_service.pagers.ListAccountServicesPager", + "shortName": "list_account_services" + }, + "description": "Sample for ListAccountServices", + "file": "merchantapi_v1_generated_account_services_service_list_account_services_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_ListAccountServices_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_account_services_service_list_account_services_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient", + "shortName": "AccountServicesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient.propose_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.ProposeAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "ProposeAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ProposeAccountServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "provider", + "type": "str" + }, + { + "name": "account_service", + "type": "google.shopping.merchant_accounts_v1.types.AccountService" + }, + { + "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_accounts_v1.types.AccountService", + "shortName": "propose_account_service" + }, + "description": "Sample for ProposeAccountService", + "file": "merchantapi_v1_generated_account_services_service_propose_account_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_ProposeAccountService_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_services_service_propose_account_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient", + "shortName": "AccountServicesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient.propose_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.ProposeAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "ProposeAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ProposeAccountServiceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "provider", + "type": "str" + }, + { + "name": "account_service", + "type": "google.shopping.merchant_accounts_v1.types.AccountService" + }, + { + "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_accounts_v1.types.AccountService", + "shortName": "propose_account_service" + }, + "description": "Sample for ProposeAccountService", + "file": "merchantapi_v1_generated_account_services_service_propose_account_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_ProposeAccountService_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_account_services_service_propose_account_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient", + "shortName": "AccountServicesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceAsyncClient.reject_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.RejectAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "RejectAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RejectAccountServiceRequest" + }, + { + "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": "reject_account_service" + }, + "description": "Sample for RejectAccountService", + "file": "merchantapi_v1_generated_account_services_service_reject_account_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_RejectAccountService_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_account_services_service_reject_account_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient", + "shortName": "AccountServicesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountServicesServiceClient.reject_account_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService.RejectAccountService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountServicesService", + "shortName": "AccountServicesService" + }, + "shortName": "RejectAccountService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RejectAccountServiceRequest" + }, + { + "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": "reject_account_service" + }, + "description": "Sample for RejectAccountService", + "file": "merchantapi_v1_generated_account_services_service_reject_account_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountServicesService_RejectAccountService_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_account_services_service_reject_account_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient.create_and_configure_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.CreateAndConfigureAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "CreateAndConfigureAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateAndConfigureAccountRequest" + }, + { + "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_accounts_v1.types.Account", + "shortName": "create_and_configure_account" + }, + "description": "Sample for CreateAndConfigureAccount", + "file": "merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_CreateAndConfigureAccount_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_accounts_service_create_and_configure_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient.create_and_configure_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.CreateAndConfigureAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "CreateAndConfigureAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateAndConfigureAccountRequest" + }, + { + "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_accounts_v1.types.Account", + "shortName": "create_and_configure_account" + }, + "description": "Sample for CreateAndConfigureAccount", + "file": "merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_CreateAndConfigureAccount_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_accounts_service_create_and_configure_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient.delete_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.DeleteAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "DeleteAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteAccountRequest" + }, + { + "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_account" + }, + "description": "Sample for DeleteAccount", + "file": "merchantapi_v1_generated_accounts_service_delete_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_DeleteAccount_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_accounts_service_delete_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient.delete_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.DeleteAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "DeleteAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteAccountRequest" + }, + { + "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_account" + }, + "description": "Sample for DeleteAccount", + "file": "merchantapi_v1_generated_accounts_service_delete_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_DeleteAccount_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_accounts_service_delete_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient.get_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.GetAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "GetAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAccountRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Account", + "shortName": "get_account" + }, + "description": "Sample for GetAccount", + "file": "merchantapi_v1_generated_accounts_service_get_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_GetAccount_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_accounts_service_get_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient.get_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.GetAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "GetAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAccountRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Account", + "shortName": "get_account" + }, + "description": "Sample for GetAccount", + "file": "merchantapi_v1_generated_accounts_service_get_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_GetAccount_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_accounts_service_get_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient.list_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.ListAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountsRequest" + }, + { + "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_accounts_v1.services.accounts_service.pagers.ListAccountsAsyncPager", + "shortName": "list_accounts" + }, + "description": "Sample for ListAccounts", + "file": "merchantapi_v1_generated_accounts_service_list_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_ListAccounts_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_accounts_service_list_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient.list_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.ListAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListAccountsRequest" + }, + { + "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_accounts_v1.services.accounts_service.pagers.ListAccountsPager", + "shortName": "list_accounts" + }, + "description": "Sample for ListAccounts", + "file": "merchantapi_v1_generated_accounts_service_list_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_ListAccounts_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_accounts_service_list_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient.list_sub_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.ListSubAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListSubAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListSubAccountsRequest" + }, + { + "name": "provider", + "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_accounts_v1.services.accounts_service.pagers.ListSubAccountsAsyncPager", + "shortName": "list_sub_accounts" + }, + "description": "Sample for ListSubAccounts", + "file": "merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_ListSubAccounts_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_accounts_service_list_sub_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient.list_sub_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.ListSubAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListSubAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListSubAccountsRequest" + }, + { + "name": "provider", + "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_accounts_v1.services.accounts_service.pagers.ListSubAccountsPager", + "shortName": "list_sub_accounts" + }, + "description": "Sample for ListSubAccounts", + "file": "merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_ListSubAccounts_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_accounts_service_list_sub_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceAsyncClient.update_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.UpdateAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "UpdateAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAccountRequest" + }, + { + "name": "account", + "type": "google.shopping.merchant_accounts_v1.types.Account" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.Account", + "shortName": "update_account" + }, + "description": "Sample for UpdateAccount", + "file": "merchantapi_v1_generated_accounts_service_update_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_UpdateAccount_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_accounts_service_update_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AccountsServiceClient.update_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService.UpdateAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "UpdateAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAccountRequest" + }, + { + "name": "account", + "type": "google.shopping.merchant_accounts_v1.types.Account" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.Account", + "shortName": "update_account" + }, + "description": "Sample for UpdateAccount", + "file": "merchantapi_v1_generated_accounts_service_update_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AccountsService_UpdateAccount_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_accounts_service_update_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceAsyncClient", + "shortName": "AutofeedSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceAsyncClient.get_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService.GetAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "GetAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAutofeedSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AutofeedSettings", + "shortName": "get_autofeed_settings" + }, + "description": "Sample for GetAutofeedSettings", + "file": "merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutofeedSettingsService_GetAutofeedSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceClient", + "shortName": "AutofeedSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceClient.get_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService.GetAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "GetAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAutofeedSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AutofeedSettings", + "shortName": "get_autofeed_settings" + }, + "description": "Sample for GetAutofeedSettings", + "file": "merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutofeedSettingsService_GetAutofeedSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceAsyncClient", + "shortName": "AutofeedSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceAsyncClient.update_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService.UpdateAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "UpdateAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAutofeedSettingsRequest" + }, + { + "name": "autofeed_settings", + "type": "google.shopping.merchant_accounts_v1.types.AutofeedSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.AutofeedSettings", + "shortName": "update_autofeed_settings" + }, + "description": "Sample for UpdateAutofeedSettings", + "file": "merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutofeedSettingsService_UpdateAutofeedSettings_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceClient", + "shortName": "AutofeedSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutofeedSettingsServiceClient.update_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService.UpdateAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "UpdateAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAutofeedSettingsRequest" + }, + { + "name": "autofeed_settings", + "type": "google.shopping.merchant_accounts_v1.types.AutofeedSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.AutofeedSettings", + "shortName": "update_autofeed_settings" + }, + "description": "Sample for UpdateAutofeedSettings", + "file": "merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutofeedSettingsService_UpdateAutofeedSettings_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient", + "shortName": "AutomaticImprovementsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient.get_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService.GetAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "GetAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAutomaticImprovementsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AutomaticImprovements", + "shortName": "get_automatic_improvements" + }, + "description": "Sample for GetAutomaticImprovements", + "file": "merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutomaticImprovementsService_GetAutomaticImprovements_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceClient", + "shortName": "AutomaticImprovementsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceClient.get_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService.GetAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "GetAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetAutomaticImprovementsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AutomaticImprovements", + "shortName": "get_automatic_improvements" + }, + "description": "Sample for GetAutomaticImprovements", + "file": "merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutomaticImprovementsService_GetAutomaticImprovements_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient", + "shortName": "AutomaticImprovementsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceAsyncClient.update_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService.UpdateAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "UpdateAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAutomaticImprovementsRequest" + }, + { + "name": "automatic_improvements", + "type": "google.shopping.merchant_accounts_v1.types.AutomaticImprovements" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.AutomaticImprovements", + "shortName": "update_automatic_improvements" + }, + "description": "Sample for UpdateAutomaticImprovements", + "file": "merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceClient", + "shortName": "AutomaticImprovementsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.AutomaticImprovementsServiceClient.update_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService.UpdateAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "UpdateAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateAutomaticImprovementsRequest" + }, + { + "name": "automatic_improvements", + "type": "google.shopping.merchant_accounts_v1.types.AutomaticImprovements" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.AutomaticImprovements", + "shortName": "update_automatic_improvements" + }, + "description": "Sample for UpdateAutomaticImprovements", + "file": "merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceAsyncClient", + "shortName": "BusinessIdentityServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceAsyncClient.get_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService.GetBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "GetBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetBusinessIdentityRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.BusinessIdentity", + "shortName": "get_business_identity" + }, + "description": "Sample for GetBusinessIdentity", + "file": "merchantapi_v1_generated_business_identity_service_get_business_identity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessIdentityService_GetBusinessIdentity_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_identity_service_get_business_identity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceClient", + "shortName": "BusinessIdentityServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceClient.get_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService.GetBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "GetBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetBusinessIdentityRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.BusinessIdentity", + "shortName": "get_business_identity" + }, + "description": "Sample for GetBusinessIdentity", + "file": "merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessIdentityService_GetBusinessIdentity_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceAsyncClient", + "shortName": "BusinessIdentityServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceAsyncClient.update_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService.UpdateBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "UpdateBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateBusinessIdentityRequest" + }, + { + "name": "business_identity", + "type": "google.shopping.merchant_accounts_v1.types.BusinessIdentity" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.BusinessIdentity", + "shortName": "update_business_identity" + }, + "description": "Sample for UpdateBusinessIdentity", + "file": "merchantapi_v1_generated_business_identity_service_update_business_identity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessIdentityService_UpdateBusinessIdentity_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_identity_service_update_business_identity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceClient", + "shortName": "BusinessIdentityServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessIdentityServiceClient.update_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService.UpdateBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "UpdateBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateBusinessIdentityRequest" + }, + { + "name": "business_identity", + "type": "google.shopping.merchant_accounts_v1.types.BusinessIdentity" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.BusinessIdentity", + "shortName": "update_business_identity" + }, + "description": "Sample for UpdateBusinessIdentity", + "file": "merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessIdentityService_UpdateBusinessIdentity_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceAsyncClient", + "shortName": "BusinessInfoServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceAsyncClient.get_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService.GetBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "GetBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetBusinessInfoRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.BusinessInfo", + "shortName": "get_business_info" + }, + "description": "Sample for GetBusinessInfo", + "file": "merchantapi_v1_generated_business_info_service_get_business_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessInfoService_GetBusinessInfo_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_info_service_get_business_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceClient", + "shortName": "BusinessInfoServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceClient.get_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService.GetBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "GetBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetBusinessInfoRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.BusinessInfo", + "shortName": "get_business_info" + }, + "description": "Sample for GetBusinessInfo", + "file": "merchantapi_v1_generated_business_info_service_get_business_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessInfoService_GetBusinessInfo_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_info_service_get_business_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceAsyncClient", + "shortName": "BusinessInfoServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceAsyncClient.update_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService.UpdateBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "UpdateBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateBusinessInfoRequest" + }, + { + "name": "business_info", + "type": "google.shopping.merchant_accounts_v1.types.BusinessInfo" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.BusinessInfo", + "shortName": "update_business_info" + }, + "description": "Sample for UpdateBusinessInfo", + "file": "merchantapi_v1_generated_business_info_service_update_business_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessInfoService_UpdateBusinessInfo_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_info_service_update_business_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceClient", + "shortName": "BusinessInfoServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.BusinessInfoServiceClient.update_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService.UpdateBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "UpdateBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateBusinessInfoRequest" + }, + { + "name": "business_info", + "type": "google.shopping.merchant_accounts_v1.types.BusinessInfo" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.BusinessInfo", + "shortName": "update_business_info" + }, + "description": "Sample for UpdateBusinessInfo", + "file": "merchantapi_v1_generated_business_info_service_update_business_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_BusinessInfoService_UpdateBusinessInfo_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_business_info_service_update_business_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient.create_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.CreateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "CreateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateCheckoutSettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1.types.CheckoutSettings" + }, + { + "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_accounts_v1.types.CheckoutSettings", + "shortName": "create_checkout_settings" + }, + "description": "Sample for CreateCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_CreateCheckoutSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient.create_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.CreateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "CreateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateCheckoutSettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1.types.CheckoutSettings" + }, + { + "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_accounts_v1.types.CheckoutSettings", + "shortName": "create_checkout_settings" + }, + "description": "Sample for CreateCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_CreateCheckoutSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient.delete_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.DeleteCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "DeleteCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteCheckoutSettingsRequest" + }, + { + "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_checkout_settings" + }, + "description": "Sample for DeleteCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_checkout_settings_service_delete_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient.delete_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.DeleteCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "DeleteCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteCheckoutSettingsRequest" + }, + { + "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_checkout_settings" + }, + "description": "Sample for DeleteCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_checkout_settings_service_delete_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient.get_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.GetCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "GetCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetCheckoutSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.CheckoutSettings", + "shortName": "get_checkout_settings" + }, + "description": "Sample for GetCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_GetCheckoutSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient.get_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.GetCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "GetCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetCheckoutSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.CheckoutSettings", + "shortName": "get_checkout_settings" + }, + "description": "Sample for GetCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_GetCheckoutSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceAsyncClient.update_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.UpdateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "UpdateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateCheckoutSettingsRequest" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1.types.CheckoutSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.CheckoutSettings", + "shortName": "update_checkout_settings" + }, + "description": "Sample for UpdateCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_UpdateCheckoutSettings_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.CheckoutSettingsServiceClient.update_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService.UpdateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "UpdateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateCheckoutSettingsRequest" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1.types.CheckoutSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.CheckoutSettings", + "shortName": "update_checkout_settings" + }, + "description": "Sample for UpdateCheckoutSettings", + "file": "merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_CheckoutSettingsService_UpdateCheckoutSettings_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient", + "shortName": "DeveloperRegistrationServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient.get_developer_registration", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService.GetDeveloperRegistration", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "shortName": "DeveloperRegistrationService" + }, + "shortName": "GetDeveloperRegistration" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetDeveloperRegistrationRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.DeveloperRegistration", + "shortName": "get_developer_registration" + }, + "description": "Sample for GetDeveloperRegistration", + "file": "merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_DeveloperRegistrationService_GetDeveloperRegistration_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceClient", + "shortName": "DeveloperRegistrationServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceClient.get_developer_registration", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService.GetDeveloperRegistration", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "shortName": "DeveloperRegistrationService" + }, + "shortName": "GetDeveloperRegistration" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetDeveloperRegistrationRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.DeveloperRegistration", + "shortName": "get_developer_registration" + }, + "description": "Sample for GetDeveloperRegistration", + "file": "merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_DeveloperRegistrationService_GetDeveloperRegistration_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient", + "shortName": "DeveloperRegistrationServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient.register_gcp", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService.RegisterGcp", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "shortName": "DeveloperRegistrationService" + }, + "shortName": "RegisterGcp" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RegisterGcpRequest" + }, + { + "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_accounts_v1.types.DeveloperRegistration", + "shortName": "register_gcp" + }, + "description": "Sample for RegisterGcp", + "file": "merchantapi_v1_generated_developer_registration_service_register_gcp_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_DeveloperRegistrationService_RegisterGcp_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_developer_registration_service_register_gcp_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceClient", + "shortName": "DeveloperRegistrationServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceClient.register_gcp", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService.RegisterGcp", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "shortName": "DeveloperRegistrationService" + }, + "shortName": "RegisterGcp" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RegisterGcpRequest" + }, + { + "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_accounts_v1.types.DeveloperRegistration", + "shortName": "register_gcp" + }, + "description": "Sample for RegisterGcp", + "file": "merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_DeveloperRegistrationService_RegisterGcp_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient", + "shortName": "DeveloperRegistrationServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceAsyncClient.unregister_gcp", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService.UnregisterGcp", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "shortName": "DeveloperRegistrationService" + }, + "shortName": "UnregisterGcp" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UnregisterGcpRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "unregister_gcp" + }, + "description": "Sample for UnregisterGcp", + "file": "merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_DeveloperRegistrationService_UnregisterGcp_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_developer_registration_service_unregister_gcp_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceClient", + "shortName": "DeveloperRegistrationServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.DeveloperRegistrationServiceClient.unregister_gcp", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService.UnregisterGcp", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", + "shortName": "DeveloperRegistrationService" + }, + "shortName": "UnregisterGcp" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UnregisterGcpRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "unregister_gcp" + }, + "description": "Sample for UnregisterGcp", + "file": "merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_DeveloperRegistrationService_UnregisterGcp_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_developer_registration_service_unregister_gcp_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceAsyncClient", + "shortName": "EmailPreferencesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceAsyncClient.get_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService.GetEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "GetEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetEmailPreferencesRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.EmailPreferences", + "shortName": "get_email_preferences" + }, + "description": "Sample for GetEmailPreferences", + "file": "merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_EmailPreferencesService_GetEmailPreferences_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceClient", + "shortName": "EmailPreferencesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceClient.get_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService.GetEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "GetEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetEmailPreferencesRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.EmailPreferences", + "shortName": "get_email_preferences" + }, + "description": "Sample for GetEmailPreferences", + "file": "merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_EmailPreferencesService_GetEmailPreferences_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceAsyncClient", + "shortName": "EmailPreferencesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceAsyncClient.update_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService.UpdateEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "UpdateEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateEmailPreferencesRequest" + }, + { + "name": "email_preferences", + "type": "google.shopping.merchant_accounts_v1.types.EmailPreferences" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.EmailPreferences", + "shortName": "update_email_preferences" + }, + "description": "Sample for UpdateEmailPreferences", + "file": "merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_EmailPreferencesService_UpdateEmailPreferences_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceClient", + "shortName": "EmailPreferencesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.EmailPreferencesServiceClient.update_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService.UpdateEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "UpdateEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateEmailPreferencesRequest" + }, + { + "name": "email_preferences", + "type": "google.shopping.merchant_accounts_v1.types.EmailPreferences" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.EmailPreferences", + "shortName": "update_email_preferences" + }, + "description": "Sample for UpdateEmailPreferences", + "file": "merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_EmailPreferencesService_UpdateEmailPreferences_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceAsyncClient", + "shortName": "GbpAccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceAsyncClient.link_gbp_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService.LinkGbpAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "LinkGbpAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.LinkGbpAccountRequest" + }, + { + "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_accounts_v1.types.LinkGbpAccountResponse", + "shortName": "link_gbp_account" + }, + "description": "Sample for LinkGbpAccount", + "file": "merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_GbpAccountsService_LinkGbpAccount_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceClient", + "shortName": "GbpAccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceClient.link_gbp_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService.LinkGbpAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "LinkGbpAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.LinkGbpAccountRequest" + }, + { + "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_accounts_v1.types.LinkGbpAccountResponse", + "shortName": "link_gbp_account" + }, + "description": "Sample for LinkGbpAccount", + "file": "merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_GbpAccountsService_LinkGbpAccount_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceAsyncClient", + "shortName": "GbpAccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceAsyncClient.list_gbp_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService.ListGbpAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "ListGbpAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListGbpAccountsRequest" + }, + { + "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_accounts_v1.services.gbp_accounts_service.pagers.ListGbpAccountsAsyncPager", + "shortName": "list_gbp_accounts" + }, + "description": "Sample for ListGbpAccounts", + "file": "merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_GbpAccountsService_ListGbpAccounts_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_gbp_accounts_service_list_gbp_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceClient", + "shortName": "GbpAccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.GbpAccountsServiceClient.list_gbp_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService.ListGbpAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "ListGbpAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListGbpAccountsRequest" + }, + { + "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_accounts_v1.services.gbp_accounts_service.pagers.ListGbpAccountsPager", + "shortName": "list_gbp_accounts" + }, + "description": "Sample for ListGbpAccounts", + "file": "merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_GbpAccountsService_ListGbpAccounts_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_gbp_accounts_service_list_gbp_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient.claim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.ClaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "ClaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ClaimHomepageRequest" + }, + { + "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_accounts_v1.types.Homepage", + "shortName": "claim_homepage" + }, + "description": "Sample for ClaimHomepage", + "file": "merchantapi_v1_generated_homepage_service_claim_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_ClaimHomepage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_claim_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient.claim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.ClaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "ClaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ClaimHomepageRequest" + }, + { + "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_accounts_v1.types.Homepage", + "shortName": "claim_homepage" + }, + "description": "Sample for ClaimHomepage", + "file": "merchantapi_v1_generated_homepage_service_claim_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_ClaimHomepage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_claim_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient.get_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.GetHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "GetHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetHomepageRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Homepage", + "shortName": "get_homepage" + }, + "description": "Sample for GetHomepage", + "file": "merchantapi_v1_generated_homepage_service_get_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_GetHomepage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_get_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient.get_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.GetHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "GetHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetHomepageRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Homepage", + "shortName": "get_homepage" + }, + "description": "Sample for GetHomepage", + "file": "merchantapi_v1_generated_homepage_service_get_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_GetHomepage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_get_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient.unclaim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.UnclaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UnclaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UnclaimHomepageRequest" + }, + { + "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_accounts_v1.types.Homepage", + "shortName": "unclaim_homepage" + }, + "description": "Sample for UnclaimHomepage", + "file": "merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_UnclaimHomepage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient.unclaim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.UnclaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UnclaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UnclaimHomepageRequest" + }, + { + "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_accounts_v1.types.Homepage", + "shortName": "unclaim_homepage" + }, + "description": "Sample for UnclaimHomepage", + "file": "merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_UnclaimHomepage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceAsyncClient.update_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.UpdateHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UpdateHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateHomepageRequest" + }, + { + "name": "homepage", + "type": "google.shopping.merchant_accounts_v1.types.Homepage" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.Homepage", + "shortName": "update_homepage" + }, + "description": "Sample for UpdateHomepage", + "file": "merchantapi_v1_generated_homepage_service_update_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_UpdateHomepage_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_update_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.HomepageServiceClient.update_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService.UpdateHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UpdateHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateHomepageRequest" + }, + { + "name": "homepage", + "type": "google.shopping.merchant_accounts_v1.types.Homepage" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.Homepage", + "shortName": "update_homepage" + }, + "description": "Sample for UpdateHomepage", + "file": "merchantapi_v1_generated_homepage_service_update_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_HomepageService_UpdateHomepage_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_homepage_service_update_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceAsyncClient", + "shortName": "LfpProvidersServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceAsyncClient.find_lfp_providers", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService.FindLfpProviders", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "FindLfpProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.FindLfpProvidersRequest" + }, + { + "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_accounts_v1.services.lfp_providers_service.pagers.FindLfpProvidersAsyncPager", + "shortName": "find_lfp_providers" + }, + "description": "Sample for FindLfpProviders", + "file": "merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LfpProvidersService_FindLfpProviders_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_lfp_providers_service_find_lfp_providers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceClient", + "shortName": "LfpProvidersServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceClient.find_lfp_providers", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService.FindLfpProviders", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "FindLfpProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.FindLfpProvidersRequest" + }, + { + "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_accounts_v1.services.lfp_providers_service.pagers.FindLfpProvidersPager", + "shortName": "find_lfp_providers" + }, + "description": "Sample for FindLfpProviders", + "file": "merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LfpProvidersService_FindLfpProviders_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_lfp_providers_service_find_lfp_providers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceAsyncClient", + "shortName": "LfpProvidersServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceAsyncClient.link_lfp_provider", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService.LinkLfpProvider", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "LinkLfpProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.LinkLfpProviderRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.LinkLfpProviderResponse", + "shortName": "link_lfp_provider" + }, + "description": "Sample for LinkLfpProvider", + "file": "merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LfpProvidersService_LinkLfpProvider_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceClient", + "shortName": "LfpProvidersServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.LfpProvidersServiceClient.link_lfp_provider", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService.LinkLfpProvider", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "LinkLfpProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.LinkLfpProviderRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.LinkLfpProviderResponse", + "shortName": "link_lfp_provider" + }, + "description": "Sample for LinkLfpProvider", + "file": "merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_LfpProvidersService_LinkLfpProvider_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient.create_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.CreateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "CreateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateOmnichannelSettingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1.types.OmnichannelSetting" + }, + { + "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_accounts_v1.types.OmnichannelSetting", + "shortName": "create_omnichannel_setting" + }, + "description": "Sample for CreateOmnichannelSetting", + "file": "merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_CreateOmnichannelSetting_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient.create_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.CreateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "CreateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateOmnichannelSettingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1.types.OmnichannelSetting" + }, + { + "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_accounts_v1.types.OmnichannelSetting", + "shortName": "create_omnichannel_setting" + }, + "description": "Sample for CreateOmnichannelSetting", + "file": "merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_CreateOmnichannelSetting_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient.get_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.GetOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "GetOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetOmnichannelSettingRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.OmnichannelSetting", + "shortName": "get_omnichannel_setting" + }, + "description": "Sample for GetOmnichannelSetting", + "file": "merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_GetOmnichannelSetting_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient.get_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.GetOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "GetOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetOmnichannelSettingRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.OmnichannelSetting", + "shortName": "get_omnichannel_setting" + }, + "description": "Sample for GetOmnichannelSetting", + "file": "merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_GetOmnichannelSetting_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient.list_omnichannel_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.ListOmnichannelSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "ListOmnichannelSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsRequest" + }, + { + "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_accounts_v1.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsAsyncPager", + "shortName": "list_omnichannel_settings" + }, + "description": "Sample for ListOmnichannelSettings", + "file": "merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_omnichannel_settings_service_list_omnichannel_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient.list_omnichannel_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.ListOmnichannelSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "ListOmnichannelSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListOmnichannelSettingsRequest" + }, + { + "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_accounts_v1.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsPager", + "shortName": "list_omnichannel_settings" + }, + "description": "Sample for ListOmnichannelSettings", + "file": "merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_omnichannel_settings_service_list_omnichannel_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient.request_inventory_verification", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.RequestInventoryVerification", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "RequestInventoryVerification" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationResponse", + "shortName": "request_inventory_verification" + }, + "description": "Sample for RequestInventoryVerification", + "file": "merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_RequestInventoryVerification_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient.request_inventory_verification", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.RequestInventoryVerification", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "RequestInventoryVerification" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.RequestInventoryVerificationResponse", + "shortName": "request_inventory_verification" + }, + "description": "Sample for RequestInventoryVerification", + "file": "merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_RequestInventoryVerification_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceAsyncClient.update_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.UpdateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "UpdateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateOmnichannelSettingRequest" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1.types.OmnichannelSetting" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.OmnichannelSetting", + "shortName": "update_omnichannel_setting" + }, + "description": "Sample for UpdateOmnichannelSetting", + "file": "merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_omnichannel_settings_service_update_omnichannel_setting_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OmnichannelSettingsServiceClient.update_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService.UpdateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "UpdateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateOmnichannelSettingRequest" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1.types.OmnichannelSetting" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.OmnichannelSetting", + "shortName": "update_omnichannel_setting" + }, + "description": "Sample for UpdateOmnichannelSetting", + "file": "merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_omnichannel_settings_service_update_omnichannel_setting_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient.create_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.CreateOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "CreateOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateOnlineReturnPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "online_return_policy", + "type": "google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy" + }, + { + "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_accounts_v1.types.OnlineReturnPolicy", + "shortName": "create_online_return_policy" + }, + "description": "Sample for CreateOnlineReturnPolicy", + "file": "merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient.create_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.CreateOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "CreateOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateOnlineReturnPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "online_return_policy", + "type": "google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy" + }, + { + "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_accounts_v1.types.OnlineReturnPolicy", + "shortName": "create_online_return_policy" + }, + "description": "Sample for CreateOnlineReturnPolicy", + "file": "merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient.delete_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.DeleteOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "DeleteOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteOnlineReturnPolicyRequest" + }, + { + "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_online_return_policy" + }, + "description": "Sample for DeleteOnlineReturnPolicy", + "file": "merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_online_return_policy_service_delete_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient.delete_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.DeleteOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "DeleteOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteOnlineReturnPolicyRequest" + }, + { + "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_online_return_policy" + }, + "description": "Sample for DeleteOnlineReturnPolicy", + "file": "merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_online_return_policy_service_delete_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient.get_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.GetOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "GetOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetOnlineReturnPolicyRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy", + "shortName": "get_online_return_policy" + }, + "description": "Sample for GetOnlineReturnPolicy", + "file": "merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient.get_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.GetOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "GetOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetOnlineReturnPolicyRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.OnlineReturnPolicy", + "shortName": "get_online_return_policy" + }, + "description": "Sample for GetOnlineReturnPolicy", + "file": "merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceAsyncClient.list_online_return_policies", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.ListOnlineReturnPolicies", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "ListOnlineReturnPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesRequest" + }, + { + "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_accounts_v1.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager", + "shortName": "list_online_return_policies" + }, + "description": "Sample for ListOnlineReturnPolicies", + "file": "merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_online_return_policy_service_list_online_return_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.OnlineReturnPolicyServiceClient.list_online_return_policies", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService.ListOnlineReturnPolicies", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "ListOnlineReturnPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListOnlineReturnPoliciesRequest" + }, + { + "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_accounts_v1.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager", + "shortName": "list_online_return_policies" + }, + "description": "Sample for ListOnlineReturnPolicies", + "file": "merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_online_return_policy_service_list_online_return_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient.disable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.DisableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "DisableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DisableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Program", + "shortName": "disable_program" + }, + "description": "Sample for DisableProgram", + "file": "merchantapi_v1_generated_programs_service_disable_program_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_DisableProgram_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_programs_service_disable_program_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient.disable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.DisableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "DisableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DisableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Program", + "shortName": "disable_program" + }, + "description": "Sample for DisableProgram", + "file": "merchantapi_v1_generated_programs_service_disable_program_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_DisableProgram_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_programs_service_disable_program_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient.enable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.EnableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "EnableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.EnableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Program", + "shortName": "enable_program" + }, + "description": "Sample for EnableProgram", + "file": "merchantapi_v1_generated_programs_service_enable_program_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_EnableProgram_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_programs_service_enable_program_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient.enable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.EnableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "EnableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.EnableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Program", + "shortName": "enable_program" + }, + "description": "Sample for EnableProgram", + "file": "merchantapi_v1_generated_programs_service_enable_program_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_EnableProgram_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_programs_service_enable_program_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient.get_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.GetProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "GetProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Program", + "shortName": "get_program" + }, + "description": "Sample for GetProgram", + "file": "merchantapi_v1_generated_programs_service_get_program_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_GetProgram_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_programs_service_get_program_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient.get_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.GetProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "GetProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Program", + "shortName": "get_program" + }, + "description": "Sample for GetProgram", + "file": "merchantapi_v1_generated_programs_service_get_program_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_GetProgram_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_programs_service_get_program_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceAsyncClient.list_programs", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.ListPrograms", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "ListPrograms" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListProgramsRequest" + }, + { + "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_accounts_v1.services.programs_service.pagers.ListProgramsAsyncPager", + "shortName": "list_programs" + }, + "description": "Sample for ListPrograms", + "file": "merchantapi_v1_generated_programs_service_list_programs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_ListPrograms_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_programs_service_list_programs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ProgramsServiceClient.list_programs", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService.ListPrograms", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "ListPrograms" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListProgramsRequest" + }, + { + "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_accounts_v1.services.programs_service.pagers.ListProgramsPager", + "shortName": "list_programs" + }, + "description": "Sample for ListPrograms", + "file": "merchantapi_v1_generated_programs_service_list_programs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ProgramsService_ListPrograms_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_programs_service_list_programs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient.create_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.CreateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "CreateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateRegionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1.types.Region" + }, + { + "name": "region_id", + "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_accounts_v1.types.Region", + "shortName": "create_region" + }, + "description": "Sample for CreateRegion", + "file": "merchantapi_v1_generated_regions_service_create_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_CreateRegion_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regions_service_create_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient.create_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.CreateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "CreateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateRegionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1.types.Region" + }, + { + "name": "region_id", + "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_accounts_v1.types.Region", + "shortName": "create_region" + }, + "description": "Sample for CreateRegion", + "file": "merchantapi_v1_generated_regions_service_create_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_CreateRegion_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regions_service_create_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient.delete_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.DeleteRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "DeleteRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteRegionRequest" + }, + { + "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_region" + }, + "description": "Sample for DeleteRegion", + "file": "merchantapi_v1_generated_regions_service_delete_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_DeleteRegion_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_regions_service_delete_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient.delete_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.DeleteRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "DeleteRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteRegionRequest" + }, + { + "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_region" + }, + "description": "Sample for DeleteRegion", + "file": "merchantapi_v1_generated_regions_service_delete_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_DeleteRegion_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_regions_service_delete_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient.get_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.GetRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "GetRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetRegionRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Region", + "shortName": "get_region" + }, + "description": "Sample for GetRegion", + "file": "merchantapi_v1_generated_regions_service_get_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_GetRegion_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regions_service_get_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient.get_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.GetRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "GetRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetRegionRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.Region", + "shortName": "get_region" + }, + "description": "Sample for GetRegion", + "file": "merchantapi_v1_generated_regions_service_get_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_GetRegion_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regions_service_get_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient.list_regions", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.ListRegions", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "ListRegions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListRegionsRequest" + }, + { + "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_accounts_v1.services.regions_service.pagers.ListRegionsAsyncPager", + "shortName": "list_regions" + }, + "description": "Sample for ListRegions", + "file": "merchantapi_v1_generated_regions_service_list_regions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_ListRegions_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_regions_service_list_regions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient.list_regions", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.ListRegions", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "ListRegions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListRegionsRequest" + }, + { + "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_accounts_v1.services.regions_service.pagers.ListRegionsPager", + "shortName": "list_regions" + }, + "description": "Sample for ListRegions", + "file": "merchantapi_v1_generated_regions_service_list_regions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_ListRegions_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_regions_service_list_regions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceAsyncClient.update_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.UpdateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "UpdateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateRegionRequest" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1.types.Region" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.Region", + "shortName": "update_region" + }, + "description": "Sample for UpdateRegion", + "file": "merchantapi_v1_generated_regions_service_update_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_UpdateRegion_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regions_service_update_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.RegionsServiceClient.update_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService.UpdateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "UpdateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateRegionRequest" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1.types.Region" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.Region", + "shortName": "update_region" + }, + "description": "Sample for UpdateRegion", + "file": "merchantapi_v1_generated_regions_service_update_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_RegionsService_UpdateRegion_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_regions_service_update_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceAsyncClient", + "shortName": "ShippingSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceAsyncClient.get_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService.GetShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "GetShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetShippingSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.ShippingSettings", + "shortName": "get_shipping_settings" + }, + "description": "Sample for GetShippingSettings", + "file": "merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ShippingSettingsService_GetShippingSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceClient", + "shortName": "ShippingSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceClient.get_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService.GetShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "GetShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetShippingSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.ShippingSettings", + "shortName": "get_shipping_settings" + }, + "description": "Sample for GetShippingSettings", + "file": "merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ShippingSettingsService_GetShippingSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceAsyncClient", + "shortName": "ShippingSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceAsyncClient.insert_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService.InsertShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "InsertShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.InsertShippingSettingsRequest" + }, + { + "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_accounts_v1.types.ShippingSettings", + "shortName": "insert_shipping_settings" + }, + "description": "Sample for InsertShippingSettings", + "file": "merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ShippingSettingsService_InsertShippingSettings_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_shipping_settings_service_insert_shipping_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceClient", + "shortName": "ShippingSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.ShippingSettingsServiceClient.insert_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService.InsertShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "InsertShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.InsertShippingSettingsRequest" + }, + { + "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_accounts_v1.types.ShippingSettings", + "shortName": "insert_shipping_settings" + }, + "description": "Sample for InsertShippingSettings", + "file": "merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_ShippingSettingsService_InsertShippingSettings_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_shipping_settings_service_insert_shipping_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient", + "shortName": "TermsOfServiceAgreementStateServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient.get_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService.GetTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "GetTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetTermsOfServiceAgreementStateRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.TermsOfServiceAgreementState", + "shortName": "get_terms_of_service_agreement_state" + }, + "description": "Sample for GetTermsOfServiceAgreementState", + "file": "merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient", + "shortName": "TermsOfServiceAgreementStateServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService.GetTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "GetTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetTermsOfServiceAgreementStateRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.TermsOfServiceAgreementState", + "shortName": "get_terms_of_service_agreement_state" + }, + "description": "Sample for GetTermsOfServiceAgreementState", + "file": "merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient", + "shortName": "TermsOfServiceAgreementStateServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient.retrieve_for_application_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService.RetrieveForApplicationTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "RetrieveForApplicationTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest" + }, + { + "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_accounts_v1.types.TermsOfServiceAgreementState", + "shortName": "retrieve_for_application_terms_of_service_agreement_state" + }, + "description": "Sample for RetrieveForApplicationTermsOfServiceAgreementState", + "file": "merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient", + "shortName": "TermsOfServiceAgreementStateServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService.RetrieveForApplicationTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "RetrieveForApplicationTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest" + }, + { + "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_accounts_v1.types.TermsOfServiceAgreementState", + "shortName": "retrieve_for_application_terms_of_service_agreement_state" + }, + "description": "Sample for RetrieveForApplicationTermsOfServiceAgreementState", + "file": "merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceAsyncClient", + "shortName": "TermsOfServiceServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceAsyncClient.accept_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService.AcceptTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "AcceptTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceResponse", + "shortName": "accept_terms_of_service" + }, + "description": "Sample for AcceptTermsOfService", + "file": "merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceService_AcceptTermsOfService_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceClient", + "shortName": "TermsOfServiceServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceClient.accept_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService.AcceptTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "AcceptTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.AcceptTermsOfServiceResponse", + "shortName": "accept_terms_of_service" + }, + "description": "Sample for AcceptTermsOfService", + "file": "merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceService_AcceptTermsOfService_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceAsyncClient", + "shortName": "TermsOfServiceServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceAsyncClient.get_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService.GetTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "GetTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetTermsOfServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.TermsOfService", + "shortName": "get_terms_of_service" + }, + "description": "Sample for GetTermsOfService", + "file": "merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceService_GetTermsOfService_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceClient", + "shortName": "TermsOfServiceServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceClient.get_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService.GetTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "GetTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetTermsOfServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.TermsOfService", + "shortName": "get_terms_of_service" + }, + "description": "Sample for GetTermsOfService", + "file": "merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceService_GetTermsOfService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceAsyncClient", + "shortName": "TermsOfServiceServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceAsyncClient.retrieve_latest_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService.RetrieveLatestTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "RetrieveLatestTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RetrieveLatestTermsOfServiceRequest" + }, + { + "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_accounts_v1.types.TermsOfService", + "shortName": "retrieve_latest_terms_of_service" + }, + "description": "Sample for RetrieveLatestTermsOfService", + "file": "merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceService_RetrieveLatestTermsOfService_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceClient", + "shortName": "TermsOfServiceServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService.RetrieveLatestTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "RetrieveLatestTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.RetrieveLatestTermsOfServiceRequest" + }, + { + "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_accounts_v1.types.TermsOfService", + "shortName": "retrieve_latest_terms_of_service" + }, + "description": "Sample for RetrieveLatestTermsOfService", + "file": "merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_TermsOfServiceService_RetrieveLatestTermsOfService_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient.create_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.CreateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1.types.User" + }, + { + "name": "user_id", + "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_accounts_v1.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "merchantapi_v1_generated_user_service_create_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_CreateUser_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_user_service_create_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient.create_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.CreateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1.types.User" + }, + { + "name": "user_id", + "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_accounts_v1.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "merchantapi_v1_generated_user_service_create_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_CreateUser_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_user_service_create_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient.delete_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.DeleteUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteUserRequest" + }, + { + "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_user" + }, + "description": "Sample for DeleteUser", + "file": "merchantapi_v1_generated_user_service_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_DeleteUser_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_user_service_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient.delete_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.DeleteUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.DeleteUserRequest" + }, + { + "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_user" + }, + "description": "Sample for DeleteUser", + "file": "merchantapi_v1_generated_user_service_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_DeleteUser_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_user_service_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient.get_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.GetUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetUserRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "merchantapi_v1_generated_user_service_get_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_GetUser_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_user_service_get_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient.get_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.GetUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.GetUserRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "merchantapi_v1_generated_user_service_get_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_GetUser_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_user_service_get_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient.list_users", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.ListUsers", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListUsersRequest" + }, + { + "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_accounts_v1.services.user_service.pagers.ListUsersAsyncPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "merchantapi_v1_generated_user_service_list_users_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_ListUsers_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_user_service_list_users_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient.list_users", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.ListUsers", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.ListUsersRequest" + }, + { + "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_accounts_v1.services.user_service.pagers.ListUsersPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "merchantapi_v1_generated_user_service_list_users_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_ListUsers_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_user_service_list_users_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceAsyncClient.update_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.UpdateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "merchantapi_v1_generated_user_service_update_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_UpdateUser_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_user_service_update_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1.UserServiceClient.update_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1.UserService.UpdateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1.UserService", + "shortName": "UserService" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "merchantapi_v1_generated_user_service_update_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1_generated_UserService_UpdateUser_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1_generated_user_service_update_user_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/scripts/fixup_merchant_accounts_v1_keywords.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/scripts/fixup_merchant_accounts_v1_keywords.py new file mode 100644 index 000000000000..7e1d4ed36609 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/scripts/fixup_merchant_accounts_v1_keywords.py @@ -0,0 +1,245 @@ +#! /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_accountsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'accept_terms_of_service': ('name', 'account', 'region_code', ), + 'approve_account_service': ('name', ), + 'claim_homepage': ('name', 'overwrite', ), + 'create_and_configure_account': ('account', 'service', 'user', ), + 'create_checkout_settings': ('parent', 'checkout_settings', ), + 'create_omnichannel_setting': ('parent', 'omnichannel_setting', ), + 'create_online_return_policy': ('parent', 'online_return_policy', ), + 'create_region': ('parent', 'region_id', 'region', ), + 'create_user': ('parent', 'user_id', 'user', ), + 'delete_account': ('name', 'force', ), + 'delete_checkout_settings': ('name', ), + 'delete_online_return_policy': ('name', ), + 'delete_region': ('name', ), + 'delete_user': ('name', ), + 'disable_program': ('name', ), + 'enable_program': ('name', ), + 'find_lfp_providers': ('parent', 'page_size', 'page_token', ), + 'get_account': ('name', ), + 'get_account_relationship': ('name', ), + 'get_account_service': ('name', ), + 'get_autofeed_settings': ('name', ), + 'get_automatic_improvements': ('name', ), + 'get_business_identity': ('name', ), + 'get_business_info': ('name', ), + 'get_checkout_settings': ('name', ), + 'get_developer_registration': ('name', ), + 'get_email_preferences': ('name', ), + 'get_homepage': ('name', ), + 'get_omnichannel_setting': ('name', ), + 'get_online_return_policy': ('name', ), + 'get_program': ('name', ), + 'get_region': ('name', ), + 'get_shipping_settings': ('name', ), + 'get_terms_of_service': ('name', ), + 'get_terms_of_service_agreement_state': ('name', ), + 'get_user': ('name', ), + 'insert_shipping_settings': ('parent', 'shipping_setting', ), + 'link_gbp_account': ('parent', 'gbp_email', ), + 'link_lfp_provider': ('name', 'external_account_id', ), + 'list_account_issues': ('parent', 'page_size', 'page_token', 'language_code', 'time_zone', ), + 'list_account_relationships': ('parent', 'page_token', 'page_size', ), + 'list_accounts': ('page_size', 'page_token', 'filter', ), + 'list_account_services': ('parent', 'page_token', 'page_size', ), + 'list_gbp_accounts': ('parent', 'page_size', 'page_token', ), + 'list_omnichannel_settings': ('parent', 'page_size', 'page_token', ), + 'list_online_return_policies': ('parent', 'page_size', 'page_token', ), + 'list_programs': ('parent', 'page_size', 'page_token', ), + 'list_regions': ('parent', 'page_size', 'page_token', ), + 'list_sub_accounts': ('provider', 'page_size', 'page_token', ), + 'list_users': ('parent', 'page_size', 'page_token', ), + 'propose_account_service': ('parent', 'provider', 'account_service', ), + 'register_gcp': ('name', 'developer_email', ), + 'reject_account_service': ('name', ), + 'request_inventory_verification': ('name', ), + 'retrieve_for_application_terms_of_service_agreement_state': ('parent', ), + 'retrieve_latest_terms_of_service': ('region_code', 'kind', ), + 'unclaim_homepage': ('name', ), + 'unregister_gcp': ('name', ), + 'update_account': ('account', 'update_mask', ), + 'update_account_relationship': ('account_relationship', 'update_mask', ), + 'update_autofeed_settings': ('autofeed_settings', 'update_mask', ), + 'update_automatic_improvements': ('automatic_improvements', 'update_mask', ), + 'update_business_identity': ('business_identity', 'update_mask', ), + 'update_business_info': ('business_info', 'update_mask', ), + 'update_checkout_settings': ('checkout_settings', 'update_mask', ), + 'update_email_preferences': ('email_preferences', 'update_mask', ), + 'update_homepage': ('homepage', 'update_mask', ), + 'update_omnichannel_setting': ('omnichannel_setting', 'update_mask', ), + 'update_region': ('region', 'update_mask', ), + 'update_user': ('user', 'update_mask', ), + } + + 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_accountsCallTransformer(), +): + """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_accounts 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-accounts/v1/setup.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/setup.py new file mode 100644 index 000000000000..9c31c0f0922e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts' + + +description = "Google Shopping Merchant Accounts API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_accounts/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-accounts" + +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-accounts/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..0112695e5bbb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2af887ec8ba0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py new file mode 100644 index 000000000000..37a6168e8021 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py @@ -0,0 +1,2418 @@ +# -*- 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.shopping.merchant_accounts_v1.services.account_issue_service import AccountIssueServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.account_issue_service import AccountIssueServiceClient +from google.shopping.merchant_accounts_v1.services.account_issue_service import pagers +from google.shopping.merchant_accounts_v1.services.account_issue_service import transports +from google.shopping.merchant_accounts_v1.types import accountissue +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 AccountIssueServiceClient._get_default_mtls_endpoint(None) is None + assert AccountIssueServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountIssueServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountIssueServiceClient._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 AccountIssueServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountIssueServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountIssueServiceClient._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 AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, False) is None + assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountIssueServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountIssueServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountIssueServiceClient._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 AccountIssueServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountIssueServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountIssueServiceClient._get_universe_domain(None, None) == AccountIssueServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountIssueServiceClient._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 = AccountIssueServiceClient(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 = AccountIssueServiceClient(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", [ + (AccountIssueServiceClient, "grpc"), + (AccountIssueServiceAsyncClient, "grpc_asyncio"), + (AccountIssueServiceClient, "rest"), +]) +def test_account_issue_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.AccountIssueServiceGrpcTransport, "grpc"), + (transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountIssueServiceRestTransport, "rest"), +]) +def test_account_issue_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", [ + (AccountIssueServiceClient, "grpc"), + (AccountIssueServiceAsyncClient, "grpc_asyncio"), + (AccountIssueServiceClient, "rest"), +]) +def test_account_issue_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_account_issue_service_client_get_transport_class(): + transport = AccountIssueServiceClient.get_transport_class() + available_transports = [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountIssueServiceClient.get_transport_class("grpc") + assert transport == transports.AccountIssueServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +def test_account_issue_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(AccountIssueServiceClient, '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(AccountIssueServiceClient, '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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "true"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "false"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "true"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_account_issue_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", [ + AccountIssueServiceClient, AccountIssueServiceAsyncClient +]) +@mock.patch.object(AccountIssueServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceAsyncClient)) +def test_account_issue_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", [ + AccountIssueServiceClient, AccountIssueServiceAsyncClient +]) +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +def test_account_issue_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountIssueServiceClient._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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), +]) +def test_account_issue_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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", None), +]) +def test_account_issue_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_account_issue_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountIssueServiceClient( + 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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_account_issue_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", [ + accountissue.ListAccountIssuesRequest, + dict, +]) +def test_list_account_issues(request_type, transport: str = 'grpc'): + client = AccountIssueServiceClient( + 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_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountissue.ListAccountIssuesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountissue.ListAccountIssuesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountIssuesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_issues_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 = AccountIssueServiceClient( + 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 = accountissue.ListAccountIssuesRequest( + parent='parent_value', + page_token='page_token_value', + language_code='language_code_value', + time_zone='time_zone_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_issues(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountissue.ListAccountIssuesRequest( + parent='parent_value', + page_token='page_token_value', + language_code='language_code_value', + time_zone='time_zone_value', + ) + +def test_list_account_issues_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 = AccountIssueServiceClient( + 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_account_issues in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_issues] = mock_rpc + request = {} + client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_issues(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_account_issues_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 = AccountIssueServiceAsyncClient( + 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_account_issues 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_account_issues] = mock_rpc + + request = {} + await client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_account_issues(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_account_issues_async(transport: str = 'grpc_asyncio', request_type=accountissue.ListAccountIssuesRequest): + client = AccountIssueServiceAsyncClient( + 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_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountissue.ListAccountIssuesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountIssuesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_issues_async_from_dict(): + await test_list_account_issues_async(request_type=dict) + +def test_list_account_issues_field_headers(): + client = AccountIssueServiceClient( + 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 = accountissue.ListAccountIssuesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value = accountissue.ListAccountIssuesResponse() + client.list_account_issues(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_account_issues_field_headers_async(): + client = AccountIssueServiceAsyncClient( + 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 = accountissue.ListAccountIssuesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) + await client.list_account_issues(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_account_issues_flattened(): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountissue.ListAccountIssuesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_account_issues( + 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_account_issues_flattened_error(): + client = AccountIssueServiceClient( + 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_account_issues( + accountissue.ListAccountIssuesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_account_issues_flattened_async(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountissue.ListAccountIssuesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_account_issues( + 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_account_issues_flattened_error_async(): + client = AccountIssueServiceAsyncClient( + 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_account_issues( + accountissue.ListAccountIssuesRequest(), + parent='parent_value', + ) + + +def test_list_account_issues_pager(transport_name: str = "grpc"): + client = AccountIssueServiceClient( + 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_account_issues), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_account_issues(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, accountissue.AccountIssue) + for i in results) +def test_list_account_issues_pages(transport_name: str = "grpc"): + client = AccountIssueServiceClient( + 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_account_issues), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_issues(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_account_issues_async_pager(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_issues(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, accountissue.AccountIssue) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_issues_async_pages(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + 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_account_issues(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_account_issues_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 = AccountIssueServiceClient( + 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_account_issues in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_issues] = mock_rpc + + request = {} + client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_issues(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_account_issues_rest_required_fields(request_type=accountissue.ListAccountIssuesRequest): + transport_class = transports.AccountIssueServiceRestTransport + + 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_account_issues._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_account_issues._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("language_code", "page_size", "page_token", "time_zone", )) + 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 = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountissue.ListAccountIssuesResponse() + # 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 = accountissue.ListAccountIssuesResponse.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_account_issues(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_account_issues_rest_unset_required_fields(): + transport = transports.AccountIssueServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_account_issues._get_unset_required_fields({}) + assert set(unset_fields) == (set(("languageCode", "pageSize", "pageToken", "timeZone", )) & set(("parent", ))) + + +def test_list_account_issues_rest_flattened(): + client = AccountIssueServiceClient( + 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 = accountissue.ListAccountIssuesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = accountissue.ListAccountIssuesResponse.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_account_issues(**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/accounts/v1/{parent=accounts/*}/issues" % client.transport._host, args[1]) + + +def test_list_account_issues_rest_flattened_error(transport: str = 'rest'): + client = AccountIssueServiceClient( + 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_account_issues( + accountissue.ListAccountIssuesRequest(), + parent='parent_value', + ) + + +def test_list_account_issues_rest_pager(transport: str = 'rest'): + client = AccountIssueServiceClient( + 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 = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accountissue.ListAccountIssuesResponse.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'} + + pager = client.list_account_issues(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accountissue.AccountIssue) + for i in results) + + pages = list(client.list_account_issues(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + 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 = AccountIssueServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountIssueServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountIssueServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + transports.AccountIssueServiceRestTransport, +]) +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 = AccountIssueServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountIssueServiceClient( + 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_account_issues_empty_call_grpc(): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value = accountissue.ListAccountIssuesResponse() + client.list_account_issues(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountissue.ListAccountIssuesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountIssueServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountIssueServiceAsyncClient( + 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_account_issues_empty_call_grpc_asyncio(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( + next_page_token='next_page_token_value', + )) + await client.list_account_issues(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountissue.ListAccountIssuesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountIssueServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_account_issues_rest_bad_request(request_type=accountissue.ListAccountIssuesRequest): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_account_issues(request) + + +@pytest.mark.parametrize("request_type", [ + accountissue.ListAccountIssuesRequest, + dict, +]) +def test_list_account_issues_rest_call_success(request_type): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accountissue.ListAccountIssuesResponse( + 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 = accountissue.ListAccountIssuesResponse.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_account_issues(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountIssuesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_issues_rest_interceptors(null_interceptor): + transport = transports.AccountIssueServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountIssueServiceRestInterceptor(), + ) + client = AccountIssueServiceClient(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.AccountIssueServiceRestInterceptor, "post_list_account_issues") as post, \ + mock.patch.object(transports.AccountIssueServiceRestInterceptor, "post_list_account_issues_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountIssueServiceRestInterceptor, "pre_list_account_issues") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountissue.ListAccountIssuesRequest.pb(accountissue.ListAccountIssuesRequest()) + 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 = accountissue.ListAccountIssuesResponse.to_json(accountissue.ListAccountIssuesResponse()) + req.return_value.content = return_value + + request = accountissue.ListAccountIssuesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountissue.ListAccountIssuesResponse() + post_with_metadata.return_value = accountissue.ListAccountIssuesResponse(), metadata + + client.list_account_issues(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountIssueServiceClient( + 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_account_issues_empty_call_rest(): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + client.list_account_issues(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountissue.ListAccountIssuesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountIssueServiceGrpcTransport, + ) + +def test_account_issue_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountIssueServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_account_issue_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountIssueServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_account_issues', + ) + 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_account_issue_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_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountIssueServiceTransport( + 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_account_issue_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_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountIssueServiceTransport() + adc.assert_called_once() + + +def test_account_issue_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) + AccountIssueServiceClient() + 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.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + ], +) +def test_account_issue_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.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + transports.AccountIssueServiceRestTransport, + ], +) +def test_account_issue_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.AccountIssueServiceGrpcTransport, grpc_helpers), + (transports.AccountIssueServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +def test_account_issue_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_account_issue_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.AccountIssueServiceRestTransport ( + 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_account_issue_service_host_no_port(transport_name): + client = AccountIssueServiceClient( + 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_account_issue_service_host_with_port(transport_name): + client = AccountIssueServiceClient( + 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_account_issue_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountIssueServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountIssueServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_account_issues._session + session2 = client2.transport.list_account_issues._session + assert session1 != session2 +def test_account_issue_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountIssueServiceGrpcTransport( + 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_account_issue_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountIssueServiceGrpcAsyncIOTransport( + 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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +def test_account_issue_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AccountIssueServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AccountIssueServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_account_path(path) + assert expected == actual + +def test_account_issue_path(): + account = "whelk" + issue = "octopus" + expected = "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) + actual = AccountIssueServiceClient.account_issue_path(account, issue) + assert expected == actual + + +def test_parse_account_issue_path(): + expected = { + "account": "oyster", + "issue": "nudibranch", + } + path = AccountIssueServiceClient.account_issue_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_account_issue_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountIssueServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AccountIssueServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountIssueServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AccountIssueServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountIssueServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AccountIssueServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AccountIssueServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AccountIssueServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AccountIssueServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.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.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountIssueServiceClient.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 = AccountIssueServiceClient( + 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 = AccountIssueServiceAsyncClient( + 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 = AccountIssueServiceClient( + 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 = AccountIssueServiceClient( + 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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py new file mode 100644 index 000000000000..2aa76d82571e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py @@ -0,0 +1,3845 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.account_relationships_service import AccountRelationshipsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.account_relationships_service import AccountRelationshipsServiceClient +from google.shopping.merchant_accounts_v1.services.account_relationships_service import pagers +from google.shopping.merchant_accounts_v1.services.account_relationships_service import transports +from google.shopping.merchant_accounts_v1.types import accountrelationships +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 AccountRelationshipsServiceClient._get_default_mtls_endpoint(None) is None + assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountRelationshipsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._get_client_cert_source(None, False) is None + assert AccountRelationshipsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountRelationshipsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) +@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountRelationshipsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountRelationshipsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountRelationshipsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountRelationshipsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountRelationshipsServiceClient._get_universe_domain(None, None) == AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountRelationshipsServiceClient._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 = AccountRelationshipsServiceClient(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 = AccountRelationshipsServiceClient(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", [ + (AccountRelationshipsServiceClient, "grpc"), + (AccountRelationshipsServiceAsyncClient, "grpc_asyncio"), + (AccountRelationshipsServiceClient, "rest"), +]) +def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, "grpc"), + (transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountRelationshipsServiceRestTransport, "rest"), +]) +def test_account_relationships_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", [ + (AccountRelationshipsServiceClient, "grpc"), + (AccountRelationshipsServiceAsyncClient, "grpc_asyncio"), + (AccountRelationshipsServiceClient, "rest"), +]) +def test_account_relationships_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_account_relationships_service_client_get_transport_class(): + transport = AccountRelationshipsServiceClient.get_transport_class() + available_transports = [ + transports.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountRelationshipsServiceClient.get_transport_class("grpc") + assert transport == transports.AccountRelationshipsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc"), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) +@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) +def test_account_relationships_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(AccountRelationshipsServiceClient, '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(AccountRelationshipsServiceClient, '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", [ + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", "true"), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", "false"), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest", "true"), + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) +@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_account_relationships_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", [ + AccountRelationshipsServiceClient, AccountRelationshipsServiceAsyncClient +]) +@mock.patch.object(AccountRelationshipsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountRelationshipsServiceClient)) +@mock.patch.object(AccountRelationshipsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountRelationshipsServiceAsyncClient)) +def test_account_relationships_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", [ + AccountRelationshipsServiceClient, AccountRelationshipsServiceAsyncClient +]) +@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) +@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) +def test_account_relationships_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountRelationshipsServiceClient._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", [ + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc"), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest"), +]) +def test_account_relationships_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", [ + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", grpc_helpers), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest", None), +]) +def test_account_relationships_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_account_relationships_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountRelationshipsServiceClient( + 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", [ + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", grpc_helpers), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_account_relationships_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", [ + accountrelationships.GetAccountRelationshipRequest, + dict, +]) +def test_get_account_relationship(request_type, transport: str = 'grpc'): + client = AccountRelationshipsServiceClient( + 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.get_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_value', + ) + response = client.get_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountrelationships.GetAccountRelationshipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountrelationships.AccountRelationship) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.account_id_alias == 'account_id_alias_value' + + +def test_get_account_relationship_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 = AccountRelationshipsServiceClient( + 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 = accountrelationships.GetAccountRelationshipRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account_relationship(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountrelationships.GetAccountRelationshipRequest( + name='name_value', + ) + +def test_get_account_relationship_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 = AccountRelationshipsServiceClient( + 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.get_account_relationship in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account_relationship] = mock_rpc + request = {} + client.get_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_relationship(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_get_account_relationship_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 = AccountRelationshipsServiceAsyncClient( + 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.get_account_relationship in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_account_relationship] = mock_rpc + + request = {} + await client.get_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_account_relationship(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_get_account_relationship_async(transport: str = 'grpc_asyncio', request_type=accountrelationships.GetAccountRelationshipRequest): + client = AccountRelationshipsServiceAsyncClient( + 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.get_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_value', + )) + response = await client.get_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountrelationships.GetAccountRelationshipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountrelationships.AccountRelationship) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.account_id_alias == 'account_id_alias_value' + + +@pytest.mark.asyncio +async def test_get_account_relationship_async_from_dict(): + await test_get_account_relationship_async(request_type=dict) + +def test_get_account_relationship_field_headers(): + client = AccountRelationshipsServiceClient( + 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 = accountrelationships.GetAccountRelationshipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + call.return_value = accountrelationships.AccountRelationship() + client.get_account_relationship(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_get_account_relationship_field_headers_async(): + client = AccountRelationshipsServiceAsyncClient( + 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 = accountrelationships.GetAccountRelationshipRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + await client.get_account_relationship(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_get_account_relationship_flattened(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.AccountRelationship() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account_relationship( + 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_get_account_relationship_flattened_error(): + client = AccountRelationshipsServiceClient( + 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.get_account_relationship( + accountrelationships.GetAccountRelationshipRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_relationship_flattened_async(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.AccountRelationship() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account_relationship( + 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_get_account_relationship_flattened_error_async(): + client = AccountRelationshipsServiceAsyncClient( + 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.get_account_relationship( + accountrelationships.GetAccountRelationshipRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accountrelationships.UpdateAccountRelationshipRequest, + dict, +]) +def test_update_account_relationship(request_type, transport: str = 'grpc'): + client = AccountRelationshipsServiceClient( + 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.update_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_value', + ) + response = client.update_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountrelationships.UpdateAccountRelationshipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountrelationships.AccountRelationship) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.account_id_alias == 'account_id_alias_value' + + +def test_update_account_relationship_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 = AccountRelationshipsServiceClient( + 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 = accountrelationships.UpdateAccountRelationshipRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account_relationship(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountrelationships.UpdateAccountRelationshipRequest( + ) + +def test_update_account_relationship_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 = AccountRelationshipsServiceClient( + 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.update_account_relationship in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account_relationship] = mock_rpc + request = {} + client.update_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account_relationship(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_update_account_relationship_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 = AccountRelationshipsServiceAsyncClient( + 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.update_account_relationship in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_account_relationship] = mock_rpc + + request = {} + await client.update_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_account_relationship(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_update_account_relationship_async(transport: str = 'grpc_asyncio', request_type=accountrelationships.UpdateAccountRelationshipRequest): + client = AccountRelationshipsServiceAsyncClient( + 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.update_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_value', + )) + response = await client.update_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountrelationships.UpdateAccountRelationshipRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountrelationships.AccountRelationship) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.account_id_alias == 'account_id_alias_value' + + +@pytest.mark.asyncio +async def test_update_account_relationship_async_from_dict(): + await test_update_account_relationship_async(request_type=dict) + +def test_update_account_relationship_field_headers(): + client = AccountRelationshipsServiceClient( + 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 = accountrelationships.UpdateAccountRelationshipRequest() + + request.account_relationship.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + call.return_value = accountrelationships.AccountRelationship() + client.update_account_relationship(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', + 'account_relationship.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_account_relationship_field_headers_async(): + client = AccountRelationshipsServiceAsyncClient( + 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 = accountrelationships.UpdateAccountRelationshipRequest() + + request.account_relationship.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + await client.update_account_relationship(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', + 'account_relationship.name=name_value', + ) in kw['metadata'] + + +def test_update_account_relationship_flattened(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.AccountRelationship() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_account_relationship( + account_relationship=accountrelationships.AccountRelationship(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account_relationship + mock_val = accountrelationships.AccountRelationship(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_account_relationship_flattened_error(): + client = AccountRelationshipsServiceClient( + 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.update_account_relationship( + accountrelationships.UpdateAccountRelationshipRequest(), + account_relationship=accountrelationships.AccountRelationship(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_account_relationship_flattened_async(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.AccountRelationship() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account_relationship( + account_relationship=accountrelationships.AccountRelationship(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account_relationship + mock_val = accountrelationships.AccountRelationship(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_account_relationship_flattened_error_async(): + client = AccountRelationshipsServiceAsyncClient( + 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.update_account_relationship( + accountrelationships.UpdateAccountRelationshipRequest(), + account_relationship=accountrelationships.AccountRelationship(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + accountrelationships.ListAccountRelationshipsRequest, + dict, +]) +def test_list_account_relationships(request_type, transport: str = 'grpc'): + client = AccountRelationshipsServiceClient( + 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_account_relationships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.ListAccountRelationshipsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_relationships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountrelationships.ListAccountRelationshipsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountRelationshipsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_relationships_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 = AccountRelationshipsServiceClient( + 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 = accountrelationships.ListAccountRelationshipsRequest( + 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_account_relationships), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_relationships(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountrelationships.ListAccountRelationshipsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_account_relationships_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 = AccountRelationshipsServiceClient( + 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_account_relationships in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_relationships] = mock_rpc + request = {} + client.list_account_relationships(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_relationships(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_account_relationships_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 = AccountRelationshipsServiceAsyncClient( + 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_account_relationships 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_account_relationships] = mock_rpc + + request = {} + await client.list_account_relationships(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_account_relationships(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_account_relationships_async(transport: str = 'grpc_asyncio', request_type=accountrelationships.ListAccountRelationshipsRequest): + client = AccountRelationshipsServiceAsyncClient( + 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_account_relationships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_relationships(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountrelationships.ListAccountRelationshipsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountRelationshipsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_relationships_async_from_dict(): + await test_list_account_relationships_async(request_type=dict) + +def test_list_account_relationships_field_headers(): + client = AccountRelationshipsServiceClient( + 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 = accountrelationships.ListAccountRelationshipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + call.return_value = accountrelationships.ListAccountRelationshipsResponse() + client.list_account_relationships(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_account_relationships_field_headers_async(): + client = AccountRelationshipsServiceAsyncClient( + 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 = accountrelationships.ListAccountRelationshipsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse()) + await client.list_account_relationships(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_account_relationships_flattened(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.ListAccountRelationshipsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_account_relationships( + 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_account_relationships_flattened_error(): + client = AccountRelationshipsServiceClient( + 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_account_relationships( + accountrelationships.ListAccountRelationshipsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_account_relationships_flattened_async(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountrelationships.ListAccountRelationshipsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_account_relationships( + 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_account_relationships_flattened_error_async(): + client = AccountRelationshipsServiceAsyncClient( + 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_account_relationships( + accountrelationships.ListAccountRelationshipsRequest(), + parent='parent_value', + ) + + +def test_list_account_relationships_pager(transport_name: str = "grpc"): + client = AccountRelationshipsServiceClient( + 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_account_relationships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + next_page_token='abc', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[], + next_page_token='def', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + ], + next_page_token='ghi', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_account_relationships(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, accountrelationships.AccountRelationship) + for i in results) +def test_list_account_relationships_pages(transport_name: str = "grpc"): + client = AccountRelationshipsServiceClient( + 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_account_relationships), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + next_page_token='abc', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[], + next_page_token='def', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + ], + next_page_token='ghi', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_relationships(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_account_relationships_async_pager(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + next_page_token='abc', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[], + next_page_token='def', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + ], + next_page_token='ghi', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_relationships(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, accountrelationships.AccountRelationship) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_relationships_async_pages(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + next_page_token='abc', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[], + next_page_token='def', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + ], + next_page_token='ghi', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + ), + 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_account_relationships(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_account_relationship_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 = AccountRelationshipsServiceClient( + 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.get_account_relationship in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account_relationship] = mock_rpc + + request = {} + client.get_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_relationship(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_get_account_relationship_rest_required_fields(request_type=accountrelationships.GetAccountRelationshipRequest): + transport_class = transports.AccountRelationshipsServiceRestTransport + + 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()).get_account_relationship._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_relationship._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 = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountrelationships.AccountRelationship() + # 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 = accountrelationships.AccountRelationship.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.get_account_relationship(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_relationship_rest_unset_required_fields(): + transport = transports.AccountRelationshipsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account_relationship._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_account_relationship_rest_flattened(): + client = AccountRelationshipsServiceClient( + 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 = accountrelationships.AccountRelationship() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/relationships/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = accountrelationships.AccountRelationship.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.get_account_relationship(**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/accounts/v1/{name=accounts/*/relationships/*}" % client.transport._host, args[1]) + + +def test_get_account_relationship_rest_flattened_error(transport: str = 'rest'): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_account_relationship( + accountrelationships.GetAccountRelationshipRequest(), + name='name_value', + ) + + +def test_update_account_relationship_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 = AccountRelationshipsServiceClient( + 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.update_account_relationship in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account_relationship] = mock_rpc + + request = {} + client.update_account_relationship(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account_relationship(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_update_account_relationship_rest_required_fields(request_type=accountrelationships.UpdateAccountRelationshipRequest): + transport_class = transports.AccountRelationshipsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_relationship._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_relationship._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountrelationships.AccountRelationship() + # 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': "patch", + '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 = accountrelationships.AccountRelationship.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.update_account_relationship(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_account_relationship_rest_unset_required_fields(): + transport = transports.AccountRelationshipsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_account_relationship._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("accountRelationship", ))) + + +def test_update_account_relationship_rest_flattened(): + client = AccountRelationshipsServiceClient( + 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 = accountrelationships.AccountRelationship() + + # get arguments that satisfy an http rule for this method + sample_request = {'account_relationship': {'name': 'accounts/sample1/relationships/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + account_relationship=accountrelationships.AccountRelationship(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = accountrelationships.AccountRelationship.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.update_account_relationship(**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/accounts/v1/{account_relationship.name=accounts/*/relationships/*}" % client.transport._host, args[1]) + + +def test_update_account_relationship_rest_flattened_error(transport: str = 'rest'): + client = AccountRelationshipsServiceClient( + 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.update_account_relationship( + accountrelationships.UpdateAccountRelationshipRequest(), + account_relationship=accountrelationships.AccountRelationship(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_account_relationships_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 = AccountRelationshipsServiceClient( + 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_account_relationships in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_relationships] = mock_rpc + + request = {} + client.list_account_relationships(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_relationships(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_account_relationships_rest_required_fields(request_type=accountrelationships.ListAccountRelationshipsRequest): + transport_class = transports.AccountRelationshipsServiceRestTransport + + 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_account_relationships._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_account_relationships._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 = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountrelationships.ListAccountRelationshipsResponse() + # 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 = accountrelationships.ListAccountRelationshipsResponse.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_account_relationships(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_account_relationships_rest_unset_required_fields(): + transport = transports.AccountRelationshipsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_account_relationships._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_account_relationships_rest_flattened(): + client = AccountRelationshipsServiceClient( + 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 = accountrelationships.ListAccountRelationshipsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = accountrelationships.ListAccountRelationshipsResponse.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_account_relationships(**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/accounts/v1/{parent=accounts/*}/relationships" % client.transport._host, args[1]) + + +def test_list_account_relationships_rest_flattened_error(transport: str = 'rest'): + client = AccountRelationshipsServiceClient( + 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_account_relationships( + accountrelationships.ListAccountRelationshipsRequest(), + parent='parent_value', + ) + + +def test_list_account_relationships_rest_pager(transport: str = 'rest'): + client = AccountRelationshipsServiceClient( + 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 = ( + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + next_page_token='abc', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[], + next_page_token='def', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + ], + next_page_token='ghi', + ), + accountrelationships.ListAccountRelationshipsResponse( + account_relationships=[ + accountrelationships.AccountRelationship(), + accountrelationships.AccountRelationship(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accountrelationships.ListAccountRelationshipsResponse.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'} + + pager = client.list_account_relationships(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accountrelationships.AccountRelationship) + for i in results) + + pages = list(client.list_account_relationships(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountRelationshipsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountRelationshipsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountRelationshipsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountRelationshipsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountRelationshipsServiceClient( + 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 = AccountRelationshipsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountRelationshipsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountRelationshipsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountRelationshipsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountRelationshipsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountRelationshipsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountRelationshipsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + transports.AccountRelationshipsServiceRestTransport, +]) +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 = AccountRelationshipsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountRelationshipsServiceClient( + 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_get_account_relationship_empty_call_grpc(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + call.return_value = accountrelationships.AccountRelationship() + client.get_account_relationship(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.GetAccountRelationshipRequest() + + 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_update_account_relationship_empty_call_grpc(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + call.return_value = accountrelationships.AccountRelationship() + client.update_account_relationship(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.UpdateAccountRelationshipRequest() + + 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_list_account_relationships_empty_call_grpc(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + call.return_value = accountrelationships.ListAccountRelationshipsResponse() + client.list_account_relationships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.ListAccountRelationshipsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountRelationshipsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountRelationshipsServiceAsyncClient( + 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_get_account_relationship_empty_call_grpc_asyncio(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_value', + )) + await client.get_account_relationship(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.GetAccountRelationshipRequest() + + 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_update_account_relationship_empty_call_grpc_asyncio(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_value', + )) + await client.update_account_relationship(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.UpdateAccountRelationshipRequest() + + 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_list_account_relationships_empty_call_grpc_asyncio(): + client = AccountRelationshipsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse( + next_page_token='next_page_token_value', + )) + await client.list_account_relationships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.ListAccountRelationshipsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountRelationshipsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_account_relationship_rest_bad_request(request_type=accountrelationships.GetAccountRelationshipRequest): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/relationships/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.get_account_relationship(request) + + +@pytest.mark.parametrize("request_type", [ + accountrelationships.GetAccountRelationshipRequest, + dict, +]) +def test_get_account_relationship_rest_call_success(request_type): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/relationships/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 = accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_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 = accountrelationships.AccountRelationship.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.get_account_relationship(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accountrelationships.AccountRelationship) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.account_id_alias == 'account_id_alias_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_relationship_rest_interceptors(null_interceptor): + transport = transports.AccountRelationshipsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountRelationshipsServiceRestInterceptor(), + ) + client = AccountRelationshipsServiceClient(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.AccountRelationshipsServiceRestInterceptor, "post_get_account_relationship") as post, \ + mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "post_get_account_relationship_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "pre_get_account_relationship") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountrelationships.GetAccountRelationshipRequest.pb(accountrelationships.GetAccountRelationshipRequest()) + 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 = accountrelationships.AccountRelationship.to_json(accountrelationships.AccountRelationship()) + req.return_value.content = return_value + + request = accountrelationships.GetAccountRelationshipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountrelationships.AccountRelationship() + post_with_metadata.return_value = accountrelationships.AccountRelationship(), metadata + + client.get_account_relationship(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_account_relationship_rest_bad_request(request_type=accountrelationships.UpdateAccountRelationshipRequest): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'account_relationship': {'name': 'accounts/sample1/relationships/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.update_account_relationship(request) + + +@pytest.mark.parametrize("request_type", [ + accountrelationships.UpdateAccountRelationshipRequest, + dict, +]) +def test_update_account_relationship_rest_call_success(request_type): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'account_relationship': {'name': 'accounts/sample1/relationships/sample2'}} + request_init["account_relationship"] = {'name': 'accounts/sample1/relationships/sample2', 'provider': 'provider_value', 'provider_display_name': 'provider_display_name_value', 'account_id_alias': 'account_id_alias_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 = accountrelationships.UpdateAccountRelationshipRequest.meta.fields["account_relationship"] + + 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["account_relationship"].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["account_relationship"][field])): + del request_init["account_relationship"][field][i][subfield] + else: + del request_init["account_relationship"][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 = accountrelationships.AccountRelationship( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + account_id_alias='account_id_alias_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 = accountrelationships.AccountRelationship.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.update_account_relationship(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accountrelationships.AccountRelationship) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.account_id_alias == 'account_id_alias_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_relationship_rest_interceptors(null_interceptor): + transport = transports.AccountRelationshipsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountRelationshipsServiceRestInterceptor(), + ) + client = AccountRelationshipsServiceClient(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.AccountRelationshipsServiceRestInterceptor, "post_update_account_relationship") as post, \ + mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "post_update_account_relationship_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "pre_update_account_relationship") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountrelationships.UpdateAccountRelationshipRequest.pb(accountrelationships.UpdateAccountRelationshipRequest()) + 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 = accountrelationships.AccountRelationship.to_json(accountrelationships.AccountRelationship()) + req.return_value.content = return_value + + request = accountrelationships.UpdateAccountRelationshipRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountrelationships.AccountRelationship() + post_with_metadata.return_value = accountrelationships.AccountRelationship(), metadata + + client.update_account_relationship(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_account_relationships_rest_bad_request(request_type=accountrelationships.ListAccountRelationshipsRequest): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_account_relationships(request) + + +@pytest.mark.parametrize("request_type", [ + accountrelationships.ListAccountRelationshipsRequest, + dict, +]) +def test_list_account_relationships_rest_call_success(request_type): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accountrelationships.ListAccountRelationshipsResponse( + 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 = accountrelationships.ListAccountRelationshipsResponse.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_account_relationships(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountRelationshipsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_relationships_rest_interceptors(null_interceptor): + transport = transports.AccountRelationshipsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountRelationshipsServiceRestInterceptor(), + ) + client = AccountRelationshipsServiceClient(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.AccountRelationshipsServiceRestInterceptor, "post_list_account_relationships") as post, \ + mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "post_list_account_relationships_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "pre_list_account_relationships") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountrelationships.ListAccountRelationshipsRequest.pb(accountrelationships.ListAccountRelationshipsRequest()) + 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 = accountrelationships.ListAccountRelationshipsResponse.to_json(accountrelationships.ListAccountRelationshipsResponse()) + req.return_value.content = return_value + + request = accountrelationships.ListAccountRelationshipsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountrelationships.ListAccountRelationshipsResponse() + post_with_metadata.return_value = accountrelationships.ListAccountRelationshipsResponse(), metadata + + client.list_account_relationships(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountRelationshipsServiceClient( + 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_get_account_relationship_empty_call_rest(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_relationship), + '__call__') as call: + client.get_account_relationship(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.GetAccountRelationshipRequest() + + 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_update_account_relationship_empty_call_rest(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_relationship), + '__call__') as call: + client.update_account_relationship(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.UpdateAccountRelationshipRequest() + + 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_list_account_relationships_empty_call_rest(): + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_relationships), + '__call__') as call: + client.list_account_relationships(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountrelationships.ListAccountRelationshipsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountRelationshipsServiceGrpcTransport, + ) + +def test_account_relationships_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountRelationshipsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_account_relationships_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountRelationshipsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account_relationship', + 'update_account_relationship', + 'list_account_relationships', + ) + 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_account_relationships_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_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountRelationshipsServiceTransport( + 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_account_relationships_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_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountRelationshipsServiceTransport() + adc.assert_called_once() + + +def test_account_relationships_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) + AccountRelationshipsServiceClient() + 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.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + ], +) +def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + transports.AccountRelationshipsServiceRestTransport, + ], +) +def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, grpc_helpers), + (transports.AccountRelationshipsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, transports.AccountRelationshipsServiceGrpcAsyncIOTransport]) +def test_account_relationships_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_account_relationships_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.AccountRelationshipsServiceRestTransport ( + 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_account_relationships_service_host_no_port(transport_name): + client = AccountRelationshipsServiceClient( + 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_account_relationships_service_host_with_port(transport_name): + client = AccountRelationshipsServiceClient( + 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_account_relationships_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountRelationshipsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountRelationshipsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account_relationship._session + session2 = client2.transport.get_account_relationship._session + assert session1 != session2 + session1 = client1.transport.update_account_relationship._session + session2 = client2.transport.update_account_relationship._session + assert session1 != session2 + session1 = client1.transport.list_account_relationships._session + session2 = client2.transport.list_account_relationships._session + assert session1 != session2 +def test_account_relationships_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountRelationshipsServiceGrpcTransport( + 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_account_relationships_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountRelationshipsServiceGrpcAsyncIOTransport( + 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.AccountRelationshipsServiceGrpcTransport, transports.AccountRelationshipsServiceGrpcAsyncIOTransport]) +def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, transports.AccountRelationshipsServiceGrpcAsyncIOTransport]) +def test_account_relationships_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AccountRelationshipsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AccountRelationshipsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.parse_account_path(path) + assert expected == actual + +def test_account_relationship_path(): + account = "whelk" + relationship = "octopus" + expected = "accounts/{account}/relationships/{relationship}".format(account=account, relationship=relationship, ) + actual = AccountRelationshipsServiceClient.account_relationship_path(account, relationship) + assert expected == actual + + +def test_parse_account_relationship_path(): + expected = { + "account": "oyster", + "relationship": "nudibranch", + } + path = AccountRelationshipsServiceClient.account_relationship_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.parse_account_relationship_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountRelationshipsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AccountRelationshipsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountRelationshipsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AccountRelationshipsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountRelationshipsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AccountRelationshipsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AccountRelationshipsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AccountRelationshipsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.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 = AccountRelationshipsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AccountRelationshipsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountRelationshipsServiceClient.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.AccountRelationshipsServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountRelationshipsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountRelationshipsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountRelationshipsServiceClient.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 = AccountRelationshipsServiceClient( + 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 = AccountRelationshipsServiceAsyncClient( + 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 = AccountRelationshipsServiceClient( + 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 = AccountRelationshipsServiceClient( + 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", [ + (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport), + (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py new file mode 100644 index 000000000000..362eb49c06b3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py @@ -0,0 +1,5133 @@ +# -*- 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.shopping.merchant_accounts_v1.services.account_services_service import AccountServicesServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.account_services_service import AccountServicesServiceClient +from google.shopping.merchant_accounts_v1.services.account_services_service import pagers +from google.shopping.merchant_accounts_v1.services.account_services_service import transports +from google.shopping.merchant_accounts_v1.types import accountservices +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 AccountServicesServiceClient._get_default_mtls_endpoint(None) is None + assert AccountServicesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountServicesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountServicesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountServicesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountServicesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountServicesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountServicesServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountServicesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountServicesServiceClient._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 AccountServicesServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountServicesServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountServicesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountServicesServiceClient._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 AccountServicesServiceClient._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 AccountServicesServiceClient._get_client_cert_source(None, False) is None + assert AccountServicesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountServicesServiceClient._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 AccountServicesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountServicesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) +@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountServicesServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountServicesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountServicesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountServicesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountServicesServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountServicesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountServicesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountServicesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountServicesServiceClient._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 AccountServicesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountServicesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountServicesServiceClient._get_universe_domain(None, None) == AccountServicesServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountServicesServiceClient._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 = AccountServicesServiceClient(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 = AccountServicesServiceClient(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", [ + (AccountServicesServiceClient, "grpc"), + (AccountServicesServiceAsyncClient, "grpc_asyncio"), + (AccountServicesServiceClient, "rest"), +]) +def test_account_services_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.AccountServicesServiceGrpcTransport, "grpc"), + (transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountServicesServiceRestTransport, "rest"), +]) +def test_account_services_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", [ + (AccountServicesServiceClient, "grpc"), + (AccountServicesServiceAsyncClient, "grpc_asyncio"), + (AccountServicesServiceClient, "rest"), +]) +def test_account_services_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_account_services_service_client_get_transport_class(): + transport = AccountServicesServiceClient.get_transport_class() + available_transports = [ + transports.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountServicesServiceClient.get_transport_class("grpc") + assert transport == transports.AccountServicesServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc"), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) +@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) +def test_account_services_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(AccountServicesServiceClient, '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(AccountServicesServiceClient, '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", [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", "true"), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", "false"), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest", "true"), + (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) +@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_account_services_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", [ + AccountServicesServiceClient, AccountServicesServiceAsyncClient +]) +@mock.patch.object(AccountServicesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountServicesServiceClient)) +@mock.patch.object(AccountServicesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountServicesServiceAsyncClient)) +def test_account_services_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", [ + AccountServicesServiceClient, AccountServicesServiceAsyncClient +]) +@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) +@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) +def test_account_services_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountServicesServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountServicesServiceClient._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", [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc"), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest"), +]) +def test_account_services_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", [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", grpc_helpers), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest", None), +]) +def test_account_services_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_account_services_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountServicesServiceClient( + 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", [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", grpc_helpers), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_account_services_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", [ + accountservices.GetAccountServiceRequest, + dict, +]) +def test_get_account_service(request_type, transport: str = 'grpc'): + client = AccountServicesServiceClient( + 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.get_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + ) + response = client.get_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountservices.GetAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +def test_get_account_service_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 = AccountServicesServiceClient( + 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 = accountservices.GetAccountServiceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountservices.GetAccountServiceRequest( + name='name_value', + ) + +def test_get_account_service_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 = AccountServicesServiceClient( + 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.get_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account_service] = mock_rpc + request = {} + client.get_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_service(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_get_account_service_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 = AccountServicesServiceAsyncClient( + 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.get_account_service in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_account_service] = mock_rpc + + request = {} + await client.get_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_account_service(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_get_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.GetAccountServiceRequest): + client = AccountServicesServiceAsyncClient( + 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.get_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + )) + response = await client.get_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountservices.GetAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +@pytest.mark.asyncio +async def test_get_account_service_async_from_dict(): + await test_get_account_service_async(request_type=dict) + +def test_get_account_service_field_headers(): + client = AccountServicesServiceClient( + 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 = accountservices.GetAccountServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + call.return_value = accountservices.AccountService() + client.get_account_service(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_get_account_service_field_headers_async(): + client = AccountServicesServiceAsyncClient( + 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 = accountservices.GetAccountServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + await client.get_account_service(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_get_account_service_flattened(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account_service( + 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_get_account_service_flattened_error(): + client = AccountServicesServiceClient( + 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.get_account_service( + accountservices.GetAccountServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_service_flattened_async(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account_service( + 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_get_account_service_flattened_error_async(): + client = AccountServicesServiceAsyncClient( + 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.get_account_service( + accountservices.GetAccountServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accountservices.ListAccountServicesRequest, + dict, +]) +def test_list_account_services(request_type, transport: str = 'grpc'): + client = AccountServicesServiceClient( + 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_account_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.ListAccountServicesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountservices.ListAccountServicesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountServicesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_services_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 = AccountServicesServiceClient( + 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 = accountservices.ListAccountServicesRequest( + 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_account_services), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_services(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountservices.ListAccountServicesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_account_services_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 = AccountServicesServiceClient( + 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_account_services in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_services] = mock_rpc + request = {} + client.list_account_services(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_services(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_account_services_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 = AccountServicesServiceAsyncClient( + 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_account_services 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_account_services] = mock_rpc + + request = {} + await client.list_account_services(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_account_services(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_account_services_async(transport: str = 'grpc_asyncio', request_type=accountservices.ListAccountServicesRequest): + client = AccountServicesServiceAsyncClient( + 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_account_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountservices.ListAccountServicesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountServicesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_services_async_from_dict(): + await test_list_account_services_async(request_type=dict) + +def test_list_account_services_field_headers(): + client = AccountServicesServiceClient( + 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 = accountservices.ListAccountServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + call.return_value = accountservices.ListAccountServicesResponse() + client.list_account_services(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_account_services_field_headers_async(): + client = AccountServicesServiceAsyncClient( + 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 = accountservices.ListAccountServicesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse()) + await client.list_account_services(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_account_services_flattened(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.ListAccountServicesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_account_services( + 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_account_services_flattened_error(): + client = AccountServicesServiceClient( + 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_account_services( + accountservices.ListAccountServicesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_account_services_flattened_async(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.ListAccountServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_account_services( + 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_account_services_flattened_error_async(): + client = AccountServicesServiceAsyncClient( + 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_account_services( + accountservices.ListAccountServicesRequest(), + parent='parent_value', + ) + + +def test_list_account_services_pager(transport_name: str = "grpc"): + client = AccountServicesServiceClient( + 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_account_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + accountservices.AccountService(), + ], + next_page_token='abc', + ), + accountservices.ListAccountServicesResponse( + account_services=[], + next_page_token='def', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + ], + next_page_token='ghi', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_account_services(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, accountservices.AccountService) + for i in results) +def test_list_account_services_pages(transport_name: str = "grpc"): + client = AccountServicesServiceClient( + 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_account_services), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + accountservices.AccountService(), + ], + next_page_token='abc', + ), + accountservices.ListAccountServicesResponse( + account_services=[], + next_page_token='def', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + ], + next_page_token='ghi', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_services(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_account_services_async_pager(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + accountservices.AccountService(), + ], + next_page_token='abc', + ), + accountservices.ListAccountServicesResponse( + account_services=[], + next_page_token='def', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + ], + next_page_token='ghi', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_services(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, accountservices.AccountService) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_services_async_pages(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + accountservices.AccountService(), + ], + next_page_token='abc', + ), + accountservices.ListAccountServicesResponse( + account_services=[], + next_page_token='def', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + ], + next_page_token='ghi', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + ], + ), + 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_account_services(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", [ + accountservices.ProposeAccountServiceRequest, + dict, +]) +def test_propose_account_service(request_type, transport: str = 'grpc'): + client = AccountServicesServiceClient( + 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.propose_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + ) + response = client.propose_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountservices.ProposeAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +def test_propose_account_service_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 = AccountServicesServiceClient( + 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 = accountservices.ProposeAccountServiceRequest( + parent='parent_value', + provider='provider_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.propose_account_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountservices.ProposeAccountServiceRequest( + parent='parent_value', + provider='provider_value', + ) + +def test_propose_account_service_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 = AccountServicesServiceClient( + 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.propose_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.propose_account_service] = mock_rpc + request = {} + client.propose_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.propose_account_service(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_propose_account_service_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 = AccountServicesServiceAsyncClient( + 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.propose_account_service 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.propose_account_service] = mock_rpc + + request = {} + await client.propose_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.propose_account_service(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_propose_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.ProposeAccountServiceRequest): + client = AccountServicesServiceAsyncClient( + 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.propose_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + )) + response = await client.propose_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountservices.ProposeAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +@pytest.mark.asyncio +async def test_propose_account_service_async_from_dict(): + await test_propose_account_service_async(request_type=dict) + +def test_propose_account_service_field_headers(): + client = AccountServicesServiceClient( + 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 = accountservices.ProposeAccountServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + call.return_value = accountservices.AccountService() + client.propose_account_service(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_propose_account_service_field_headers_async(): + client = AccountServicesServiceAsyncClient( + 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 = accountservices.ProposeAccountServiceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + await client.propose_account_service(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_propose_account_service_flattened(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.propose_account_service( + parent='parent_value', + provider='provider_value', + account_service=accountservices.AccountService(products_management=None), + ) + + # 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 + arg = args[0].provider + mock_val = 'provider_value' + assert arg == mock_val + arg = args[0].account_service + mock_val = accountservices.AccountService(products_management=None) + assert arg == mock_val + + +def test_propose_account_service_flattened_error(): + client = AccountServicesServiceClient( + 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.propose_account_service( + accountservices.ProposeAccountServiceRequest(), + parent='parent_value', + provider='provider_value', + account_service=accountservices.AccountService(products_management=None), + ) + +@pytest.mark.asyncio +async def test_propose_account_service_flattened_async(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.propose_account_service( + parent='parent_value', + provider='provider_value', + account_service=accountservices.AccountService(products_management=None), + ) + + # 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 + arg = args[0].provider + mock_val = 'provider_value' + assert arg == mock_val + arg = args[0].account_service + mock_val = accountservices.AccountService(products_management=None) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_propose_account_service_flattened_error_async(): + client = AccountServicesServiceAsyncClient( + 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.propose_account_service( + accountservices.ProposeAccountServiceRequest(), + parent='parent_value', + provider='provider_value', + account_service=accountservices.AccountService(products_management=None), + ) + + +@pytest.mark.parametrize("request_type", [ + accountservices.ApproveAccountServiceRequest, + dict, +]) +def test_approve_account_service(request_type, transport: str = 'grpc'): + client = AccountServicesServiceClient( + 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.approve_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + ) + response = client.approve_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountservices.ApproveAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +def test_approve_account_service_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 = AccountServicesServiceClient( + 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 = accountservices.ApproveAccountServiceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.approve_account_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountservices.ApproveAccountServiceRequest( + name='name_value', + ) + +def test_approve_account_service_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 = AccountServicesServiceClient( + 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.approve_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.approve_account_service] = mock_rpc + request = {} + client.approve_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.approve_account_service(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_approve_account_service_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 = AccountServicesServiceAsyncClient( + 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.approve_account_service 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.approve_account_service] = mock_rpc + + request = {} + await client.approve_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.approve_account_service(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_approve_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.ApproveAccountServiceRequest): + client = AccountServicesServiceAsyncClient( + 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.approve_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + )) + response = await client.approve_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountservices.ApproveAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +@pytest.mark.asyncio +async def test_approve_account_service_async_from_dict(): + await test_approve_account_service_async(request_type=dict) + +def test_approve_account_service_field_headers(): + client = AccountServicesServiceClient( + 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 = accountservices.ApproveAccountServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + call.return_value = accountservices.AccountService() + client.approve_account_service(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_approve_account_service_field_headers_async(): + client = AccountServicesServiceAsyncClient( + 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 = accountservices.ApproveAccountServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + await client.approve_account_service(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_approve_account_service_flattened(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.approve_account_service( + 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_approve_account_service_flattened_error(): + client = AccountServicesServiceClient( + 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.approve_account_service( + accountservices.ApproveAccountServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_approve_account_service_flattened_async(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountservices.AccountService() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.approve_account_service( + 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_approve_account_service_flattened_error_async(): + client = AccountServicesServiceAsyncClient( + 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.approve_account_service( + accountservices.ApproveAccountServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accountservices.RejectAccountServiceRequest, + dict, +]) +def test_reject_account_service(request_type, transport: str = 'grpc'): + client = AccountServicesServiceClient( + 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.reject_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.reject_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountservices.RejectAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_reject_account_service_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 = AccountServicesServiceClient( + 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 = accountservices.RejectAccountServiceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.reject_account_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountservices.RejectAccountServiceRequest( + name='name_value', + ) + +def test_reject_account_service_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 = AccountServicesServiceClient( + 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.reject_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.reject_account_service] = mock_rpc + request = {} + client.reject_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.reject_account_service(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_reject_account_service_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 = AccountServicesServiceAsyncClient( + 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.reject_account_service 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.reject_account_service] = mock_rpc + + request = {} + await client.reject_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.reject_account_service(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_reject_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.RejectAccountServiceRequest): + client = AccountServicesServiceAsyncClient( + 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.reject_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.reject_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountservices.RejectAccountServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_reject_account_service_async_from_dict(): + await test_reject_account_service_async(request_type=dict) + +def test_reject_account_service_field_headers(): + client = AccountServicesServiceClient( + 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 = accountservices.RejectAccountServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__call__') as call: + call.return_value = None + client.reject_account_service(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_reject_account_service_field_headers_async(): + client = AccountServicesServiceAsyncClient( + 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 = accountservices.RejectAccountServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.reject_account_service(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_reject_account_service_flattened(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__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.reject_account_service( + 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_reject_account_service_flattened_error(): + client = AccountServicesServiceClient( + 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.reject_account_service( + accountservices.RejectAccountServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_reject_account_service_flattened_async(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__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.reject_account_service( + 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_reject_account_service_flattened_error_async(): + client = AccountServicesServiceAsyncClient( + 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.reject_account_service( + accountservices.RejectAccountServiceRequest(), + name='name_value', + ) + + +def test_get_account_service_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 = AccountServicesServiceClient( + 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.get_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account_service] = mock_rpc + + request = {} + client.get_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_service(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_get_account_service_rest_required_fields(request_type=accountservices.GetAccountServiceRequest): + transport_class = transports.AccountServicesServiceRestTransport + + 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()).get_account_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_service._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 = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountservices.AccountService() + # 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 = accountservices.AccountService.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.get_account_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_service_rest_unset_required_fields(): + transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_account_service_rest_flattened(): + client = AccountServicesServiceClient( + 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 = accountservices.AccountService() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/services/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = accountservices.AccountService.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.get_account_service(**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/accounts/v1/{name=accounts/*/services/*}" % client.transport._host, args[1]) + + +def test_get_account_service_rest_flattened_error(transport: str = 'rest'): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_account_service( + accountservices.GetAccountServiceRequest(), + name='name_value', + ) + + +def test_list_account_services_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 = AccountServicesServiceClient( + 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_account_services in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_services] = mock_rpc + + request = {} + client.list_account_services(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_services(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_account_services_rest_required_fields(request_type=accountservices.ListAccountServicesRequest): + transport_class = transports.AccountServicesServiceRestTransport + + 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_account_services._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_account_services._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 = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountservices.ListAccountServicesResponse() + # 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 = accountservices.ListAccountServicesResponse.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_account_services(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_account_services_rest_unset_required_fields(): + transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_account_services._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_account_services_rest_flattened(): + client = AccountServicesServiceClient( + 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 = accountservices.ListAccountServicesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = accountservices.ListAccountServicesResponse.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_account_services(**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/accounts/v1/{parent=accounts/*}/services" % client.transport._host, args[1]) + + +def test_list_account_services_rest_flattened_error(transport: str = 'rest'): + client = AccountServicesServiceClient( + 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_account_services( + accountservices.ListAccountServicesRequest(), + parent='parent_value', + ) + + +def test_list_account_services_rest_pager(transport: str = 'rest'): + client = AccountServicesServiceClient( + 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 = ( + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + accountservices.AccountService(), + ], + next_page_token='abc', + ), + accountservices.ListAccountServicesResponse( + account_services=[], + next_page_token='def', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + ], + next_page_token='ghi', + ), + accountservices.ListAccountServicesResponse( + account_services=[ + accountservices.AccountService(), + accountservices.AccountService(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accountservices.ListAccountServicesResponse.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'} + + pager = client.list_account_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accountservices.AccountService) + for i in results) + + pages = list(client.list_account_services(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_propose_account_service_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 = AccountServicesServiceClient( + 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.propose_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.propose_account_service] = mock_rpc + + request = {} + client.propose_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.propose_account_service(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_propose_account_service_rest_required_fields(request_type=accountservices.ProposeAccountServiceRequest): + transport_class = transports.AccountServicesServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["provider"] = "" + 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()).propose_account_service._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["provider"] = 'provider_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).propose_account_service._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 "provider" in jsonified_request + assert jsonified_request["provider"] == 'provider_value' + + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountservices.AccountService() + # 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 = accountservices.AccountService.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.propose_account_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_propose_account_service_rest_unset_required_fields(): + transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.propose_account_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "provider", "accountService", ))) + + +def test_propose_account_service_rest_flattened(): + client = AccountServicesServiceClient( + 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 = accountservices.AccountService() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + provider='provider_value', + account_service=accountservices.AccountService(products_management=None), + ) + 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 = accountservices.AccountService.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.propose_account_service(**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/accounts/v1/{parent=accounts/*}/services:propose" % client.transport._host, args[1]) + + +def test_propose_account_service_rest_flattened_error(transport: str = 'rest'): + client = AccountServicesServiceClient( + 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.propose_account_service( + accountservices.ProposeAccountServiceRequest(), + parent='parent_value', + provider='provider_value', + account_service=accountservices.AccountService(products_management=None), + ) + + +def test_approve_account_service_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 = AccountServicesServiceClient( + 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.approve_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.approve_account_service] = mock_rpc + + request = {} + client.approve_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.approve_account_service(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_approve_account_service_rest_required_fields(request_type=accountservices.ApproveAccountServiceRequest): + transport_class = transports.AccountServicesServiceRestTransport + + 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()).approve_account_service._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()).approve_account_service._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 = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountservices.AccountService() + # 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 = accountservices.AccountService.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.approve_account_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_approve_account_service_rest_unset_required_fields(): + transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.approve_account_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_approve_account_service_rest_flattened(): + client = AccountServicesServiceClient( + 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 = accountservices.AccountService() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/services/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = accountservices.AccountService.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.approve_account_service(**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/accounts/v1/{name=accounts/*/services/*}:approve" % client.transport._host, args[1]) + + +def test_approve_account_service_rest_flattened_error(transport: str = 'rest'): + client = AccountServicesServiceClient( + 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.approve_account_service( + accountservices.ApproveAccountServiceRequest(), + name='name_value', + ) + + +def test_reject_account_service_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 = AccountServicesServiceClient( + 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.reject_account_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.reject_account_service] = mock_rpc + + request = {} + client.reject_account_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.reject_account_service(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_reject_account_service_rest_required_fields(request_type=accountservices.RejectAccountServiceRequest): + transport_class = transports.AccountServicesServiceRestTransport + + 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()).reject_account_service._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()).reject_account_service._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 = AccountServicesServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = 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.reject_account_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_reject_account_service_rest_unset_required_fields(): + transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.reject_account_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_reject_account_service_rest_flattened(): + client = AccountServicesServiceClient( + 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/services/sample2'} + + # 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.reject_account_service(**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/accounts/v1/{name=accounts/*/services/*}:reject" % client.transport._host, args[1]) + + +def test_reject_account_service_rest_flattened_error(transport: str = 'rest'): + client = AccountServicesServiceClient( + 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.reject_account_service( + accountservices.RejectAccountServiceRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountServicesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountServicesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountServicesServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountServicesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountServicesServiceClient( + 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 = AccountServicesServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountServicesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountServicesServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountServicesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountServicesServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountServicesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountServicesServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + transports.AccountServicesServiceRestTransport, +]) +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 = AccountServicesServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountServicesServiceClient( + 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_get_account_service_empty_call_grpc(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + call.return_value = accountservices.AccountService() + client.get_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.GetAccountServiceRequest() + + 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_list_account_services_empty_call_grpc(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + call.return_value = accountservices.ListAccountServicesResponse() + client.list_account_services(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ListAccountServicesRequest() + + 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_propose_account_service_empty_call_grpc(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + call.return_value = accountservices.AccountService() + client.propose_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ProposeAccountServiceRequest() + + 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_approve_account_service_empty_call_grpc(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + call.return_value = accountservices.AccountService() + client.approve_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ApproveAccountServiceRequest() + + 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_reject_account_service_empty_call_grpc(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__call__') as call: + call.return_value = None + client.reject_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.RejectAccountServiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountServicesServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountServicesServiceAsyncClient( + 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_get_account_service_empty_call_grpc_asyncio(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + )) + await client.get_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.GetAccountServiceRequest() + + 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_list_account_services_empty_call_grpc_asyncio(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse( + next_page_token='next_page_token_value', + )) + await client.list_account_services(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ListAccountServicesRequest() + + 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_propose_account_service_empty_call_grpc_asyncio(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + )) + await client.propose_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ProposeAccountServiceRequest() + + 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_approve_account_service_empty_call_grpc_asyncio(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_value', + )) + await client.approve_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ApproveAccountServiceRequest() + + 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_reject_account_service_empty_call_grpc_asyncio(): + client = AccountServicesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.reject_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.RejectAccountServiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountServicesServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_account_service_rest_bad_request(request_type=accountservices.GetAccountServiceRequest): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/services/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.get_account_service(request) + + +@pytest.mark.parametrize("request_type", [ + accountservices.GetAccountServiceRequest, + dict, +]) +def test_get_account_service_rest_call_success(request_type): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/services/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 = accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_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 = accountservices.AccountService.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.get_account_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_service_rest_interceptors(null_interceptor): + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), + ) + client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_get_account_service") as post, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_get_account_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_get_account_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountservices.GetAccountServiceRequest.pb(accountservices.GetAccountServiceRequest()) + 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 = accountservices.AccountService.to_json(accountservices.AccountService()) + req.return_value.content = return_value + + request = accountservices.GetAccountServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountservices.AccountService() + post_with_metadata.return_value = accountservices.AccountService(), metadata + + client.get_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_account_services_rest_bad_request(request_type=accountservices.ListAccountServicesRequest): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_account_services(request) + + +@pytest.mark.parametrize("request_type", [ + accountservices.ListAccountServicesRequest, + dict, +]) +def test_list_account_services_rest_call_success(request_type): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accountservices.ListAccountServicesResponse( + 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 = accountservices.ListAccountServicesResponse.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_account_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountServicesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_services_rest_interceptors(null_interceptor): + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), + ) + client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_list_account_services") as post, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_list_account_services_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_list_account_services") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountservices.ListAccountServicesRequest.pb(accountservices.ListAccountServicesRequest()) + 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 = accountservices.ListAccountServicesResponse.to_json(accountservices.ListAccountServicesResponse()) + req.return_value.content = return_value + + request = accountservices.ListAccountServicesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountservices.ListAccountServicesResponse() + post_with_metadata.return_value = accountservices.ListAccountServicesResponse(), metadata + + client.list_account_services(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_propose_account_service_rest_bad_request(request_type=accountservices.ProposeAccountServiceRequest): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.propose_account_service(request) + + +@pytest.mark.parametrize("request_type", [ + accountservices.ProposeAccountServiceRequest, + dict, +]) +def test_propose_account_service_rest_call_success(request_type): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_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 = accountservices.AccountService.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.propose_account_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_propose_account_service_rest_interceptors(null_interceptor): + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), + ) + client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_propose_account_service") as post, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_propose_account_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_propose_account_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountservices.ProposeAccountServiceRequest.pb(accountservices.ProposeAccountServiceRequest()) + 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 = accountservices.AccountService.to_json(accountservices.AccountService()) + req.return_value.content = return_value + + request = accountservices.ProposeAccountServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountservices.AccountService() + post_with_metadata.return_value = accountservices.AccountService(), metadata + + client.propose_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_approve_account_service_rest_bad_request(request_type=accountservices.ApproveAccountServiceRequest): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/services/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.approve_account_service(request) + + +@pytest.mark.parametrize("request_type", [ + accountservices.ApproveAccountServiceRequest, + dict, +]) +def test_approve_account_service_rest_call_success(request_type): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/services/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 = accountservices.AccountService( + name='name_value', + provider='provider_value', + provider_display_name='provider_display_name_value', + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id='external_account_id_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 = accountservices.AccountService.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.approve_account_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accountservices.AccountService) + assert response.name == 'name_value' + assert response.provider == 'provider_value' + assert response.provider_display_name == 'provider_display_name_value' + assert response.mutability == accountservices.AccountService.Mutability.MUTABLE + assert response.external_account_id == 'external_account_id_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_approve_account_service_rest_interceptors(null_interceptor): + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), + ) + client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_approve_account_service") as post, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_approve_account_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_approve_account_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountservices.ApproveAccountServiceRequest.pb(accountservices.ApproveAccountServiceRequest()) + 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 = accountservices.AccountService.to_json(accountservices.AccountService()) + req.return_value.content = return_value + + request = accountservices.ApproveAccountServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountservices.AccountService() + post_with_metadata.return_value = accountservices.AccountService(), metadata + + client.approve_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_reject_account_service_rest_bad_request(request_type=accountservices.RejectAccountServiceRequest): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/services/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.reject_account_service(request) + + +@pytest.mark.parametrize("request_type", [ + accountservices.RejectAccountServiceRequest, + dict, +]) +def test_reject_account_service_rest_call_success(request_type): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/services/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 = 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.reject_account_service(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reject_account_service_rest_interceptors(null_interceptor): + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), + ) + client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "pre_reject_account_service") as pre: + pre.assert_not_called() + pb_message = accountservices.RejectAccountServiceRequest.pb(accountservices.RejectAccountServiceRequest()) + 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 = accountservices.RejectAccountServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.reject_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountServicesServiceClient( + 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_get_account_service_empty_call_rest(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_service), + '__call__') as call: + client.get_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.GetAccountServiceRequest() + + 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_list_account_services_empty_call_rest(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_services), + '__call__') as call: + client.list_account_services(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ListAccountServicesRequest() + + 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_propose_account_service_empty_call_rest(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.propose_account_service), + '__call__') as call: + client.propose_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ProposeAccountServiceRequest() + + 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_approve_account_service_empty_call_rest(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.approve_account_service), + '__call__') as call: + client.approve_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.ApproveAccountServiceRequest() + + 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_reject_account_service_empty_call_rest(): + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reject_account_service), + '__call__') as call: + client.reject_account_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountservices.RejectAccountServiceRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountServicesServiceGrpcTransport, + ) + +def test_account_services_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountServicesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_account_services_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountServicesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account_service', + 'list_account_services', + 'propose_account_service', + 'approve_account_service', + 'reject_account_service', + ) + 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_account_services_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_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountServicesServiceTransport( + 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_account_services_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_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountServicesServiceTransport() + adc.assert_called_once() + + +def test_account_services_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) + AccountServicesServiceClient() + 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.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + ], +) +def test_account_services_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.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + transports.AccountServicesServiceRestTransport, + ], +) +def test_account_services_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.AccountServicesServiceGrpcTransport, grpc_helpers), + (transports.AccountServicesServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_account_services_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.AccountServicesServiceGrpcTransport, transports.AccountServicesServiceGrpcAsyncIOTransport]) +def test_account_services_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_account_services_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.AccountServicesServiceRestTransport ( + 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_account_services_service_host_no_port(transport_name): + client = AccountServicesServiceClient( + 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_account_services_service_host_with_port(transport_name): + client = AccountServicesServiceClient( + 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_account_services_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountServicesServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountServicesServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account_service._session + session2 = client2.transport.get_account_service._session + assert session1 != session2 + session1 = client1.transport.list_account_services._session + session2 = client2.transport.list_account_services._session + assert session1 != session2 + session1 = client1.transport.propose_account_service._session + session2 = client2.transport.propose_account_service._session + assert session1 != session2 + session1 = client1.transport.approve_account_service._session + session2 = client2.transport.approve_account_service._session + assert session1 != session2 + session1 = client1.transport.reject_account_service._session + session2 = client2.transport.reject_account_service._session + assert session1 != session2 +def test_account_services_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountServicesServiceGrpcTransport( + 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_account_services_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountServicesServiceGrpcAsyncIOTransport( + 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.AccountServicesServiceGrpcTransport, transports.AccountServicesServiceGrpcAsyncIOTransport]) +def test_account_services_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.AccountServicesServiceGrpcTransport, transports.AccountServicesServiceGrpcAsyncIOTransport]) +def test_account_services_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AccountServicesServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AccountServicesServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.parse_account_path(path) + assert expected == actual + +def test_account_service_path(): + account = "whelk" + service = "octopus" + expected = "accounts/{account}/services/{service}".format(account=account, service=service, ) + actual = AccountServicesServiceClient.account_service_path(account, service) + assert expected == actual + + +def test_parse_account_service_path(): + expected = { + "account": "oyster", + "service": "nudibranch", + } + path = AccountServicesServiceClient.account_service_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.parse_account_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountServicesServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AccountServicesServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountServicesServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AccountServicesServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountServicesServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AccountServicesServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AccountServicesServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AccountServicesServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.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 = AccountServicesServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AccountServicesServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountServicesServiceClient.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.AccountServicesServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountServicesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountServicesServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountServicesServiceClient.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 = AccountServicesServiceClient( + 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 = AccountServicesServiceAsyncClient( + 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 = AccountServicesServiceClient( + 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 = AccountServicesServiceClient( + 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", [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport), + (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py new file mode 100644 index 000000000000..28c58a938938 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py @@ -0,0 +1,5633 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.accounts_service import AccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.accounts_service import AccountsServiceClient +from google.shopping.merchant_accounts_v1.services.accounts_service import pagers +from google.shopping.merchant_accounts_v1.services.accounts_service import transports +from google.shopping.merchant_accounts_v1.types import accessright +from google.shopping.merchant_accounts_v1.types import accounts +from google.shopping.merchant_accounts_v1.types import accountservices +from google.shopping.merchant_accounts_v1.types import user +from google.type import datetime_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 AccountsServiceClient._get_default_mtls_endpoint(None) is None + assert AccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountsServiceClient._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 AccountsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountsServiceClient._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 AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, False) is None + assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountsServiceClient._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 AccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountsServiceClient._get_universe_domain(None, None) == AccountsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountsServiceClient._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 = AccountsServiceClient(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 = AccountsServiceClient(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", [ + (AccountsServiceClient, "grpc"), + (AccountsServiceAsyncClient, "grpc_asyncio"), + (AccountsServiceClient, "rest"), +]) +def test_accounts_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.AccountsServiceGrpcTransport, "grpc"), + (transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountsServiceRestTransport, "rest"), +]) +def test_accounts_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", [ + (AccountsServiceClient, "grpc"), + (AccountsServiceAsyncClient, "grpc_asyncio"), + (AccountsServiceClient, "rest"), +]) +def test_accounts_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_accounts_service_client_get_transport_class(): + transport = AccountsServiceClient.get_transport_class() + available_transports = [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountsServiceClient.get_transport_class("grpc") + assert transport == transports.AccountsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +def test_accounts_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(AccountsServiceClient, '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(AccountsServiceClient, '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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "true"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "false"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "true"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_accounts_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", [ + AccountsServiceClient, AccountsServiceAsyncClient +]) +@mock.patch.object(AccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceAsyncClient)) +def test_accounts_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", [ + AccountsServiceClient, AccountsServiceAsyncClient +]) +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +def test_accounts_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountsServiceClient._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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), +]) +def test_accounts_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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", None), +]) +def test_accounts_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_accounts_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountsServiceClient( + 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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_accounts_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", [ + accounts.GetAccountRequest, + dict, +]) +def test_get_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + ) + response = client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +def test_get_account_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 = AccountsServiceClient( + 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 = accounts.GetAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.GetAccountRequest( + name='name_value', + ) + +def test_get_account_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 = AccountsServiceClient( + 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.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(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_get_account_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 = AccountsServiceAsyncClient( + 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.get_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_account] = mock_rpc + + request = {} + await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_account(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_get_account_async(transport: str = 'grpc_asyncio', request_type=accounts.GetAccountRequest): + client = AccountsServiceAsyncClient( + 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.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + response = await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_account_async_from_dict(): + await test_get_account_async(request_type=dict) + +def test_get_account_field_headers(): + client = AccountsServiceClient( + 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 = accounts.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = accounts.Account() + client.get_account(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_get_account_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + await client.get_account(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_get_account_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account( + 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_get_account_flattened_error(): + client = AccountsServiceClient( + 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.get_account( + accounts.GetAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account( + 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_get_account_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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.get_account( + accounts.GetAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accounts.CreateAndConfigureAccountRequest, + dict, +]) +def test_create_and_configure_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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.create_and_configure_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + ) + response = client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.CreateAndConfigureAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +def test_create_and_configure_account_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 = AccountsServiceClient( + 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 = accounts.CreateAndConfigureAccountRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_and_configure_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.CreateAndConfigureAccountRequest( + ) + +def test_create_and_configure_account_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 = AccountsServiceClient( + 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.create_and_configure_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc + request = {} + client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_and_configure_account(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_create_and_configure_account_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 = AccountsServiceAsyncClient( + 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.create_and_configure_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_and_configure_account] = mock_rpc + + request = {} + await client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_and_configure_account(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_create_and_configure_account_async(transport: str = 'grpc_asyncio', request_type=accounts.CreateAndConfigureAccountRequest): + client = AccountsServiceAsyncClient( + 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.create_and_configure_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + response = await client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.CreateAndConfigureAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_and_configure_account_async_from_dict(): + await test_create_and_configure_account_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + accounts.DeleteAccountRequest, + dict, +]) +def test_delete_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.DeleteAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_account_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 = AccountsServiceClient( + 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 = accounts.DeleteAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.DeleteAccountRequest( + name='name_value', + ) + +def test_delete_account_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 = AccountsServiceClient( + 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_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account] = mock_rpc + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(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_account_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 = AccountsServiceAsyncClient( + 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_account 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_account] = mock_rpc + + request = {} + await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_account(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_account_async(transport: str = 'grpc_asyncio', request_type=accounts.DeleteAccountRequest): + client = AccountsServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.DeleteAccountRequest() + 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_account_async_from_dict(): + await test_delete_account_async(request_type=dict) + +def test_delete_account_field_headers(): + client = AccountsServiceClient( + 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 = accounts.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = None + client.delete_account(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_account_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_account(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_account_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error(): + client = AccountsServiceClient( + 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_account( + accounts.DeleteAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_account_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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_account( + accounts.DeleteAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accounts.UpdateAccountRequest, + dict, +]) +def test_update_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + ) + response = client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +def test_update_account_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 = AccountsServiceClient( + 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 = accounts.UpdateAccountRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.UpdateAccountRequest( + ) + +def test_update_account_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 = AccountsServiceClient( + 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.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(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_update_account_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 = AccountsServiceAsyncClient( + 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.update_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_account] = mock_rpc + + request = {} + await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_account(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_update_account_async(transport: str = 'grpc_asyncio', request_type=accounts.UpdateAccountRequest): + client = AccountsServiceAsyncClient( + 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.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + response = await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_update_account_async_from_dict(): + await test_update_account_async(request_type=dict) + +def test_update_account_field_headers(): + client = AccountsServiceClient( + 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 = accounts.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = accounts.Account() + client.update_account(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', + 'account.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_account_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + await client.update_account(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', + 'account.name=name_value', + ) in kw['metadata'] + + +def test_update_account_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_account( + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account + mock_val = accounts.Account(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_account_flattened_error(): + client = AccountsServiceClient( + 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.update_account( + accounts.UpdateAccountRequest(), + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_account_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account( + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account + mock_val = accounts.Account(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_account_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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.update_account( + accounts.UpdateAccountRequest(), + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + accounts.ListAccountsRequest, + dict, +]) +def test_list_accounts(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_accounts_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 = AccountsServiceClient( + 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 = accounts.ListAccountsRequest( + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.ListAccountsRequest( + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_accounts_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 = AccountsServiceClient( + 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_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_accounts] = mock_rpc + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(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_accounts_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 = AccountsServiceAsyncClient( + 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_accounts 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_accounts] = mock_rpc + + request = {} + await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_accounts(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_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListAccountsRequest): + client = AccountsServiceAsyncClient( + 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_accounts_async_from_dict(): + await test_list_accounts_async(request_type=dict) + + +def test_list_accounts_pager(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_accounts(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, accounts.Account) + for i in results) +def test_list_accounts_pages(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + pages = list(client.list_accounts(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_accounts_async_pager(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_accounts(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, accounts.Account) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_accounts_async_pages(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + 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_accounts(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", [ + accounts.ListSubAccountsRequest, + dict, +]) +def test_list_sub_accounts(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListSubAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.ListSubAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sub_accounts_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 = AccountsServiceClient( + 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 = accounts.ListSubAccountsRequest( + provider='provider_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_sub_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sub_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.ListSubAccountsRequest( + provider='provider_value', + page_token='page_token_value', + ) + +def test_list_sub_accounts_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 = AccountsServiceClient( + 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_sub_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_sub_accounts] = mock_rpc + request = {} + client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sub_accounts(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_sub_accounts_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 = AccountsServiceAsyncClient( + 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_sub_accounts 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_sub_accounts] = mock_rpc + + request = {} + await client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_sub_accounts(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_sub_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListSubAccountsRequest): + client = AccountsServiceAsyncClient( + 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_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.ListSubAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sub_accounts_async_from_dict(): + await test_list_sub_accounts_async(request_type=dict) + +def test_list_sub_accounts_field_headers(): + client = AccountsServiceClient( + 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 = accounts.ListSubAccountsRequest() + + request.provider = 'provider_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + call.return_value = accounts.ListSubAccountsResponse() + client.list_sub_accounts(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', + 'provider=provider_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_sub_accounts_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.ListSubAccountsRequest() + + request.provider = 'provider_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) + await client.list_sub_accounts(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', + 'provider=provider_value', + ) in kw['metadata'] + + +def test_list_sub_accounts_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListSubAccountsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sub_accounts( + provider='provider_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].provider + mock_val = 'provider_value' + assert arg == mock_val + + +def test_list_sub_accounts_flattened_error(): + client = AccountsServiceClient( + 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_sub_accounts( + accounts.ListSubAccountsRequest(), + provider='provider_value', + ) + +@pytest.mark.asyncio +async def test_list_sub_accounts_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListSubAccountsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sub_accounts( + provider='provider_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].provider + mock_val = 'provider_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_sub_accounts_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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_sub_accounts( + accounts.ListSubAccountsRequest(), + provider='provider_value', + ) + + +def test_list_sub_accounts_pager(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_sub_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('provider', ''), + )), + ) + pager = client.list_sub_accounts(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, accounts.Account) + for i in results) +def test_list_sub_accounts_pages(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_sub_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sub_accounts(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_sub_accounts_async_pager(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sub_accounts(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, accounts.Account) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sub_accounts_async_pages(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + 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_sub_accounts(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_account_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 = AccountsServiceClient( + 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.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(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_get_account_rest_required_fields(request_type=accounts.GetAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + 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()).get_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account._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 = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.Account() + # 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 = accounts.Account.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.get_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_account_rest_flattened(): + client = AccountsServiceClient( + 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 = accounts.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1'} + + # 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 + # Convert return value to protobuf type + return_value = accounts.Account.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.get_account(**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/accounts/v1/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_get_account_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_account( + accounts.GetAccountRequest(), + name='name_value', + ) + + +def test_create_and_configure_account_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 = AccountsServiceClient( + 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.create_and_configure_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc + + request = {} + client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_and_configure_account(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_create_and_configure_account_rest_required_fields(request_type=accounts.CreateAndConfigureAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.Account() + # 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 = accounts.Account.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.create_and_configure_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_and_configure_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_and_configure_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("account", "service", ))) + + +def test_delete_account_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 = AccountsServiceClient( + 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_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account] = mock_rpc + + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(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_account_rest_required_fields(request_type=accounts.DeleteAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + 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_account._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_account._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + 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 = AccountsServiceClient( + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +def test_delete_account_rest_flattened(): + client = AccountsServiceClient( + 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'} + + # 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_account(**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/accounts/v1/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_delete_account_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + 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_account( + accounts.DeleteAccountRequest(), + name='name_value', + ) + + +def test_update_account_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 = AccountsServiceClient( + 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.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(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_update_account_rest_required_fields(request_type=accounts.UpdateAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.Account() + # 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': "patch", + '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 = accounts.Account.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.update_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("account", ))) + + +def test_update_account_rest_flattened(): + client = AccountsServiceClient( + 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 = accounts.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'account': {'name': 'accounts/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = accounts.Account.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.update_account(**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/accounts/v1/{account.name=accounts/*}" % client.transport._host, args[1]) + + +def test_update_account_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + 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.update_account( + accounts.UpdateAccountRequest(), + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_accounts_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 = AccountsServiceClient( + 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_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_accounts] = mock_rpc + + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(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_accounts_rest_pager(transport: str = 'rest'): + client = AccountsServiceClient( + 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 = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accounts.ListAccountsResponse.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 = {} + + pager = client.list_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accounts.Account) + for i in results) + + pages = list(client.list_accounts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_sub_accounts_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 = AccountsServiceClient( + 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_sub_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_sub_accounts] = mock_rpc + + request = {} + client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sub_accounts(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_sub_accounts_rest_required_fields(request_type=accounts.ListSubAccountsRequest): + transport_class = transports.AccountsServiceRestTransport + + request_init = {} + request_init["provider"] = "" + 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_sub_accounts._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["provider"] = 'provider_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_sub_accounts._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 "provider" in jsonified_request + assert jsonified_request["provider"] == 'provider_value' + + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.ListSubAccountsResponse() + # 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 = accounts.ListSubAccountsResponse.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_sub_accounts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sub_accounts_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sub_accounts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("provider", ))) + + +def test_list_sub_accounts_rest_flattened(): + client = AccountsServiceClient( + 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 = accounts.ListSubAccountsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'provider': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + provider='provider_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 = accounts.ListSubAccountsResponse.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_sub_accounts(**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/accounts/v1/{provider=accounts/*}:listSubaccounts" % client.transport._host, args[1]) + + +def test_list_sub_accounts_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + 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_sub_accounts( + accounts.ListSubAccountsRequest(), + provider='provider_value', + ) + + +def test_list_sub_accounts_rest_pager(transport: str = 'rest'): + client = AccountsServiceClient( + 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 = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accounts.ListSubAccountsResponse.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 = {'provider': 'accounts/sample1'} + + pager = client.list_sub_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accounts.Account) + for i in results) + + pages = list(client.list_sub_accounts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountsServiceClient( + 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 = AccountsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + transports.AccountsServiceRestTransport, +]) +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 = AccountsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountsServiceClient( + 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_get_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = accounts.Account() + client.get_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.GetAccountRequest() + + 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_create_and_configure_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + call.return_value = accounts.Account() + client.create_and_configure_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.CreateAndConfigureAccountRequest() + + 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_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = None + client.delete_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.DeleteAccountRequest() + + 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_update_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = accounts.Account() + client.update_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.UpdateAccountRequest() + + 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_list_accounts_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + call.return_value = accounts.ListAccountsResponse() + client.list_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListAccountsRequest() + + 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_list_sub_accounts_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + call.return_value = accounts.ListSubAccountsResponse() + client.list_sub_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListSubAccountsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountsServiceAsyncClient( + 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_get_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + await client.get_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.GetAccountRequest() + + 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_create_and_configure_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + await client.create_and_configure_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.CreateAndConfigureAccountRequest() + + 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_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.DeleteAccountRequest() + + 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_update_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + await client.update_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.UpdateAccountRequest() + + 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_list_accounts_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + await client.list_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListAccountsRequest() + + 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_list_sub_accounts_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( + next_page_token='next_page_token_value', + )) + await client.list_sub_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListSubAccountsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_account_rest_bad_request(request_type=accounts.GetAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + 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.get_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.GetAccountRequest, + dict, +]) +def test_get_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_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 = accounts.Account.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.get_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_get_account") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_get_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_get_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.GetAccountRequest.pb(accounts.GetAccountRequest()) + 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 = accounts.Account.to_json(accounts.Account()) + req.return_value.content = return_value + + request = accounts.GetAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.Account() + post_with_metadata.return_value = accounts.Account(), metadata + + client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_and_configure_account_rest_bad_request(request_type=accounts.CreateAndConfigureAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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.create_and_configure_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.CreateAndConfigureAccountRequest, + dict, +]) +def test_create_and_configure_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_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 = accounts.Account.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.create_and_configure_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_and_configure_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_create_and_configure_account") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_create_and_configure_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_create_and_configure_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.CreateAndConfigureAccountRequest.pb(accounts.CreateAndConfigureAccountRequest()) + 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 = accounts.Account.to_json(accounts.Account()) + req.return_value.content = return_value + + request = accounts.CreateAndConfigureAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.Account() + post_with_metadata.return_value = accounts.Account(), metadata + + client.create_and_configure_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_account_rest_bad_request(request_type=accounts.DeleteAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + 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_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.DeleteAccountRequest, + dict, +]) +def test_delete_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_account(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_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "pre_delete_account") as pre: + pre.assert_not_called() + pb_message = accounts.DeleteAccountRequest.pb(accounts.DeleteAccountRequest()) + 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 = accounts.DeleteAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_update_account_rest_bad_request(request_type=accounts.UpdateAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/sample1'}} + 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.update_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.UpdateAccountRequest, + dict, +]) +def test_update_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/sample1'}} + request_init["account"] = {'name': 'accounts/sample1', 'account_id': 1049, 'account_name': 'account_name_value', 'adult_content': True, 'test_account': True, 'time_zone': {'id': 'id_value', 'version': 'version_value'}, 'language_code': 'language_code_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 = accounts.UpdateAccountRequest.meta.fields["account"] + + 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["account"].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["account"][field])): + del request_init["account"][field][i][subfield] + else: + del request_init["account"][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 = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_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 = accounts.Account.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.update_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_update_account") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_update_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_update_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.UpdateAccountRequest.pb(accounts.UpdateAccountRequest()) + 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 = accounts.Account.to_json(accounts.Account()) + req.return_value.content = return_value + + request = accounts.UpdateAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.Account() + post_with_metadata.return_value = accounts.Account(), metadata + + client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_accounts_rest_bad_request(request_type=accounts.ListAccountsRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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_accounts(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.ListAccountsRequest, + dict, +]) +def test_list_accounts_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.ListAccountsResponse( + 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 = accounts.ListAccountsResponse.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_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_accounts_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_accounts") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_accounts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.ListAccountsRequest.pb(accounts.ListAccountsRequest()) + 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 = accounts.ListAccountsResponse.to_json(accounts.ListAccountsResponse()) + req.return_value.content = return_value + + request = accounts.ListAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.ListAccountsResponse() + post_with_metadata.return_value = accounts.ListAccountsResponse(), metadata + + client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_sub_accounts_rest_bad_request(request_type=accounts.ListSubAccountsRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'provider': 'accounts/sample1'} + 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_sub_accounts(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.ListSubAccountsRequest, + dict, +]) +def test_list_sub_accounts_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'provider': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.ListSubAccountsResponse( + 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 = accounts.ListSubAccountsResponse.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_sub_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sub_accounts_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_sub_accounts") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_sub_accounts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_sub_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.ListSubAccountsRequest.pb(accounts.ListSubAccountsRequest()) + 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 = accounts.ListSubAccountsResponse.to_json(accounts.ListSubAccountsResponse()) + req.return_value.content = return_value + + request = accounts.ListSubAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.ListSubAccountsResponse() + post_with_metadata.return_value = accounts.ListSubAccountsResponse(), metadata + + client.list_sub_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountsServiceClient( + 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_get_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + client.get_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.GetAccountRequest() + + 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_create_and_configure_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + client.create_and_configure_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.CreateAndConfigureAccountRequest() + + 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_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + client.delete_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.DeleteAccountRequest() + + 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_update_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + client.update_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.UpdateAccountRequest() + + 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_list_accounts_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + client.list_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListAccountsRequest() + + 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_list_sub_accounts_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + client.list_sub_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListSubAccountsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountsServiceGrpcTransport, + ) + +def test_accounts_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_accounts_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account', + 'create_and_configure_account', + 'delete_account', + 'update_account', + 'list_accounts', + 'list_sub_accounts', + ) + 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_accounts_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_accounts_v1.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountsServiceTransport( + 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_accounts_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_accounts_v1.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountsServiceTransport() + adc.assert_called_once() + + +def test_accounts_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) + AccountsServiceClient() + 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.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + ], +) +def test_accounts_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.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + transports.AccountsServiceRestTransport, + ], +) +def test_accounts_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.AccountsServiceGrpcTransport, grpc_helpers), + (transports.AccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +def test_accounts_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_accounts_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.AccountsServiceRestTransport ( + 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_accounts_service_host_no_port(transport_name): + client = AccountsServiceClient( + 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_accounts_service_host_with_port(transport_name): + client = AccountsServiceClient( + 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_accounts_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account._session + session2 = client2.transport.get_account._session + assert session1 != session2 + session1 = client1.transport.create_and_configure_account._session + session2 = client2.transport.create_and_configure_account._session + assert session1 != session2 + session1 = client1.transport.delete_account._session + session2 = client2.transport.delete_account._session + assert session1 != session2 + session1 = client1.transport.update_account._session + session2 = client2.transport.update_account._session + assert session1 != session2 + session1 = client1.transport.list_accounts._session + session2 = client2.transport.list_accounts._session + assert session1 != session2 + session1 = client1.transport.list_sub_accounts._session + session2 = client2.transport.list_sub_accounts._session + assert session1 != session2 +def test_accounts_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountsServiceGrpcTransport( + 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_accounts_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountsServiceGrpcAsyncIOTransport( + 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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +def test_accounts_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AccountsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AccountsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_account_path(path) + assert expected == actual + +def test_user_path(): + account = "whelk" + email = "octopus" + expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) + actual = AccountsServiceClient.user_path(account, email) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "account": "oyster", + "email": "nudibranch", + } + path = AccountsServiceClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AccountsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AccountsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AccountsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AccountsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AccountsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.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 = AccountsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AccountsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.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.AccountsServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountsServiceClient.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 = AccountsServiceClient( + 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 = AccountsServiceAsyncClient( + 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 = AccountsServiceClient( + 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 = AccountsServiceClient( + 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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py new file mode 100644 index 000000000000..bc40953915c2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py @@ -0,0 +1,2890 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import AutofeedSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import transports +from google.shopping.merchant_accounts_v1.types import autofeedsettings +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 AutofeedSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, False) is None + assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AutofeedSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AutofeedSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AutofeedSettingsServiceClient._get_universe_domain(None, None) == AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient(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 = AutofeedSettingsServiceClient(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", [ + (AutofeedSettingsServiceClient, "grpc"), + (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), + (AutofeedSettingsServiceClient, "rest"), +]) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, "grpc"), + (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +def test_autofeed_settings_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", [ + (AutofeedSettingsServiceClient, "grpc"), + (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), + (AutofeedSettingsServiceClient, "rest"), +]) +def test_autofeed_settings_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_autofeed_settings_service_client_get_transport_class(): + transport = AutofeedSettingsServiceClient.get_transport_class() + available_transports = [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = AutofeedSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.AutofeedSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +def test_autofeed_settings_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(AutofeedSettingsServiceClient, '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(AutofeedSettingsServiceClient, '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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "true"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "false"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "true"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_autofeed_settings_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", [ + AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient +]) +@mock.patch.object(AutofeedSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceAsyncClient)) +def test_autofeed_settings_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", [ + AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient +]) +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +def test_autofeed_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutofeedSettingsServiceClient._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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +def test_autofeed_settings_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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", None), +]) +def test_autofeed_settings_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_autofeed_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AutofeedSettingsServiceClient( + 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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_autofeed_settings_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", [ + autofeedsettings.GetAutofeedSettingsRequest, + dict, +]) +def test_get_autofeed_settings(request_type, transport: str = 'grpc'): + client = AutofeedSettingsServiceClient( + 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.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + response = client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autofeedsettings.GetAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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 = autofeedsettings.GetAutofeedSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_autofeed_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autofeedsettings.GetAutofeedSettingsRequest( + name='name_value', + ) + +def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.get_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc + request = {} + client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_autofeed_settings(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_get_autofeed_settings_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 = AutofeedSettingsServiceAsyncClient( + 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.get_autofeed_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_autofeed_settings] = mock_rpc + + request = {} + await client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_autofeed_settings(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_get_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.GetAutofeedSettingsRequest): + client = AutofeedSettingsServiceAsyncClient( + 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.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + response = await client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autofeedsettings.GetAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.asyncio +async def test_get_autofeed_settings_async_from_dict(): + await test_get_autofeed_settings_async(request_type=dict) + +def test_get_autofeed_settings_field_headers(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.GetAutofeedSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.get_autofeed_settings(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_get_autofeed_settings_field_headers_async(): + client = AutofeedSettingsServiceAsyncClient( + 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 = autofeedsettings.GetAutofeedSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + await client.get_autofeed_settings(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_get_autofeed_settings_flattened(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_autofeed_settings( + 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_get_autofeed_settings_flattened_error(): + client = AutofeedSettingsServiceClient( + 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.get_autofeed_settings( + autofeedsettings.GetAutofeedSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_autofeed_settings_flattened_async(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_autofeed_settings( + 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_get_autofeed_settings_flattened_error_async(): + client = AutofeedSettingsServiceAsyncClient( + 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.get_autofeed_settings( + autofeedsettings.GetAutofeedSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + autofeedsettings.UpdateAutofeedSettingsRequest, + dict, +]) +def test_update_autofeed_settings(request_type, transport: str = 'grpc'): + client = AutofeedSettingsServiceClient( + 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.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + response = client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autofeedsettings.UpdateAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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 = autofeedsettings.UpdateAutofeedSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_autofeed_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autofeedsettings.UpdateAutofeedSettingsRequest( + ) + +def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.update_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc + request = {} + client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_autofeed_settings(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_update_autofeed_settings_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 = AutofeedSettingsServiceAsyncClient( + 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.update_autofeed_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_autofeed_settings] = mock_rpc + + request = {} + await client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_autofeed_settings(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_update_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.UpdateAutofeedSettingsRequest): + client = AutofeedSettingsServiceAsyncClient( + 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.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + response = await client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autofeedsettings.UpdateAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.asyncio +async def test_update_autofeed_settings_async_from_dict(): + await test_update_autofeed_settings_async(request_type=dict) + +def test_update_autofeed_settings_field_headers(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.UpdateAutofeedSettingsRequest() + + request.autofeed_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.update_autofeed_settings(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', + 'autofeed_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_autofeed_settings_field_headers_async(): + client = AutofeedSettingsServiceAsyncClient( + 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 = autofeedsettings.UpdateAutofeedSettingsRequest() + + request.autofeed_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + await client.update_autofeed_settings(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', + 'autofeed_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_autofeed_settings_flattened(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_autofeed_settings( + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].autofeed_settings + mock_val = autofeedsettings.AutofeedSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_autofeed_settings_flattened_error(): + client = AutofeedSettingsServiceClient( + 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.update_autofeed_settings( + autofeedsettings.UpdateAutofeedSettingsRequest(), + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_autofeed_settings_flattened_async(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_autofeed_settings( + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].autofeed_settings + mock_val = autofeedsettings.AutofeedSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_autofeed_settings_flattened_error_async(): + client = AutofeedSettingsServiceAsyncClient( + 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.update_autofeed_settings( + autofeedsettings.UpdateAutofeedSettingsRequest(), + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.get_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc + + request = {} + client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_autofeed_settings(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_get_autofeed_settings_rest_required_fields(request_type=autofeedsettings.GetAutofeedSettingsRequest): + transport_class = transports.AutofeedSettingsServiceRestTransport + + 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()).get_autofeed_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autofeed_settings._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 = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autofeedsettings.AutofeedSettings() + # 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 = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_autofeed_settings_rest_unset_required_fields(): + transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_autofeed_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_autofeed_settings_rest_flattened(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.AutofeedSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/autofeedSettings'} + + # 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 + # Convert return value to protobuf type + return_value = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(**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/accounts/v1/{name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) + + +def test_get_autofeed_settings_rest_flattened_error(transport: str = 'rest'): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_autofeed_settings( + autofeedsettings.GetAutofeedSettingsRequest(), + name='name_value', + ) + + +def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.update_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc + + request = {} + client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_autofeed_settings(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_update_autofeed_settings_rest_required_fields(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): + transport_class = transports.AutofeedSettingsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autofeedsettings.AutofeedSettings() + # 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': "patch", + '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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_autofeed_settings_rest_unset_required_fields(): + transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_autofeed_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("autofeedSettings", "updateMask", ))) + + +def test_update_autofeed_settings_rest_flattened(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.AutofeedSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(**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/accounts/v1/{autofeed_settings.name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) + + +def test_update_autofeed_settings_rest_flattened_error(transport: str = 'rest'): + client = AutofeedSettingsServiceClient( + 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.update_autofeed_settings( + autofeedsettings.UpdateAutofeedSettingsRequest(), + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + 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 = AutofeedSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AutofeedSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AutofeedSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + transports.AutofeedSettingsServiceRestTransport, +]) +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 = AutofeedSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AutofeedSettingsServiceClient( + 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_get_autofeed_settings_empty_call_grpc(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.get_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.GetAutofeedSettingsRequest() + + 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_update_autofeed_settings_empty_call_grpc(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.update_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AutofeedSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AutofeedSettingsServiceAsyncClient( + 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_get_autofeed_settings_empty_call_grpc_asyncio(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + await client.get_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.GetAutofeedSettingsRequest() + + 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_update_autofeed_settings_empty_call_grpc_asyncio(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + await client.update_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AutofeedSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_autofeed_settings_rest_bad_request(request_type=autofeedsettings.GetAutofeedSettingsRequest): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/autofeedSettings'} + 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.get_autofeed_settings(request) + + +@pytest.mark.parametrize("request_type", [ + autofeedsettings.GetAutofeedSettingsRequest, + dict, +]) +def test_get_autofeed_settings_rest_call_success(request_type): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/autofeedSettings'} + request = request_type(**request_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 = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + + # 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 = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_autofeed_settings_rest_interceptors(null_interceptor): + transport = transports.AutofeedSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), + ) + client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings") as post, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_get_autofeed_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autofeedsettings.GetAutofeedSettingsRequest.pb(autofeedsettings.GetAutofeedSettingsRequest()) + 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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) + req.return_value.content = return_value + + request = autofeedsettings.GetAutofeedSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autofeedsettings.AutofeedSettings() + post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata + + client.get_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_autofeed_settings_rest_bad_request(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + 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.update_autofeed_settings(request) + + +@pytest.mark.parametrize("request_type", [ + autofeedsettings.UpdateAutofeedSettingsRequest, + dict, +]) +def test_update_autofeed_settings_rest_call_success(request_type): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + request_init["autofeed_settings"] = {'name': 'accounts/sample1/autofeedSettings', 'enable_products': True, 'eligible': True} + # 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 = autofeedsettings.UpdateAutofeedSettingsRequest.meta.fields["autofeed_settings"] + + 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["autofeed_settings"].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["autofeed_settings"][field])): + del request_init["autofeed_settings"][field][i][subfield] + else: + del request_init["autofeed_settings"][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 = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + + # 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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_autofeed_settings_rest_interceptors(null_interceptor): + transport = transports.AutofeedSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), + ) + client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings") as post, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_update_autofeed_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autofeedsettings.UpdateAutofeedSettingsRequest.pb(autofeedsettings.UpdateAutofeedSettingsRequest()) + 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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) + req.return_value.content = return_value + + request = autofeedsettings.UpdateAutofeedSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autofeedsettings.AutofeedSettings() + post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata + + client.update_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AutofeedSettingsServiceClient( + 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_get_autofeed_settings_empty_call_rest(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + client.get_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.GetAutofeedSettingsRequest() + + 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_update_autofeed_settings_empty_call_rest(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + client.update_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AutofeedSettingsServiceGrpcTransport, + ) + +def test_autofeed_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AutofeedSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_autofeed_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AutofeedSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_autofeed_settings', + 'update_autofeed_settings', + ) + 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_autofeed_settings_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_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutofeedSettingsServiceTransport( + 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_autofeed_settings_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_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutofeedSettingsServiceTransport() + adc.assert_called_once() + + +def test_autofeed_settings_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) + AutofeedSettingsServiceClient() + 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.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + transports.AutofeedSettingsServiceRestTransport, + ], +) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, grpc_helpers), + (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +def test_autofeed_settings_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_autofeed_settings_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.AutofeedSettingsServiceRestTransport ( + 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_autofeed_settings_service_host_no_port(transport_name): + client = AutofeedSettingsServiceClient( + 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_autofeed_settings_service_host_with_port(transport_name): + client = AutofeedSettingsServiceClient( + 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_autofeed_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutofeedSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutofeedSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_autofeed_settings._session + session2 = client2.transport.get_autofeed_settings._session + assert session1 != session2 + session1 = client1.transport.update_autofeed_settings._session + session2 = client2.transport.update_autofeed_settings._session + assert session1 != session2 +def test_autofeed_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutofeedSettingsServiceGrpcTransport( + 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_autofeed_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutofeedSettingsServiceGrpcAsyncIOTransport( + 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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +def test_autofeed_settings_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_autofeed_settings_path(): + account = "squid" + expected = "accounts/{account}/autofeedSettings".format(account=account, ) + actual = AutofeedSettingsServiceClient.autofeed_settings_path(account) + assert expected == actual + + +def test_parse_autofeed_settings_path(): + expected = { + "account": "clam", + } + path = AutofeedSettingsServiceClient.autofeed_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_autofeed_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AutofeedSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AutofeedSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AutofeedSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AutofeedSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AutofeedSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AutofeedSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AutofeedSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AutofeedSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AutofeedSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AutofeedSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.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.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AutofeedSettingsServiceClient.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 = AutofeedSettingsServiceClient( + 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 = AutofeedSettingsServiceAsyncClient( + 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 = AutofeedSettingsServiceClient( + 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 = AutofeedSettingsServiceClient( + 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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py new file mode 100644 index 000000000000..e2dd6637a920 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py @@ -0,0 +1,2862 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import AutomaticImprovementsServiceClient +from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import transports +from google.shopping.merchant_accounts_v1.types import automaticimprovements +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 AutomaticImprovementsServiceClient._get_default_mtls_endpoint(None) is None + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, False) is None + assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AutomaticImprovementsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AutomaticImprovementsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AutomaticImprovementsServiceClient._get_universe_domain(None, None) == AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient(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 = AutomaticImprovementsServiceClient(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", [ + (AutomaticImprovementsServiceClient, "grpc"), + (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, "rest"), +]) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutomaticImprovementsServiceRestTransport, "rest"), +]) +def test_automatic_improvements_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", [ + (AutomaticImprovementsServiceClient, "grpc"), + (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, "rest"), +]) +def test_automatic_improvements_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_automatic_improvements_service_client_get_transport_class(): + transport = AutomaticImprovementsServiceClient.get_transport_class() + available_transports = [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceRestTransport, + ] + assert transport in available_transports + + transport = AutomaticImprovementsServiceClient.get_transport_class("grpc") + assert transport == transports.AutomaticImprovementsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +def test_automatic_improvements_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(AutomaticImprovementsServiceClient, '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(AutomaticImprovementsServiceClient, '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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "true"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "false"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "true"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_automatic_improvements_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", [ + AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceAsyncClient)) +def test_automatic_improvements_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", [ + AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +def test_automatic_improvements_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutomaticImprovementsServiceClient._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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), +]) +def test_automatic_improvements_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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", None), +]) +def test_automatic_improvements_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_automatic_improvements_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AutomaticImprovementsServiceClient( + 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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_automatic_improvements_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", [ + automaticimprovements.GetAutomaticImprovementsRequest, + dict, +]) +def test_get_automatic_improvements(request_type, transport: str = 'grpc'): + client = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements( + name='name_value', + ) + response = client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = automaticimprovements.GetAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.GetAutomaticImprovementsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_automatic_improvements(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == automaticimprovements.GetAutomaticImprovementsRequest( + name='name_value', + ) + +def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc + request = {} + client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_automatic_improvements(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_get_automatic_improvements_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 = AutomaticImprovementsServiceAsyncClient( + 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.get_automatic_improvements in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_automatic_improvements] = mock_rpc + + request = {} + await client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_automatic_improvements(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_get_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.GetAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceAsyncClient( + 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.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + response = await client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = automaticimprovements.GetAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_automatic_improvements_async_from_dict(): + await test_get_automatic_improvements_async(request_type=dict) + +def test_get_automatic_improvements_field_headers(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.GetAutomaticImprovementsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.get_automatic_improvements(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_get_automatic_improvements_field_headers_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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 = automaticimprovements.GetAutomaticImprovementsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + await client.get_automatic_improvements(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_get_automatic_improvements_flattened(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_automatic_improvements( + 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_get_automatic_improvements_flattened_error(): + client = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements( + automaticimprovements.GetAutomaticImprovementsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_automatic_improvements_flattened_async(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_automatic_improvements( + 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_get_automatic_improvements_flattened_error_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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.get_automatic_improvements( + automaticimprovements.GetAutomaticImprovementsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + automaticimprovements.UpdateAutomaticImprovementsRequest, + dict, +]) +def test_update_automatic_improvements(request_type, transport: str = 'grpc'): + client = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements( + name='name_value', + ) + response = client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = automaticimprovements.UpdateAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.UpdateAutomaticImprovementsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_automatic_improvements(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == automaticimprovements.UpdateAutomaticImprovementsRequest( + ) + +def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc + request = {} + client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_automatic_improvements(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_update_automatic_improvements_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 = AutomaticImprovementsServiceAsyncClient( + 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.update_automatic_improvements in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_automatic_improvements] = mock_rpc + + request = {} + await client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_automatic_improvements(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_update_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceAsyncClient( + 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.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + response = await client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = automaticimprovements.UpdateAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_automatic_improvements_async_from_dict(): + await test_update_automatic_improvements_async(request_type=dict) + +def test_update_automatic_improvements_field_headers(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.UpdateAutomaticImprovementsRequest() + + request.automatic_improvements.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.update_automatic_improvements(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', + 'automatic_improvements.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_automatic_improvements_field_headers_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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 = automaticimprovements.UpdateAutomaticImprovementsRequest() + + request.automatic_improvements.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + await client.update_automatic_improvements(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', + 'automatic_improvements.name=name_value', + ) in kw['metadata'] + + +def test_update_automatic_improvements_flattened(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_automatic_improvements( + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].automatic_improvements + mock_val = automaticimprovements.AutomaticImprovements(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_automatic_improvements_flattened_error(): + client = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements( + automaticimprovements.UpdateAutomaticImprovementsRequest(), + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_automatic_improvements_flattened_async(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_automatic_improvements( + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].automatic_improvements + mock_val = automaticimprovements.AutomaticImprovements(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_automatic_improvements_flattened_error_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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.update_automatic_improvements( + automaticimprovements.UpdateAutomaticImprovementsRequest(), + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc + + request = {} + client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_automatic_improvements(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_get_automatic_improvements_rest_required_fields(request_type=automaticimprovements.GetAutomaticImprovementsRequest): + transport_class = transports.AutomaticImprovementsServiceRestTransport + + 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()).get_automatic_improvements._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_automatic_improvements._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 = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = automaticimprovements.AutomaticImprovements() + # 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 = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_automatic_improvements_rest_unset_required_fields(): + transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_automatic_improvements._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_automatic_improvements_rest_flattened(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.AutomaticImprovements() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/automaticImprovements'} + + # 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 + # Convert return value to protobuf type + return_value = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(**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/accounts/v1/{name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) + + +def test_get_automatic_improvements_rest_flattened_error(transport: str = 'rest'): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_automatic_improvements( + automaticimprovements.GetAutomaticImprovementsRequest(), + name='name_value', + ) + + +def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc + + request = {} + client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_automatic_improvements(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_update_automatic_improvements_rest_required_fields(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): + transport_class = transports.AutomaticImprovementsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = automaticimprovements.AutomaticImprovements() + # 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': "patch", + '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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_automatic_improvements_rest_unset_required_fields(): + transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_automatic_improvements._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("automaticImprovements", "updateMask", ))) + + +def test_update_automatic_improvements_rest_flattened(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.AutomaticImprovements() + + # get arguments that satisfy an http rule for this method + sample_request = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + + # get truthy value for each flattened field + mock_args = dict( + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(**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/accounts/v1/{automatic_improvements.name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) + + +def test_update_automatic_improvements_rest_flattened_error(transport: str = 'rest'): + client = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements( + automaticimprovements.UpdateAutomaticImprovementsRequest(), + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + 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 = AutomaticImprovementsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AutomaticImprovementsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AutomaticImprovementsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + transports.AutomaticImprovementsServiceRestTransport, +]) +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 = AutomaticImprovementsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AutomaticImprovementsServiceClient( + 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_get_automatic_improvements_empty_call_grpc(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.get_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.GetAutomaticImprovementsRequest() + + 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_update_automatic_improvements_empty_call_grpc(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.update_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AutomaticImprovementsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AutomaticImprovementsServiceAsyncClient( + 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_get_automatic_improvements_empty_call_grpc_asyncio(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + await client.get_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.GetAutomaticImprovementsRequest() + + 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_update_automatic_improvements_empty_call_grpc_asyncio(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + await client.update_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AutomaticImprovementsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_automatic_improvements_rest_bad_request(request_type=automaticimprovements.GetAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/automaticImprovements'} + 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.get_automatic_improvements(request) + + +@pytest.mark.parametrize("request_type", [ + automaticimprovements.GetAutomaticImprovementsRequest, + dict, +]) +def test_get_automatic_improvements_rest_call_success(request_type): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/automaticImprovements'} + request = request_type(**request_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 = automaticimprovements.AutomaticImprovements( + name='name_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 = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_automatic_improvements_rest_interceptors(null_interceptor): + transport = transports.AutomaticImprovementsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), + ) + client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements") as post, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_get_automatic_improvements") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = automaticimprovements.GetAutomaticImprovementsRequest.pb(automaticimprovements.GetAutomaticImprovementsRequest()) + 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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) + req.return_value.content = return_value + + request = automaticimprovements.GetAutomaticImprovementsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = automaticimprovements.AutomaticImprovements() + post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata + + client.get_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_automatic_improvements_rest_bad_request(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + 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.update_automatic_improvements(request) + + +@pytest.mark.parametrize("request_type", [ + automaticimprovements.UpdateAutomaticImprovementsRequest, + dict, +]) +def test_update_automatic_improvements_rest_call_success(request_type): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + request_init["automatic_improvements"] = {'name': 'accounts/sample1/automaticImprovements', 'item_updates': {'account_item_updates_settings': {'allow_price_updates': True, 'allow_availability_updates': True, 'allow_strict_availability_updates': True, 'allow_condition_updates': True}, 'effective_allow_price_updates': True, 'effective_allow_availability_updates': True, 'effective_allow_strict_availability_updates': True, 'effective_allow_condition_updates': True}, 'image_improvements': {'account_image_improvements_settings': {'allow_automatic_image_improvements': True}, 'effective_allow_automatic_image_improvements': True}, 'shipping_improvements': {'allow_shipping_improvements': True}} + # 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 = automaticimprovements.UpdateAutomaticImprovementsRequest.meta.fields["automatic_improvements"] + + 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["automatic_improvements"].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["automatic_improvements"][field])): + del request_init["automatic_improvements"][field][i][subfield] + else: + del request_init["automatic_improvements"][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 = automaticimprovements.AutomaticImprovements( + name='name_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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_automatic_improvements_rest_interceptors(null_interceptor): + transport = transports.AutomaticImprovementsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), + ) + client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements") as post, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_update_automatic_improvements") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = automaticimprovements.UpdateAutomaticImprovementsRequest.pb(automaticimprovements.UpdateAutomaticImprovementsRequest()) + 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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) + req.return_value.content = return_value + + request = automaticimprovements.UpdateAutomaticImprovementsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = automaticimprovements.AutomaticImprovements() + post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata + + client.update_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AutomaticImprovementsServiceClient( + 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_get_automatic_improvements_empty_call_rest(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + client.get_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.GetAutomaticImprovementsRequest() + + 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_update_automatic_improvements_empty_call_rest(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + client.update_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AutomaticImprovementsServiceGrpcTransport, + ) + +def test_automatic_improvements_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AutomaticImprovementsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_automatic_improvements_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AutomaticImprovementsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_automatic_improvements', + 'update_automatic_improvements', + ) + 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_automatic_improvements_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_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutomaticImprovementsServiceTransport( + 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_automatic_improvements_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_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutomaticImprovementsServiceTransport() + adc.assert_called_once() + + +def test_automatic_improvements_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) + AutomaticImprovementsServiceClient() + 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.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + ], +) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + transports.AutomaticImprovementsServiceRestTransport, + ], +) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, grpc_helpers), + (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +def test_automatic_improvements_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_automatic_improvements_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.AutomaticImprovementsServiceRestTransport ( + 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_automatic_improvements_service_host_no_port(transport_name): + client = AutomaticImprovementsServiceClient( + 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_automatic_improvements_service_host_with_port(transport_name): + client = AutomaticImprovementsServiceClient( + 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_automatic_improvements_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutomaticImprovementsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutomaticImprovementsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_automatic_improvements._session + session2 = client2.transport.get_automatic_improvements._session + assert session1 != session2 + session1 = client1.transport.update_automatic_improvements._session + session2 = client2.transport.update_automatic_improvements._session + assert session1 != session2 +def test_automatic_improvements_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + 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_automatic_improvements_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutomaticImprovementsServiceGrpcAsyncIOTransport( + 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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +def test_automatic_improvements_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_automatic_improvements_path(): + account = "squid" + expected = "accounts/{account}/automaticImprovements".format(account=account, ) + actual = AutomaticImprovementsServiceClient.automatic_improvements_path(account) + assert expected == actual + + +def test_parse_automatic_improvements_path(): + expected = { + "account": "clam", + } + path = AutomaticImprovementsServiceClient.automatic_improvements_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_automatic_improvements_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AutomaticImprovementsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AutomaticImprovementsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AutomaticImprovementsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AutomaticImprovementsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AutomaticImprovementsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AutomaticImprovementsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AutomaticImprovementsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AutomaticImprovementsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AutomaticImprovementsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AutomaticImprovementsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.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.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AutomaticImprovementsServiceClient.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 = AutomaticImprovementsServiceClient( + 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 = AutomaticImprovementsServiceAsyncClient( + 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 = AutomaticImprovementsServiceClient( + 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 = AutomaticImprovementsServiceClient( + 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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py new file mode 100644 index 000000000000..0cb00207a4ae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py @@ -0,0 +1,2876 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.business_identity_service import BusinessIdentityServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.business_identity_service import BusinessIdentityServiceClient +from google.shopping.merchant_accounts_v1.services.business_identity_service import transports +from google.shopping.merchant_accounts_v1.types import businessidentity +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 BusinessIdentityServiceClient._get_default_mtls_endpoint(None) is None + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, False) is None + assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert BusinessIdentityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert BusinessIdentityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert BusinessIdentityServiceClient._get_universe_domain(None, None) == BusinessIdentityServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient(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 = BusinessIdentityServiceClient(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", [ + (BusinessIdentityServiceClient, "grpc"), + (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), + (BusinessIdentityServiceClient, "rest"), +]) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, "grpc"), + (transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BusinessIdentityServiceRestTransport, "rest"), +]) +def test_business_identity_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", [ + (BusinessIdentityServiceClient, "grpc"), + (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), + (BusinessIdentityServiceClient, "rest"), +]) +def test_business_identity_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_business_identity_service_client_get_transport_class(): + transport = BusinessIdentityServiceClient.get_transport_class() + available_transports = [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceRestTransport, + ] + assert transport in available_transports + + transport = BusinessIdentityServiceClient.get_transport_class("grpc") + assert transport == transports.BusinessIdentityServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), +]) +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +def test_business_identity_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(BusinessIdentityServiceClient, '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(BusinessIdentityServiceClient, '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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "true"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "false"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "true"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_business_identity_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", [ + BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient +]) +@mock.patch.object(BusinessIdentityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceAsyncClient)) +def test_business_identity_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", [ + BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient +]) +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +def test_business_identity_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessIdentityServiceClient._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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), +]) +def test_business_identity_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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", None), +]) +def test_business_identity_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_business_identity_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = BusinessIdentityServiceClient( + 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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_business_identity_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", [ + businessidentity.GetBusinessIdentityRequest, + dict, +]) +def test_get_business_identity(request_type, transport: str = 'grpc'): + client = BusinessIdentityServiceClient( + 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.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + response = client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessidentity.GetBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +def test_get_business_identity_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 = BusinessIdentityServiceClient( + 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 = businessidentity.GetBusinessIdentityRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_business_identity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessidentity.GetBusinessIdentityRequest( + name='name_value', + ) + +def test_get_business_identity_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 = BusinessIdentityServiceClient( + 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.get_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc + request = {} + client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_identity(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_get_business_identity_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 = BusinessIdentityServiceAsyncClient( + 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.get_business_identity in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_business_identity] = mock_rpc + + request = {} + await client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_business_identity(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_get_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.GetBusinessIdentityRequest): + client = BusinessIdentityServiceAsyncClient( + 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.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + response = await client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessidentity.GetBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.asyncio +async def test_get_business_identity_async_from_dict(): + await test_get_business_identity_async(request_type=dict) + +def test_get_business_identity_field_headers(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.GetBusinessIdentityRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.get_business_identity(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_get_business_identity_field_headers_async(): + client = BusinessIdentityServiceAsyncClient( + 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 = businessidentity.GetBusinessIdentityRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + await client.get_business_identity(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_get_business_identity_flattened(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_business_identity( + 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_get_business_identity_flattened_error(): + client = BusinessIdentityServiceClient( + 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.get_business_identity( + businessidentity.GetBusinessIdentityRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_business_identity_flattened_async(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_business_identity( + 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_get_business_identity_flattened_error_async(): + client = BusinessIdentityServiceAsyncClient( + 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.get_business_identity( + businessidentity.GetBusinessIdentityRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + businessidentity.UpdateBusinessIdentityRequest, + dict, +]) +def test_update_business_identity(request_type, transport: str = 'grpc'): + client = BusinessIdentityServiceClient( + 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.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + response = client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessidentity.UpdateBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +def test_update_business_identity_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 = BusinessIdentityServiceClient( + 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 = businessidentity.UpdateBusinessIdentityRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_business_identity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessidentity.UpdateBusinessIdentityRequest( + ) + +def test_update_business_identity_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 = BusinessIdentityServiceClient( + 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.update_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc + request = {} + client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_identity(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_update_business_identity_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 = BusinessIdentityServiceAsyncClient( + 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.update_business_identity in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_business_identity] = mock_rpc + + request = {} + await client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_business_identity(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_update_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.UpdateBusinessIdentityRequest): + client = BusinessIdentityServiceAsyncClient( + 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.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + response = await client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessidentity.UpdateBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.asyncio +async def test_update_business_identity_async_from_dict(): + await test_update_business_identity_async(request_type=dict) + +def test_update_business_identity_field_headers(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.UpdateBusinessIdentityRequest() + + request.business_identity.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.update_business_identity(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', + 'business_identity.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_business_identity_field_headers_async(): + client = BusinessIdentityServiceAsyncClient( + 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 = businessidentity.UpdateBusinessIdentityRequest() + + request.business_identity.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + await client.update_business_identity(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', + 'business_identity.name=name_value', + ) in kw['metadata'] + + +def test_update_business_identity_flattened(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_business_identity( + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_identity + mock_val = businessidentity.BusinessIdentity(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_business_identity_flattened_error(): + client = BusinessIdentityServiceClient( + 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.update_business_identity( + businessidentity.UpdateBusinessIdentityRequest(), + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_business_identity_flattened_async(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_business_identity( + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_identity + mock_val = businessidentity.BusinessIdentity(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_business_identity_flattened_error_async(): + client = BusinessIdentityServiceAsyncClient( + 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.update_business_identity( + businessidentity.UpdateBusinessIdentityRequest(), + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_business_identity_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 = BusinessIdentityServiceClient( + 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.get_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc + + request = {} + client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_identity(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_get_business_identity_rest_required_fields(request_type=businessidentity.GetBusinessIdentityRequest): + transport_class = transports.BusinessIdentityServiceRestTransport + + 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()).get_business_identity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_identity._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 = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessidentity.BusinessIdentity() + # 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 = businessidentity.BusinessIdentity.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.get_business_identity(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_business_identity_rest_unset_required_fields(): + transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_business_identity._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_business_identity_rest_flattened(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.BusinessIdentity() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/businessIdentity'} + + # 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 + # Convert return value to protobuf type + return_value = businessidentity.BusinessIdentity.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.get_business_identity(**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/accounts/v1/{name=accounts/*/businessIdentity}" % client.transport._host, args[1]) + + +def test_get_business_identity_rest_flattened_error(transport: str = 'rest'): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_business_identity( + businessidentity.GetBusinessIdentityRequest(), + name='name_value', + ) + + +def test_update_business_identity_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 = BusinessIdentityServiceClient( + 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.update_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc + + request = {} + client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_identity(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_update_business_identity_rest_required_fields(request_type=businessidentity.UpdateBusinessIdentityRequest): + transport_class = transports.BusinessIdentityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessidentity.BusinessIdentity() + # 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': "patch", + '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 = businessidentity.BusinessIdentity.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.update_business_identity(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_business_identity_rest_unset_required_fields(): + transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_business_identity._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("businessIdentity", ))) + + +def test_update_business_identity_rest_flattened(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.BusinessIdentity() + + # get arguments that satisfy an http rule for this method + sample_request = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + + # get truthy value for each flattened field + mock_args = dict( + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = businessidentity.BusinessIdentity.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.update_business_identity(**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/accounts/v1/{business_identity.name=accounts/*/businessIdentity}" % client.transport._host, args[1]) + + +def test_update_business_identity_rest_flattened_error(transport: str = 'rest'): + client = BusinessIdentityServiceClient( + 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.update_business_identity( + businessidentity.UpdateBusinessIdentityRequest(), + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + 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 = BusinessIdentityServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BusinessIdentityServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BusinessIdentityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + transports.BusinessIdentityServiceRestTransport, +]) +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 = BusinessIdentityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BusinessIdentityServiceClient( + 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_get_business_identity_empty_call_grpc(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.get_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.GetBusinessIdentityRequest() + + 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_update_business_identity_empty_call_grpc(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.update_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.UpdateBusinessIdentityRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BusinessIdentityServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BusinessIdentityServiceAsyncClient( + 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_get_business_identity_empty_call_grpc_asyncio(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + await client.get_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.GetBusinessIdentityRequest() + + 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_update_business_identity_empty_call_grpc_asyncio(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + await client.update_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.UpdateBusinessIdentityRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BusinessIdentityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_business_identity_rest_bad_request(request_type=businessidentity.GetBusinessIdentityRequest): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessIdentity'} + 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.get_business_identity(request) + + +@pytest.mark.parametrize("request_type", [ + businessidentity.GetBusinessIdentityRequest, + dict, +]) +def test_get_business_identity_rest_call_success(request_type): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessIdentity'} + request = request_type(**request_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 = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + + # 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 = businessidentity.BusinessIdentity.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.get_business_identity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_business_identity_rest_interceptors(null_interceptor): + transport = transports.BusinessIdentityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), + ) + client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_get_business_identity") as post, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_get_business_identity_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_get_business_identity") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessidentity.GetBusinessIdentityRequest.pb(businessidentity.GetBusinessIdentityRequest()) + 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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) + req.return_value.content = return_value + + request = businessidentity.GetBusinessIdentityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessidentity.BusinessIdentity() + post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata + + client.get_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_business_identity_rest_bad_request(request_type=businessidentity.UpdateBusinessIdentityRequest): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + 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.update_business_identity(request) + + +@pytest.mark.parametrize("request_type", [ + businessidentity.UpdateBusinessIdentityRequest, + dict, +]) +def test_update_business_identity_rest_call_success(request_type): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + request_init["business_identity"] = {'name': 'accounts/sample1/businessIdentity', 'promotions_consent': 1, 'black_owned': {'identity_declaration': 1}, 'women_owned': {}, 'veteran_owned': {}, 'latino_owned': {}, 'small_business': {}} + # 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 = businessidentity.UpdateBusinessIdentityRequest.meta.fields["business_identity"] + + 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["business_identity"].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["business_identity"][field])): + del request_init["business_identity"][field][i][subfield] + else: + del request_init["business_identity"][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 = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + + # 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 = businessidentity.BusinessIdentity.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.update_business_identity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_business_identity_rest_interceptors(null_interceptor): + transport = transports.BusinessIdentityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), + ) + client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_update_business_identity") as post, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_update_business_identity_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_update_business_identity") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessidentity.UpdateBusinessIdentityRequest.pb(businessidentity.UpdateBusinessIdentityRequest()) + 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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) + req.return_value.content = return_value + + request = businessidentity.UpdateBusinessIdentityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessidentity.BusinessIdentity() + post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata + + client.update_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = BusinessIdentityServiceClient( + 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_get_business_identity_empty_call_rest(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + client.get_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.GetBusinessIdentityRequest() + + 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_update_business_identity_empty_call_rest(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + client.update_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.UpdateBusinessIdentityRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BusinessIdentityServiceGrpcTransport, + ) + +def test_business_identity_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BusinessIdentityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_business_identity_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.BusinessIdentityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_business_identity', + 'update_business_identity', + ) + 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_business_identity_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_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessIdentityServiceTransport( + 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_business_identity_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_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessIdentityServiceTransport() + adc.assert_called_once() + + +def test_business_identity_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) + BusinessIdentityServiceClient() + 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.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + ], +) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + transports.BusinessIdentityServiceRestTransport, + ], +) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, grpc_helpers), + (transports.BusinessIdentityServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +def test_business_identity_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_business_identity_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.BusinessIdentityServiceRestTransport ( + 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_business_identity_service_host_no_port(transport_name): + client = BusinessIdentityServiceClient( + 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_business_identity_service_host_with_port(transport_name): + client = BusinessIdentityServiceClient( + 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_business_identity_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BusinessIdentityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BusinessIdentityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_business_identity._session + session2 = client2.transport.get_business_identity._session + assert session1 != session2 + session1 = client1.transport.update_business_identity._session + session2 = client2.transport.update_business_identity._session + assert session1 != session2 +def test_business_identity_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessIdentityServiceGrpcTransport( + 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_business_identity_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessIdentityServiceGrpcAsyncIOTransport( + 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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +def test_business_identity_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_business_identity_path(): + account = "squid" + expected = "accounts/{account}/businessIdentity".format(account=account, ) + actual = BusinessIdentityServiceClient.business_identity_path(account) + assert expected == actual + + +def test_parse_business_identity_path(): + expected = { + "account": "clam", + } + path = BusinessIdentityServiceClient.business_identity_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_business_identity_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = BusinessIdentityServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = BusinessIdentityServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = BusinessIdentityServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = BusinessIdentityServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = BusinessIdentityServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = BusinessIdentityServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = BusinessIdentityServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = BusinessIdentityServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = BusinessIdentityServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = BusinessIdentityServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.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.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = BusinessIdentityServiceClient.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 = BusinessIdentityServiceClient( + 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 = BusinessIdentityServiceAsyncClient( + 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 = BusinessIdentityServiceClient( + 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 = BusinessIdentityServiceClient( + 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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py new file mode 100644 index 000000000000..708c9ea01bb2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py @@ -0,0 +1,2894 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.business_info_service import BusinessInfoServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.business_info_service import BusinessInfoServiceClient +from google.shopping.merchant_accounts_v1.services.business_info_service import transports +from google.shopping.merchant_accounts_v1.types import businessinfo +from google.shopping.merchant_accounts_v1.types import customerservice +from google.shopping.merchant_accounts_v1.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_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 BusinessInfoServiceClient._get_default_mtls_endpoint(None) is None + assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert BusinessInfoServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + BusinessInfoServiceClient._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 BusinessInfoServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessInfoServiceClient._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 BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, False) is None + assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert BusinessInfoServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessInfoServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert BusinessInfoServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert BusinessInfoServiceClient._get_universe_domain(None, None) == BusinessInfoServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + BusinessInfoServiceClient._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 = BusinessInfoServiceClient(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 = BusinessInfoServiceClient(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", [ + (BusinessInfoServiceClient, "grpc"), + (BusinessInfoServiceAsyncClient, "grpc_asyncio"), + (BusinessInfoServiceClient, "rest"), +]) +def test_business_info_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.BusinessInfoServiceGrpcTransport, "grpc"), + (transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BusinessInfoServiceRestTransport, "rest"), +]) +def test_business_info_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", [ + (BusinessInfoServiceClient, "grpc"), + (BusinessInfoServiceAsyncClient, "grpc_asyncio"), + (BusinessInfoServiceClient, "rest"), +]) +def test_business_info_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_business_info_service_client_get_transport_class(): + transport = BusinessInfoServiceClient.get_transport_class() + available_transports = [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceRestTransport, + ] + assert transport in available_transports + + transport = BusinessInfoServiceClient.get_transport_class("grpc") + assert transport == transports.BusinessInfoServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), +]) +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +def test_business_info_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(BusinessInfoServiceClient, '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(BusinessInfoServiceClient, '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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "true"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "false"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "true"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_business_info_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", [ + BusinessInfoServiceClient, BusinessInfoServiceAsyncClient +]) +@mock.patch.object(BusinessInfoServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceAsyncClient)) +def test_business_info_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", [ + BusinessInfoServiceClient, BusinessInfoServiceAsyncClient +]) +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +def test_business_info_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessInfoServiceClient._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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), +]) +def test_business_info_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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", None), +]) +def test_business_info_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_business_info_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = BusinessInfoServiceClient( + 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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_business_info_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", [ + businessinfo.GetBusinessInfoRequest, + dict, +]) +def test_get_business_info(request_type, transport: str = 'grpc'): + client = BusinessInfoServiceClient( + 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.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + ) + response = client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessinfo.GetBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +def test_get_business_info_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 = BusinessInfoServiceClient( + 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 = businessinfo.GetBusinessInfoRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_business_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessinfo.GetBusinessInfoRequest( + name='name_value', + ) + +def test_get_business_info_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 = BusinessInfoServiceClient( + 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.get_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc + request = {} + client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_info(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_get_business_info_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 = BusinessInfoServiceAsyncClient( + 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.get_business_info in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_business_info] = mock_rpc + + request = {} + await client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_business_info(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_get_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.GetBusinessInfoRequest): + client = BusinessInfoServiceAsyncClient( + 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.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + response = await client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessinfo.GetBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.asyncio +async def test_get_business_info_async_from_dict(): + await test_get_business_info_async(request_type=dict) + +def test_get_business_info_field_headers(): + client = BusinessInfoServiceClient( + 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 = businessinfo.GetBusinessInfoRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.get_business_info(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_get_business_info_field_headers_async(): + client = BusinessInfoServiceAsyncClient( + 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 = businessinfo.GetBusinessInfoRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + await client.get_business_info(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_get_business_info_flattened(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_business_info( + 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_get_business_info_flattened_error(): + client = BusinessInfoServiceClient( + 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.get_business_info( + businessinfo.GetBusinessInfoRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_business_info_flattened_async(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_business_info( + 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_get_business_info_flattened_error_async(): + client = BusinessInfoServiceAsyncClient( + 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.get_business_info( + businessinfo.GetBusinessInfoRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + businessinfo.UpdateBusinessInfoRequest, + dict, +]) +def test_update_business_info(request_type, transport: str = 'grpc'): + client = BusinessInfoServiceClient( + 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.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + ) + response = client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessinfo.UpdateBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +def test_update_business_info_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 = BusinessInfoServiceClient( + 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 = businessinfo.UpdateBusinessInfoRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_business_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessinfo.UpdateBusinessInfoRequest( + ) + +def test_update_business_info_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 = BusinessInfoServiceClient( + 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.update_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc + request = {} + client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_info(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_update_business_info_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 = BusinessInfoServiceAsyncClient( + 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.update_business_info in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_business_info] = mock_rpc + + request = {} + await client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_business_info(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_update_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.UpdateBusinessInfoRequest): + client = BusinessInfoServiceAsyncClient( + 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.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + response = await client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessinfo.UpdateBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.asyncio +async def test_update_business_info_async_from_dict(): + await test_update_business_info_async(request_type=dict) + +def test_update_business_info_field_headers(): + client = BusinessInfoServiceClient( + 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 = businessinfo.UpdateBusinessInfoRequest() + + request.business_info.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.update_business_info(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', + 'business_info.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_business_info_field_headers_async(): + client = BusinessInfoServiceAsyncClient( + 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 = businessinfo.UpdateBusinessInfoRequest() + + request.business_info.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + await client.update_business_info(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', + 'business_info.name=name_value', + ) in kw['metadata'] + + +def test_update_business_info_flattened(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_business_info( + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_info + mock_val = businessinfo.BusinessInfo(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_business_info_flattened_error(): + client = BusinessInfoServiceClient( + 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.update_business_info( + businessinfo.UpdateBusinessInfoRequest(), + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_business_info_flattened_async(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_business_info( + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_info + mock_val = businessinfo.BusinessInfo(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_business_info_flattened_error_async(): + client = BusinessInfoServiceAsyncClient( + 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.update_business_info( + businessinfo.UpdateBusinessInfoRequest(), + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_business_info_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 = BusinessInfoServiceClient( + 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.get_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc + + request = {} + client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_info(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_get_business_info_rest_required_fields(request_type=businessinfo.GetBusinessInfoRequest): + transport_class = transports.BusinessInfoServiceRestTransport + + 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()).get_business_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_info._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 = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessinfo.BusinessInfo() + # 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 = businessinfo.BusinessInfo.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.get_business_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_business_info_rest_unset_required_fields(): + transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_business_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_business_info_rest_flattened(): + client = BusinessInfoServiceClient( + 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 = businessinfo.BusinessInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/businessInfo'} + + # 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 + # Convert return value to protobuf type + return_value = businessinfo.BusinessInfo.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.get_business_info(**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/accounts/v1/{name=accounts/*/businessInfo}" % client.transport._host, args[1]) + + +def test_get_business_info_rest_flattened_error(transport: str = 'rest'): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_business_info( + businessinfo.GetBusinessInfoRequest(), + name='name_value', + ) + + +def test_update_business_info_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 = BusinessInfoServiceClient( + 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.update_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc + + request = {} + client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_info(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_update_business_info_rest_required_fields(request_type=businessinfo.UpdateBusinessInfoRequest): + transport_class = transports.BusinessInfoServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessinfo.BusinessInfo() + # 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': "patch", + '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 = businessinfo.BusinessInfo.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.update_business_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_business_info_rest_unset_required_fields(): + transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_business_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("businessInfo", ))) + + +def test_update_business_info_rest_flattened(): + client = BusinessInfoServiceClient( + 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 = businessinfo.BusinessInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + + # get truthy value for each flattened field + mock_args = dict( + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = businessinfo.BusinessInfo.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.update_business_info(**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/accounts/v1/{business_info.name=accounts/*/businessInfo}" % client.transport._host, args[1]) + + +def test_update_business_info_rest_flattened_error(transport: str = 'rest'): + client = BusinessInfoServiceClient( + 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.update_business_info( + businessinfo.UpdateBusinessInfoRequest(), + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + 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 = BusinessInfoServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BusinessInfoServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BusinessInfoServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + transports.BusinessInfoServiceRestTransport, +]) +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 = BusinessInfoServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BusinessInfoServiceClient( + 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_get_business_info_empty_call_grpc(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.get_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.GetBusinessInfoRequest() + + 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_update_business_info_empty_call_grpc(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.update_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.UpdateBusinessInfoRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BusinessInfoServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BusinessInfoServiceAsyncClient( + 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_get_business_info_empty_call_grpc_asyncio(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + await client.get_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.GetBusinessInfoRequest() + + 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_update_business_info_empty_call_grpc_asyncio(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + await client.update_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.UpdateBusinessInfoRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BusinessInfoServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_business_info_rest_bad_request(request_type=businessinfo.GetBusinessInfoRequest): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessInfo'} + 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.get_business_info(request) + + +@pytest.mark.parametrize("request_type", [ + businessinfo.GetBusinessInfoRequest, + dict, +]) +def test_get_business_info_rest_call_success(request_type): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessInfo'} + request = request_type(**request_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 = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_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 = businessinfo.BusinessInfo.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.get_business_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_business_info_rest_interceptors(null_interceptor): + transport = transports.BusinessInfoServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), + ) + client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_get_business_info") as post, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_get_business_info_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_get_business_info") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessinfo.GetBusinessInfoRequest.pb(businessinfo.GetBusinessInfoRequest()) + 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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) + req.return_value.content = return_value + + request = businessinfo.GetBusinessInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessinfo.BusinessInfo() + post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata + + client.get_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_business_info_rest_bad_request(request_type=businessinfo.UpdateBusinessInfoRequest): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + 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.update_business_info(request) + + +@pytest.mark.parametrize("request_type", [ + businessinfo.UpdateBusinessInfoRequest, + dict, +]) +def test_update_business_info_rest_call_success(request_type): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + request_init["business_info"] = {'name': 'accounts/sample1/businessInfo', 'address': {'revision': 879, 'region_code': 'region_code_value', 'language_code': 'language_code_value', 'postal_code': 'postal_code_value', 'sorting_code': 'sorting_code_value', 'administrative_area': 'administrative_area_value', 'locality': 'locality_value', 'sublocality': 'sublocality_value', 'address_lines': ['address_lines_value1', 'address_lines_value2'], 'recipients': ['recipients_value1', 'recipients_value2'], 'organization': 'organization_value'}, 'phone': {'e164_number': 'e164_number_value', 'short_code': {'region_code': 'region_code_value', 'number': 'number_value'}, 'extension': 'extension_value'}, 'phone_verification_state': 1, 'customer_service': {'uri': 'uri_value', 'email': 'email_value', 'phone': {}}, 'korean_business_registration_number': 'korean_business_registration_number_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 = businessinfo.UpdateBusinessInfoRequest.meta.fields["business_info"] + + 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["business_info"].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["business_info"][field])): + del request_init["business_info"][field][i][subfield] + else: + del request_init["business_info"][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 = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_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 = businessinfo.BusinessInfo.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.update_business_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_business_info_rest_interceptors(null_interceptor): + transport = transports.BusinessInfoServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), + ) + client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_update_business_info") as post, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_update_business_info_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_update_business_info") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessinfo.UpdateBusinessInfoRequest.pb(businessinfo.UpdateBusinessInfoRequest()) + 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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) + req.return_value.content = return_value + + request = businessinfo.UpdateBusinessInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessinfo.BusinessInfo() + post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata + + client.update_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = BusinessInfoServiceClient( + 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_get_business_info_empty_call_rest(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + client.get_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.GetBusinessInfoRequest() + + 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_update_business_info_empty_call_rest(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + client.update_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.UpdateBusinessInfoRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BusinessInfoServiceGrpcTransport, + ) + +def test_business_info_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BusinessInfoServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_business_info_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.BusinessInfoServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_business_info', + 'update_business_info', + ) + 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_business_info_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_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessInfoServiceTransport( + 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_business_info_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_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessInfoServiceTransport() + adc.assert_called_once() + + +def test_business_info_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) + BusinessInfoServiceClient() + 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.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + ], +) +def test_business_info_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.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + transports.BusinessInfoServiceRestTransport, + ], +) +def test_business_info_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.BusinessInfoServiceGrpcTransport, grpc_helpers), + (transports.BusinessInfoServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +def test_business_info_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_business_info_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.BusinessInfoServiceRestTransport ( + 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_business_info_service_host_no_port(transport_name): + client = BusinessInfoServiceClient( + 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_business_info_service_host_with_port(transport_name): + client = BusinessInfoServiceClient( + 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_business_info_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BusinessInfoServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BusinessInfoServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_business_info._session + session2 = client2.transport.get_business_info._session + assert session1 != session2 + session1 = client1.transport.update_business_info._session + session2 = client2.transport.update_business_info._session + assert session1 != session2 +def test_business_info_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessInfoServiceGrpcTransport( + 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_business_info_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessInfoServiceGrpcAsyncIOTransport( + 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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +def test_business_info_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_business_info_path(): + account = "squid" + expected = "accounts/{account}/businessInfo".format(account=account, ) + actual = BusinessInfoServiceClient.business_info_path(account) + assert expected == actual + + +def test_parse_business_info_path(): + expected = { + "account": "clam", + } + path = BusinessInfoServiceClient.business_info_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_business_info_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = BusinessInfoServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = BusinessInfoServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = BusinessInfoServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = BusinessInfoServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = BusinessInfoServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = BusinessInfoServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = BusinessInfoServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = BusinessInfoServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = BusinessInfoServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = BusinessInfoServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.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.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = BusinessInfoServiceClient.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 = BusinessInfoServiceClient( + 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 = BusinessInfoServiceAsyncClient( + 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 = BusinessInfoServiceClient( + 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 = BusinessInfoServiceClient( + 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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py new file mode 100644 index 000000000000..2e57c5160d4d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py @@ -0,0 +1,4334 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.checkout_settings_service import CheckoutSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.checkout_settings_service import CheckoutSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.checkout_settings_service import transports +from google.shopping.merchant_accounts_v1.types import checkoutsettings +from google.shopping.type.types import types +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 CheckoutSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, False) is None + assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert CheckoutSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert CheckoutSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert CheckoutSettingsServiceClient._get_universe_domain(None, None) == CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient(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 = CheckoutSettingsServiceClient(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", [ + (CheckoutSettingsServiceClient, "grpc"), + (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), + (CheckoutSettingsServiceClient, "rest"), +]) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, "grpc"), + (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CheckoutSettingsServiceRestTransport, "rest"), +]) +def test_checkout_settings_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", [ + (CheckoutSettingsServiceClient, "grpc"), + (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), + (CheckoutSettingsServiceClient, "rest"), +]) +def test_checkout_settings_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_checkout_settings_service_client_get_transport_class(): + transport = CheckoutSettingsServiceClient.get_transport_class() + available_transports = [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = CheckoutSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.CheckoutSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +def test_checkout_settings_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(CheckoutSettingsServiceClient, '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(CheckoutSettingsServiceClient, '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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "true"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "false"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "true"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_checkout_settings_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", [ + CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient +]) +@mock.patch.object(CheckoutSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceAsyncClient)) +def test_checkout_settings_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", [ + CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient +]) +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +def test_checkout_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = CheckoutSettingsServiceClient._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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), +]) +def test_checkout_settings_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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", None), +]) +def test_checkout_settings_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_checkout_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CheckoutSettingsServiceClient( + 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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_checkout_settings_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", [ + checkoutsettings.GetCheckoutSettingsRequest, + dict, +]) +def test_get_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + response = client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.GetCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.GetCheckoutSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.GetCheckoutSettingsRequest( + name='name_value', + ) + +def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.get_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc + request = {} + client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_checkout_settings(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_get_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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.get_checkout_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_checkout_settings] = mock_rpc + + request = {} + await client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_checkout_settings(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_get_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.GetCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + response = await client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.GetCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.asyncio +async def test_get_checkout_settings_async_from_dict(): + await test_get_checkout_settings_async(request_type=dict) + +def test_get_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.GetCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.get_checkout_settings(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_get_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.GetCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + await client.get_checkout_settings(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_get_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_checkout_settings( + 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_get_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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.get_checkout_settings( + checkoutsettings.GetCheckoutSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_checkout_settings( + 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_get_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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.get_checkout_settings( + checkoutsettings.GetCheckoutSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.CreateCheckoutSettingsRequest, + dict, +]) +def test_create_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + response = client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.CreateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CreateCheckoutSettingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.CreateCheckoutSettingsRequest( + parent='parent_value', + ) + +def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.create_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc + request = {} + client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_checkout_settings(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_create_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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.create_checkout_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_checkout_settings] = mock_rpc + + request = {} + await client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_checkout_settings(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_create_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.CreateCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + response = await client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.CreateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.asyncio +async def test_create_checkout_settings_async_from_dict(): + await test_create_checkout_settings_async(request_type=dict) + +def test_create_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CreateCheckoutSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.create_checkout_settings(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_create_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.CreateCheckoutSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + await client.create_checkout_settings(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_create_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_checkout_settings( + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + + +def test_create_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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.create_checkout_settings( + checkoutsettings.CreateCheckoutSettingsRequest(), + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_checkout_settings( + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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.create_checkout_settings( + checkoutsettings.CreateCheckoutSettingsRequest(), + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.UpdateCheckoutSettingsRequest, + dict, +]) +def test_update_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + response = client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.UpdateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.UpdateCheckoutSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.UpdateCheckoutSettingsRequest( + ) + +def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.update_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc + request = {} + client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_checkout_settings(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_update_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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.update_checkout_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_checkout_settings] = mock_rpc + + request = {} + await client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_checkout_settings(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_update_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.UpdateCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + response = await client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.UpdateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.asyncio +async def test_update_checkout_settings_async_from_dict(): + await test_update_checkout_settings_async(request_type=dict) + +def test_update_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.UpdateCheckoutSettingsRequest() + + request.checkout_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.update_checkout_settings(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', + 'checkout_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.UpdateCheckoutSettingsRequest() + + request.checkout_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + await client.update_checkout_settings(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', + 'checkout_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_checkout_settings( + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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.update_checkout_settings( + checkoutsettings.UpdateCheckoutSettingsRequest(), + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_checkout_settings( + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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.update_checkout_settings( + checkoutsettings.UpdateCheckoutSettingsRequest(), + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.DeleteCheckoutSettingsRequest, + dict, +]) +def test_delete_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.DeleteCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.DeleteCheckoutSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.DeleteCheckoutSettingsRequest( + name='name_value', + ) + +def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( + 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_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_checkout_settings] = mock_rpc + request = {} + client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_checkout_settings(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_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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_checkout_settings 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_checkout_settings] = mock_rpc + + request = {} + await client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_checkout_settings(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_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.DeleteCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.DeleteCheckoutSettingsRequest() + 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_checkout_settings_async_from_dict(): + await test_delete_checkout_settings_async(request_type=dict) + +def test_delete_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.DeleteCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value = None + client.delete_checkout_settings(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_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.DeleteCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_checkout_settings(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_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__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_checkout_settings( + 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_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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_checkout_settings( + checkoutsettings.DeleteCheckoutSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__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_checkout_settings( + 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_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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_checkout_settings( + checkoutsettings.DeleteCheckoutSettingsRequest(), + name='name_value', + ) + + +def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.get_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc + + request = {} + client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_checkout_settings(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_get_checkout_settings_rest_required_fields(request_type=checkoutsettings.GetCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + 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()).get_checkout_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_checkout_settings._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 = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = checkoutsettings.CheckoutSettings() + # 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 = checkoutsettings.CheckoutSettings.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.get_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CheckoutSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + + # 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 + # Convert return value to protobuf type + return_value = checkoutsettings.CheckoutSettings.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.get_checkout_settings(**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/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + + +def test_get_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_checkout_settings( + checkoutsettings.GetCheckoutSettingsRequest(), + name='name_value', + ) + + +def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.create_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc + + request = {} + client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_checkout_settings(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_create_checkout_settings_rest_required_fields(request_type=checkoutsettings.CreateCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + 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()).create_checkout_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_checkout_settings._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 = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = checkoutsettings.CheckoutSettings() + # 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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "checkoutSettings", ))) + + +def test_create_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CheckoutSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/programs/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(**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/accounts/v1/{parent=accounts/*/programs/*}/checkoutSettings" % client.transport._host, args[1]) + + +def test_create_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + 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.create_checkout_settings( + checkoutsettings.CreateCheckoutSettingsRequest(), + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + ) + + +def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.update_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc + + request = {} + client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_checkout_settings(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_update_checkout_settings_rest_required_fields(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = checkoutsettings.CheckoutSettings() + # 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': "patch", + '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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("checkoutSettings", "updateMask", ))) + + +def test_update_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CheckoutSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(**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/accounts/v1/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + + +def test_update_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + 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.update_checkout_settings( + checkoutsettings.UpdateCheckoutSettingsRequest(), + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( + 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_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_checkout_settings] = mock_rpc + + request = {} + client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_checkout_settings(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_checkout_settings_rest_required_fields(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + 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_checkout_settings._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_checkout_settings._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 = CheckoutSettingsServiceClient( + 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_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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/programs/sample2/checkoutSettings'} + + # 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_checkout_settings(**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/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + + +def test_delete_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + 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_checkout_settings( + checkoutsettings.DeleteCheckoutSettingsRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + 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 = CheckoutSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CheckoutSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CheckoutSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + transports.CheckoutSettingsServiceRestTransport, +]) +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 = CheckoutSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CheckoutSettingsServiceClient( + 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_get_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.get_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.GetCheckoutSettingsRequest() + + 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_create_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.create_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.CreateCheckoutSettingsRequest() + + 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_update_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.update_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() + + 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_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value = None + client.delete_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CheckoutSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + 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_get_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + await client.get_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.GetCheckoutSettingsRequest() + + 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_create_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + await client.create_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.CreateCheckoutSettingsRequest() + + 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_update_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + await client.update_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() + + 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_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CheckoutSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_checkout_settings_rest_bad_request(request_type=checkoutsettings.GetCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + 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.get_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.GetCheckoutSettingsRequest, + dict, +]) +def test_get_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request = request_type(**request_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 = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + + # 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 = checkoutsettings.CheckoutSettings.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.get_checkout_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings") as post, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_get_checkout_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = checkoutsettings.GetCheckoutSettingsRequest.pb(checkoutsettings.GetCheckoutSettingsRequest()) + 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + req.return_value.content = return_value + + request = checkoutsettings.GetCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checkoutsettings.CheckoutSettings() + post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata + + client.get_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_checkout_settings_rest_bad_request(request_type=checkoutsettings.CreateCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/programs/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.create_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.CreateCheckoutSettingsRequest, + dict, +]) +def test_create_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/programs/sample2'} + request_init["checkout_settings"] = {'name': 'name_value', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 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 = checkoutsettings.CreateCheckoutSettingsRequest.meta.fields["checkout_settings"] + + 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["checkout_settings"].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["checkout_settings"][field])): + del request_init["checkout_settings"][field][i][subfield] + else: + del request_init["checkout_settings"][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 = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + + # 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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings") as post, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_create_checkout_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = checkoutsettings.CreateCheckoutSettingsRequest.pb(checkoutsettings.CreateCheckoutSettingsRequest()) + 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + req.return_value.content = return_value + + request = checkoutsettings.CreateCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checkoutsettings.CheckoutSettings() + post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata + + client.create_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_checkout_settings_rest_bad_request(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + 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.update_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.UpdateCheckoutSettingsRequest, + dict, +]) +def test_update_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + request_init["checkout_settings"] = {'name': 'accounts/sample1/programs/sample2/checkoutSettings', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 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 = checkoutsettings.UpdateCheckoutSettingsRequest.meta.fields["checkout_settings"] + + 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["checkout_settings"].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["checkout_settings"][field])): + del request_init["checkout_settings"][field][i][subfield] + else: + del request_init["checkout_settings"][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 = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + + # 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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings") as post, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_update_checkout_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = checkoutsettings.UpdateCheckoutSettingsRequest.pb(checkoutsettings.UpdateCheckoutSettingsRequest()) + 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + req.return_value.content = return_value + + request = checkoutsettings.UpdateCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checkoutsettings.CheckoutSettings() + post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata + + client.update_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_checkout_settings_rest_bad_request(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + 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_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.DeleteCheckoutSettingsRequest, + dict, +]) +def test_delete_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request = request_type(**request_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_checkout_settings(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_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "pre_delete_checkout_settings") as pre: + pre.assert_not_called() + pb_message = checkoutsettings.DeleteCheckoutSettingsRequest.pb(checkoutsettings.DeleteCheckoutSettingsRequest()) + 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 = checkoutsettings.DeleteCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = CheckoutSettingsServiceClient( + 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_get_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + client.get_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.GetCheckoutSettingsRequest() + + 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_create_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + client.create_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.CreateCheckoutSettingsRequest() + + 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_update_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + client.update_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() + + 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_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + client.delete_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CheckoutSettingsServiceGrpcTransport, + ) + +def test_checkout_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CheckoutSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_checkout_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CheckoutSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_checkout_settings', + 'create_checkout_settings', + 'update_checkout_settings', + 'delete_checkout_settings', + ) + 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_checkout_settings_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_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CheckoutSettingsServiceTransport( + 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_checkout_settings_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_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CheckoutSettingsServiceTransport() + adc.assert_called_once() + + +def test_checkout_settings_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) + CheckoutSettingsServiceClient() + 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.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + transports.CheckoutSettingsServiceRestTransport, + ], +) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, grpc_helpers), + (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +def test_checkout_settings_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_checkout_settings_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.CheckoutSettingsServiceRestTransport ( + 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_checkout_settings_service_host_no_port(transport_name): + client = CheckoutSettingsServiceClient( + 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_checkout_settings_service_host_with_port(transport_name): + client = CheckoutSettingsServiceClient( + 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_checkout_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CheckoutSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CheckoutSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_checkout_settings._session + session2 = client2.transport.get_checkout_settings._session + assert session1 != session2 + session1 = client1.transport.create_checkout_settings._session + session2 = client2.transport.create_checkout_settings._session + assert session1 != session2 + session1 = client1.transport.update_checkout_settings._session + session2 = client2.transport.update_checkout_settings._session + assert session1 != session2 + session1 = client1.transport.delete_checkout_settings._session + session2 = client2.transport.delete_checkout_settings._session + assert session1 != session2 +def test_checkout_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CheckoutSettingsServiceGrpcTransport( + 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_checkout_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CheckoutSettingsServiceGrpcAsyncIOTransport( + 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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +def test_checkout_settings_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_checkout_settings_path(): + account = "squid" + program = "clam" + expected = "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) + actual = CheckoutSettingsServiceClient.checkout_settings_path(account, program) + assert expected == actual + + +def test_parse_checkout_settings_path(): + expected = { + "account": "whelk", + "program": "octopus", + } + path = CheckoutSettingsServiceClient.checkout_settings_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_checkout_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CheckoutSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = CheckoutSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = CheckoutSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = CheckoutSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CheckoutSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = CheckoutSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = CheckoutSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = CheckoutSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CheckoutSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = CheckoutSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.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.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CheckoutSettingsServiceClient.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 = CheckoutSettingsServiceClient( + 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 = CheckoutSettingsServiceAsyncClient( + 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 = CheckoutSettingsServiceClient( + 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 = CheckoutSettingsServiceClient( + 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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py new file mode 100644 index 000000000000..cd958ad19b4c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py @@ -0,0 +1,3166 @@ +# -*- 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.shopping.merchant_accounts_v1.services.developer_registration_service import DeveloperRegistrationServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.developer_registration_service import DeveloperRegistrationServiceClient +from google.shopping.merchant_accounts_v1.services.developer_registration_service import transports +from google.shopping.merchant_accounts_v1.types import developerregistration +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 DeveloperRegistrationServiceClient._get_default_mtls_endpoint(None) is None + assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert DeveloperRegistrationServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._get_client_cert_source(None, False) is None + assert DeveloperRegistrationServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert DeveloperRegistrationServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) +@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + default_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert DeveloperRegistrationServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert DeveloperRegistrationServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, default_universe, "always") == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + assert DeveloperRegistrationServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert DeveloperRegistrationServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert DeveloperRegistrationServiceClient._get_universe_domain(None, None) == DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + DeveloperRegistrationServiceClient._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 = DeveloperRegistrationServiceClient(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 = DeveloperRegistrationServiceClient(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", [ + (DeveloperRegistrationServiceClient, "grpc"), + (DeveloperRegistrationServiceAsyncClient, "grpc_asyncio"), + (DeveloperRegistrationServiceClient, "rest"), +]) +def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, "grpc"), + (transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DeveloperRegistrationServiceRestTransport, "rest"), +]) +def test_developer_registration_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", [ + (DeveloperRegistrationServiceClient, "grpc"), + (DeveloperRegistrationServiceAsyncClient, "grpc_asyncio"), + (DeveloperRegistrationServiceClient, "rest"), +]) +def test_developer_registration_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_developer_registration_service_client_get_transport_class(): + transport = DeveloperRegistrationServiceClient.get_transport_class() + available_transports = [ + transports.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceRestTransport, + ] + assert transport in available_transports + + transport = DeveloperRegistrationServiceClient.get_transport_class("grpc") + assert transport == transports.DeveloperRegistrationServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc"), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest"), +]) +@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) +@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) +def test_developer_registration_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(DeveloperRegistrationServiceClient, '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(DeveloperRegistrationServiceClient, '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", [ + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", "true"), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", "false"), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest", "true"), + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) +@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_developer_registration_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", [ + DeveloperRegistrationServiceClient, DeveloperRegistrationServiceAsyncClient +]) +@mock.patch.object(DeveloperRegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeveloperRegistrationServiceClient)) +@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeveloperRegistrationServiceAsyncClient)) +def test_developer_registration_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", [ + DeveloperRegistrationServiceClient, DeveloperRegistrationServiceAsyncClient +]) +@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) +@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) +def test_developer_registration_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + default_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = DeveloperRegistrationServiceClient._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", [ + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc"), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest"), +]) +def test_developer_registration_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", [ + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", grpc_helpers), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest", None), +]) +def test_developer_registration_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_developer_registration_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DeveloperRegistrationServiceClient( + 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", [ + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", grpc_helpers), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_developer_registration_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", [ + developerregistration.RegisterGcpRequest, + dict, +]) +def test_register_gcp(request_type, transport: str = 'grpc'): + client = DeveloperRegistrationServiceClient( + 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.register_gcp), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_value'], + ) + response = client.register_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developerregistration.RegisterGcpRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developerregistration.DeveloperRegistration) + assert response.name == 'name_value' + assert response.gcp_ids == ['gcp_ids_value'] + + +def test_register_gcp_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 = DeveloperRegistrationServiceClient( + 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 = developerregistration.RegisterGcpRequest( + name='name_value', + developer_email='developer_email_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.register_gcp), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.register_gcp(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == developerregistration.RegisterGcpRequest( + name='name_value', + developer_email='developer_email_value', + ) + +def test_register_gcp_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 = DeveloperRegistrationServiceClient( + 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.register_gcp in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.register_gcp] = mock_rpc + request = {} + client.register_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.register_gcp(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_register_gcp_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 = DeveloperRegistrationServiceAsyncClient( + 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.register_gcp 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.register_gcp] = mock_rpc + + request = {} + await client.register_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.register_gcp(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_register_gcp_async(transport: str = 'grpc_asyncio', request_type=developerregistration.RegisterGcpRequest): + client = DeveloperRegistrationServiceAsyncClient( + 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.register_gcp), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_value'], + )) + response = await client.register_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developerregistration.RegisterGcpRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developerregistration.DeveloperRegistration) + assert response.name == 'name_value' + assert response.gcp_ids == ['gcp_ids_value'] + + +@pytest.mark.asyncio +async def test_register_gcp_async_from_dict(): + await test_register_gcp_async(request_type=dict) + +def test_register_gcp_field_headers(): + client = DeveloperRegistrationServiceClient( + 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 = developerregistration.RegisterGcpRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.register_gcp), + '__call__') as call: + call.return_value = developerregistration.DeveloperRegistration() + client.register_gcp(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_register_gcp_field_headers_async(): + client = DeveloperRegistrationServiceAsyncClient( + 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 = developerregistration.RegisterGcpRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.register_gcp), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration()) + await client.register_gcp(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'] + + +@pytest.mark.parametrize("request_type", [ + developerregistration.GetDeveloperRegistrationRequest, + dict, +]) +def test_get_developer_registration(request_type, transport: str = 'grpc'): + client = DeveloperRegistrationServiceClient( + 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.get_developer_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_value'], + ) + response = client.get_developer_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developerregistration.GetDeveloperRegistrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developerregistration.DeveloperRegistration) + assert response.name == 'name_value' + assert response.gcp_ids == ['gcp_ids_value'] + + +def test_get_developer_registration_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 = DeveloperRegistrationServiceClient( + 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 = developerregistration.GetDeveloperRegistrationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_developer_registration(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == developerregistration.GetDeveloperRegistrationRequest( + name='name_value', + ) + +def test_get_developer_registration_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 = DeveloperRegistrationServiceClient( + 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.get_developer_registration in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_developer_registration] = mock_rpc + request = {} + client.get_developer_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_developer_registration(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_get_developer_registration_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 = DeveloperRegistrationServiceAsyncClient( + 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.get_developer_registration in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_developer_registration] = mock_rpc + + request = {} + await client.get_developer_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_developer_registration(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_get_developer_registration_async(transport: str = 'grpc_asyncio', request_type=developerregistration.GetDeveloperRegistrationRequest): + client = DeveloperRegistrationServiceAsyncClient( + 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.get_developer_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_value'], + )) + response = await client.get_developer_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developerregistration.GetDeveloperRegistrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developerregistration.DeveloperRegistration) + assert response.name == 'name_value' + assert response.gcp_ids == ['gcp_ids_value'] + + +@pytest.mark.asyncio +async def test_get_developer_registration_async_from_dict(): + await test_get_developer_registration_async(request_type=dict) + +def test_get_developer_registration_field_headers(): + client = DeveloperRegistrationServiceClient( + 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 = developerregistration.GetDeveloperRegistrationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + call.return_value = developerregistration.DeveloperRegistration() + client.get_developer_registration(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_get_developer_registration_field_headers_async(): + client = DeveloperRegistrationServiceAsyncClient( + 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 = developerregistration.GetDeveloperRegistrationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration()) + await client.get_developer_registration(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_get_developer_registration_flattened(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = developerregistration.DeveloperRegistration() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_developer_registration( + 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_get_developer_registration_flattened_error(): + client = DeveloperRegistrationServiceClient( + 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.get_developer_registration( + developerregistration.GetDeveloperRegistrationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_developer_registration_flattened_async(): + client = DeveloperRegistrationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = developerregistration.DeveloperRegistration() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_developer_registration( + 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_get_developer_registration_flattened_error_async(): + client = DeveloperRegistrationServiceAsyncClient( + 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.get_developer_registration( + developerregistration.GetDeveloperRegistrationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + developerregistration.UnregisterGcpRequest, + dict, +]) +def test_unregister_gcp(request_type, transport: str = 'grpc'): + client = DeveloperRegistrationServiceClient( + 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.unregister_gcp), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.unregister_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developerregistration.UnregisterGcpRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_unregister_gcp_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 = DeveloperRegistrationServiceClient( + 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 = developerregistration.UnregisterGcpRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unregister_gcp), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.unregister_gcp(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == developerregistration.UnregisterGcpRequest( + name='name_value', + ) + +def test_unregister_gcp_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 = DeveloperRegistrationServiceClient( + 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.unregister_gcp in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unregister_gcp] = mock_rpc + request = {} + client.unregister_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.unregister_gcp(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_unregister_gcp_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 = DeveloperRegistrationServiceAsyncClient( + 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.unregister_gcp 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.unregister_gcp] = mock_rpc + + request = {} + await client.unregister_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.unregister_gcp(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_unregister_gcp_async(transport: str = 'grpc_asyncio', request_type=developerregistration.UnregisterGcpRequest): + client = DeveloperRegistrationServiceAsyncClient( + 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.unregister_gcp), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.unregister_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developerregistration.UnregisterGcpRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_unregister_gcp_async_from_dict(): + await test_unregister_gcp_async(request_type=dict) + +def test_unregister_gcp_field_headers(): + client = DeveloperRegistrationServiceClient( + 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 = developerregistration.UnregisterGcpRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unregister_gcp), + '__call__') as call: + call.return_value = None + client.unregister_gcp(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_unregister_gcp_field_headers_async(): + client = DeveloperRegistrationServiceAsyncClient( + 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 = developerregistration.UnregisterGcpRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unregister_gcp), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.unregister_gcp(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_register_gcp_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 = DeveloperRegistrationServiceClient( + 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.register_gcp in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.register_gcp] = mock_rpc + + request = {} + client.register_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.register_gcp(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_register_gcp_rest_required_fields(request_type=developerregistration.RegisterGcpRequest): + transport_class = transports.DeveloperRegistrationServiceRestTransport + + 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()).register_gcp._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()).register_gcp._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 = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developerregistration.DeveloperRegistration() + # 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 = developerregistration.DeveloperRegistration.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.register_gcp(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_register_gcp_rest_unset_required_fields(): + transport = transports.DeveloperRegistrationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.register_gcp._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_developer_registration_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 = DeveloperRegistrationServiceClient( + 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.get_developer_registration in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_developer_registration] = mock_rpc + + request = {} + client.get_developer_registration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_developer_registration(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_get_developer_registration_rest_required_fields(request_type=developerregistration.GetDeveloperRegistrationRequest): + transport_class = transports.DeveloperRegistrationServiceRestTransport + + 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()).get_developer_registration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_developer_registration._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 = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developerregistration.DeveloperRegistration() + # 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 = developerregistration.DeveloperRegistration.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.get_developer_registration(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_developer_registration_rest_unset_required_fields(): + transport = transports.DeveloperRegistrationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_developer_registration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_developer_registration_rest_flattened(): + client = DeveloperRegistrationServiceClient( + 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 = developerregistration.DeveloperRegistration() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/developerRegistration'} + + # 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 + # Convert return value to protobuf type + return_value = developerregistration.DeveloperRegistration.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.get_developer_registration(**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/accounts/v1/{name=accounts/*/developerRegistration}" % client.transport._host, args[1]) + + +def test_get_developer_registration_rest_flattened_error(transport: str = 'rest'): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_developer_registration( + developerregistration.GetDeveloperRegistrationRequest(), + name='name_value', + ) + + +def test_unregister_gcp_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 = DeveloperRegistrationServiceClient( + 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.unregister_gcp in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unregister_gcp] = mock_rpc + + request = {} + client.unregister_gcp(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.unregister_gcp(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_unregister_gcp_rest_required_fields(request_type=developerregistration.UnregisterGcpRequest): + transport_class = transports.DeveloperRegistrationServiceRestTransport + + 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()).unregister_gcp._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()).unregister_gcp._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 = DeveloperRegistrationServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = 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.unregister_gcp(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_unregister_gcp_rest_unset_required_fields(): + transport = transports.DeveloperRegistrationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.unregister_gcp._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeveloperRegistrationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DeveloperRegistrationServiceClient( + 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 = DeveloperRegistrationServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeveloperRegistrationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DeveloperRegistrationServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DeveloperRegistrationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + transports.DeveloperRegistrationServiceRestTransport, +]) +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 = DeveloperRegistrationServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DeveloperRegistrationServiceClient( + 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_register_gcp_empty_call_grpc(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.register_gcp), + '__call__') as call: + call.return_value = developerregistration.DeveloperRegistration() + client.register_gcp(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.RegisterGcpRequest() + + 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_get_developer_registration_empty_call_grpc(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + call.return_value = developerregistration.DeveloperRegistration() + client.get_developer_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.GetDeveloperRegistrationRequest() + + 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_unregister_gcp_empty_call_grpc(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unregister_gcp), + '__call__') as call: + call.return_value = None + client.unregister_gcp(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.UnregisterGcpRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = DeveloperRegistrationServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DeveloperRegistrationServiceAsyncClient( + 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_register_gcp_empty_call_grpc_asyncio(): + client = DeveloperRegistrationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.register_gcp), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_value'], + )) + await client.register_gcp(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.RegisterGcpRequest() + + 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_get_developer_registration_empty_call_grpc_asyncio(): + client = DeveloperRegistrationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_value'], + )) + await client.get_developer_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.GetDeveloperRegistrationRequest() + + 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_unregister_gcp_empty_call_grpc_asyncio(): + client = DeveloperRegistrationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unregister_gcp), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.unregister_gcp(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.UnregisterGcpRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = DeveloperRegistrationServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_register_gcp_rest_bad_request(request_type=developerregistration.RegisterGcpRequest): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/developerRegistration'} + 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.register_gcp(request) + + +@pytest.mark.parametrize("request_type", [ + developerregistration.RegisterGcpRequest, + dict, +]) +def test_register_gcp_rest_call_success(request_type): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/developerRegistration'} + request = request_type(**request_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 = developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_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 = developerregistration.DeveloperRegistration.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.register_gcp(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, developerregistration.DeveloperRegistration) + assert response.name == 'name_value' + assert response.gcp_ids == ['gcp_ids_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_register_gcp_rest_interceptors(null_interceptor): + transport = transports.DeveloperRegistrationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeveloperRegistrationServiceRestInterceptor(), + ) + client = DeveloperRegistrationServiceClient(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.DeveloperRegistrationServiceRestInterceptor, "post_register_gcp") as post, \ + mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "post_register_gcp_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "pre_register_gcp") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developerregistration.RegisterGcpRequest.pb(developerregistration.RegisterGcpRequest()) + 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 = developerregistration.DeveloperRegistration.to_json(developerregistration.DeveloperRegistration()) + req.return_value.content = return_value + + request = developerregistration.RegisterGcpRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developerregistration.DeveloperRegistration() + post_with_metadata.return_value = developerregistration.DeveloperRegistration(), metadata + + client.register_gcp(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_developer_registration_rest_bad_request(request_type=developerregistration.GetDeveloperRegistrationRequest): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/developerRegistration'} + 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.get_developer_registration(request) + + +@pytest.mark.parametrize("request_type", [ + developerregistration.GetDeveloperRegistrationRequest, + dict, +]) +def test_get_developer_registration_rest_call_success(request_type): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/developerRegistration'} + request = request_type(**request_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 = developerregistration.DeveloperRegistration( + name='name_value', + gcp_ids=['gcp_ids_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 = developerregistration.DeveloperRegistration.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.get_developer_registration(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, developerregistration.DeveloperRegistration) + assert response.name == 'name_value' + assert response.gcp_ids == ['gcp_ids_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_developer_registration_rest_interceptors(null_interceptor): + transport = transports.DeveloperRegistrationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeveloperRegistrationServiceRestInterceptor(), + ) + client = DeveloperRegistrationServiceClient(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.DeveloperRegistrationServiceRestInterceptor, "post_get_developer_registration") as post, \ + mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "post_get_developer_registration_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "pre_get_developer_registration") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developerregistration.GetDeveloperRegistrationRequest.pb(developerregistration.GetDeveloperRegistrationRequest()) + 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 = developerregistration.DeveloperRegistration.to_json(developerregistration.DeveloperRegistration()) + req.return_value.content = return_value + + request = developerregistration.GetDeveloperRegistrationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developerregistration.DeveloperRegistration() + post_with_metadata.return_value = developerregistration.DeveloperRegistration(), metadata + + client.get_developer_registration(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_unregister_gcp_rest_bad_request(request_type=developerregistration.UnregisterGcpRequest): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/developerRegistration'} + 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.unregister_gcp(request) + + +@pytest.mark.parametrize("request_type", [ + developerregistration.UnregisterGcpRequest, + dict, +]) +def test_unregister_gcp_rest_call_success(request_type): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/developerRegistration'} + request = request_type(**request_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.unregister_gcp(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_unregister_gcp_rest_interceptors(null_interceptor): + transport = transports.DeveloperRegistrationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DeveloperRegistrationServiceRestInterceptor(), + ) + client = DeveloperRegistrationServiceClient(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.DeveloperRegistrationServiceRestInterceptor, "pre_unregister_gcp") as pre: + pre.assert_not_called() + pb_message = developerregistration.UnregisterGcpRequest.pb(developerregistration.UnregisterGcpRequest()) + 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 = developerregistration.UnregisterGcpRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.unregister_gcp(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = DeveloperRegistrationServiceClient( + 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_register_gcp_empty_call_rest(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.register_gcp), + '__call__') as call: + client.register_gcp(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.RegisterGcpRequest() + + 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_get_developer_registration_empty_call_rest(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_developer_registration), + '__call__') as call: + client.get_developer_registration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.GetDeveloperRegistrationRequest() + + 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_unregister_gcp_empty_call_rest(): + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unregister_gcp), + '__call__') as call: + client.unregister_gcp(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developerregistration.UnregisterGcpRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DeveloperRegistrationServiceGrpcTransport, + ) + +def test_developer_registration_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DeveloperRegistrationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_developer_registration_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DeveloperRegistrationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'register_gcp', + 'get_developer_registration', + 'unregister_gcp', + ) + 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_developer_registration_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_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeveloperRegistrationServiceTransport( + 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_developer_registration_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_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DeveloperRegistrationServiceTransport() + adc.assert_called_once() + + +def test_developer_registration_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) + DeveloperRegistrationServiceClient() + 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.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + transports.DeveloperRegistrationServiceRestTransport, + ], +) +def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, grpc_helpers), + (transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport]) +def test_developer_registration_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_developer_registration_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.DeveloperRegistrationServiceRestTransport ( + 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_developer_registration_service_host_no_port(transport_name): + client = DeveloperRegistrationServiceClient( + 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_developer_registration_service_host_with_port(transport_name): + client = DeveloperRegistrationServiceClient( + 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_developer_registration_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DeveloperRegistrationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DeveloperRegistrationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.register_gcp._session + session2 = client2.transport.register_gcp._session + assert session1 != session2 + session1 = client1.transport.get_developer_registration._session + session2 = client2.transport.get_developer_registration._session + assert session1 != session2 + session1 = client1.transport.unregister_gcp._session + session2 = client2.transport.unregister_gcp._session + assert session1 != session2 +def test_developer_registration_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeveloperRegistrationServiceGrpcTransport( + 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_developer_registration_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DeveloperRegistrationServiceGrpcAsyncIOTransport( + 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.DeveloperRegistrationServiceGrpcTransport, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport]) +def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport]) +def test_developer_registration_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_developer_registration_path(): + account = "squid" + expected = "accounts/{account}/developerRegistration".format(account=account, ) + actual = DeveloperRegistrationServiceClient.developer_registration_path(account) + assert expected == actual + + +def test_parse_developer_registration_path(): + expected = { + "account": "clam", + } + path = DeveloperRegistrationServiceClient.developer_registration_path(**expected) + + # Check that the path construction is reversible. + actual = DeveloperRegistrationServiceClient.parse_developer_registration_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DeveloperRegistrationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = DeveloperRegistrationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DeveloperRegistrationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = DeveloperRegistrationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = DeveloperRegistrationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DeveloperRegistrationServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DeveloperRegistrationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = DeveloperRegistrationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DeveloperRegistrationServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = DeveloperRegistrationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = DeveloperRegistrationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DeveloperRegistrationServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DeveloperRegistrationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = DeveloperRegistrationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DeveloperRegistrationServiceClient.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.DeveloperRegistrationServiceTransport, '_prep_wrapped_messages') as prep: + client = DeveloperRegistrationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DeveloperRegistrationServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DeveloperRegistrationServiceClient.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 = DeveloperRegistrationServiceClient( + 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 = DeveloperRegistrationServiceAsyncClient( + 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 = DeveloperRegistrationServiceClient( + 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 = DeveloperRegistrationServiceClient( + 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", [ + (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport), + (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py new file mode 100644 index 000000000000..94095b92c5dc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py @@ -0,0 +1,2878 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.email_preferences_service import EmailPreferencesServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.email_preferences_service import EmailPreferencesServiceClient +from google.shopping.merchant_accounts_v1.services.email_preferences_service import transports +from google.shopping.merchant_accounts_v1.types import emailpreferences +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 EmailPreferencesServiceClient._get_default_mtls_endpoint(None) is None + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, False) is None + assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EmailPreferencesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EmailPreferencesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EmailPreferencesServiceClient._get_universe_domain(None, None) == EmailPreferencesServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient(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 = EmailPreferencesServiceClient(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", [ + (EmailPreferencesServiceClient, "grpc"), + (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), + (EmailPreferencesServiceClient, "rest"), +]) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, "grpc"), + (transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EmailPreferencesServiceRestTransport, "rest"), +]) +def test_email_preferences_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", [ + (EmailPreferencesServiceClient, "grpc"), + (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), + (EmailPreferencesServiceClient, "rest"), +]) +def test_email_preferences_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_email_preferences_service_client_get_transport_class(): + transport = EmailPreferencesServiceClient.get_transport_class() + available_transports = [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceRestTransport, + ] + assert transport in available_transports + + transport = EmailPreferencesServiceClient.get_transport_class("grpc") + assert transport == transports.EmailPreferencesServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), +]) +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +def test_email_preferences_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(EmailPreferencesServiceClient, '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(EmailPreferencesServiceClient, '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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "true"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "false"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "true"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_email_preferences_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", [ + EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient +]) +@mock.patch.object(EmailPreferencesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceAsyncClient)) +def test_email_preferences_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", [ + EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient +]) +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +def test_email_preferences_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EmailPreferencesServiceClient._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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), +]) +def test_email_preferences_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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", None), +]) +def test_email_preferences_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_email_preferences_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EmailPreferencesServiceClient( + 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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_email_preferences_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", [ + emailpreferences.GetEmailPreferencesRequest, + dict, +]) +def test_get_email_preferences(request_type, transport: str = 'grpc'): + client = EmailPreferencesServiceClient( + 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.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + response = client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = emailpreferences.GetEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +def test_get_email_preferences_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 = EmailPreferencesServiceClient( + 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 = emailpreferences.GetEmailPreferencesRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_email_preferences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == emailpreferences.GetEmailPreferencesRequest( + name='name_value', + ) + +def test_get_email_preferences_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 = EmailPreferencesServiceClient( + 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.get_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc + request = {} + client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_email_preferences(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_get_email_preferences_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 = EmailPreferencesServiceAsyncClient( + 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.get_email_preferences in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_email_preferences] = mock_rpc + + request = {} + await client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_email_preferences(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_get_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.GetEmailPreferencesRequest): + client = EmailPreferencesServiceAsyncClient( + 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.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + response = await client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = emailpreferences.GetEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.asyncio +async def test_get_email_preferences_async_from_dict(): + await test_get_email_preferences_async(request_type=dict) + +def test_get_email_preferences_field_headers(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.GetEmailPreferencesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.get_email_preferences(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_get_email_preferences_field_headers_async(): + client = EmailPreferencesServiceAsyncClient( + 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 = emailpreferences.GetEmailPreferencesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + await client.get_email_preferences(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_get_email_preferences_flattened(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_email_preferences( + 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_get_email_preferences_flattened_error(): + client = EmailPreferencesServiceClient( + 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.get_email_preferences( + emailpreferences.GetEmailPreferencesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_email_preferences_flattened_async(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_email_preferences( + 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_get_email_preferences_flattened_error_async(): + client = EmailPreferencesServiceAsyncClient( + 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.get_email_preferences( + emailpreferences.GetEmailPreferencesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + emailpreferences.UpdateEmailPreferencesRequest, + dict, +]) +def test_update_email_preferences(request_type, transport: str = 'grpc'): + client = EmailPreferencesServiceClient( + 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.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + response = client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = emailpreferences.UpdateEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +def test_update_email_preferences_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 = EmailPreferencesServiceClient( + 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 = emailpreferences.UpdateEmailPreferencesRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_email_preferences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == emailpreferences.UpdateEmailPreferencesRequest( + ) + +def test_update_email_preferences_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 = EmailPreferencesServiceClient( + 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.update_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc + request = {} + client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_email_preferences(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_update_email_preferences_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 = EmailPreferencesServiceAsyncClient( + 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.update_email_preferences in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_email_preferences] = mock_rpc + + request = {} + await client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_email_preferences(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_update_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.UpdateEmailPreferencesRequest): + client = EmailPreferencesServiceAsyncClient( + 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.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + response = await client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = emailpreferences.UpdateEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.asyncio +async def test_update_email_preferences_async_from_dict(): + await test_update_email_preferences_async(request_type=dict) + +def test_update_email_preferences_field_headers(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.UpdateEmailPreferencesRequest() + + request.email_preferences.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.update_email_preferences(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', + 'email_preferences.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_email_preferences_field_headers_async(): + client = EmailPreferencesServiceAsyncClient( + 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 = emailpreferences.UpdateEmailPreferencesRequest() + + request.email_preferences.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + await client.update_email_preferences(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', + 'email_preferences.name=name_value', + ) in kw['metadata'] + + +def test_update_email_preferences_flattened(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_email_preferences( + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].email_preferences + mock_val = emailpreferences.EmailPreferences(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_email_preferences_flattened_error(): + client = EmailPreferencesServiceClient( + 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.update_email_preferences( + emailpreferences.UpdateEmailPreferencesRequest(), + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_email_preferences_flattened_async(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_email_preferences( + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].email_preferences + mock_val = emailpreferences.EmailPreferences(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_email_preferences_flattened_error_async(): + client = EmailPreferencesServiceAsyncClient( + 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.update_email_preferences( + emailpreferences.UpdateEmailPreferencesRequest(), + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_email_preferences_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 = EmailPreferencesServiceClient( + 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.get_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc + + request = {} + client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_email_preferences(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_get_email_preferences_rest_required_fields(request_type=emailpreferences.GetEmailPreferencesRequest): + transport_class = transports.EmailPreferencesServiceRestTransport + + 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()).get_email_preferences._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_email_preferences._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 = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = emailpreferences.EmailPreferences() + # 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 = emailpreferences.EmailPreferences.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.get_email_preferences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_email_preferences_rest_unset_required_fields(): + transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_email_preferences._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_email_preferences_rest_flattened(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.EmailPreferences() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + + # 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 + # Convert return value to protobuf type + return_value = emailpreferences.EmailPreferences.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.get_email_preferences(**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/accounts/v1/{name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) + + +def test_get_email_preferences_rest_flattened_error(transport: str = 'rest'): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_email_preferences( + emailpreferences.GetEmailPreferencesRequest(), + name='name_value', + ) + + +def test_update_email_preferences_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 = EmailPreferencesServiceClient( + 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.update_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc + + request = {} + client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_email_preferences(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_update_email_preferences_rest_required_fields(request_type=emailpreferences.UpdateEmailPreferencesRequest): + transport_class = transports.EmailPreferencesServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = emailpreferences.EmailPreferences() + # 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': "patch", + '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 = emailpreferences.EmailPreferences.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.update_email_preferences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_email_preferences_rest_unset_required_fields(): + transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_email_preferences._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("emailPreferences", "updateMask", ))) + + +def test_update_email_preferences_rest_flattened(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.EmailPreferences() + + # get arguments that satisfy an http rule for this method + sample_request = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + + # get truthy value for each flattened field + mock_args = dict( + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = emailpreferences.EmailPreferences.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.update_email_preferences(**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/accounts/v1/{email_preferences.name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) + + +def test_update_email_preferences_rest_flattened_error(transport: str = 'rest'): + client = EmailPreferencesServiceClient( + 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.update_email_preferences( + emailpreferences.UpdateEmailPreferencesRequest(), + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + 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 = EmailPreferencesServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EmailPreferencesServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EmailPreferencesServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + transports.EmailPreferencesServiceRestTransport, +]) +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 = EmailPreferencesServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EmailPreferencesServiceClient( + 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_get_email_preferences_empty_call_grpc(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.get_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.GetEmailPreferencesRequest() + + 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_update_email_preferences_empty_call_grpc(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.update_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.UpdateEmailPreferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EmailPreferencesServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EmailPreferencesServiceAsyncClient( + 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_get_email_preferences_empty_call_grpc_asyncio(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + await client.get_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.GetEmailPreferencesRequest() + + 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_update_email_preferences_empty_call_grpc_asyncio(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + await client.update_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.UpdateEmailPreferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EmailPreferencesServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_email_preferences_rest_bad_request(request_type=emailpreferences.GetEmailPreferencesRequest): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + 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.get_email_preferences(request) + + +@pytest.mark.parametrize("request_type", [ + emailpreferences.GetEmailPreferencesRequest, + dict, +]) +def test_get_email_preferences_rest_call_success(request_type): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + request = request_type(**request_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 = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + + # 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 = emailpreferences.EmailPreferences.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.get_email_preferences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_email_preferences_rest_interceptors(null_interceptor): + transport = transports.EmailPreferencesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), + ) + client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences") as post, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_get_email_preferences") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = emailpreferences.GetEmailPreferencesRequest.pb(emailpreferences.GetEmailPreferencesRequest()) + 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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) + req.return_value.content = return_value + + request = emailpreferences.GetEmailPreferencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = emailpreferences.EmailPreferences() + post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata + + client.get_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_email_preferences_rest_bad_request(request_type=emailpreferences.UpdateEmailPreferencesRequest): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + 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.update_email_preferences(request) + + +@pytest.mark.parametrize("request_type", [ + emailpreferences.UpdateEmailPreferencesRequest, + dict, +]) +def test_update_email_preferences_rest_call_success(request_type): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + request_init["email_preferences"] = {'name': 'accounts/sample1/users/sample2/emailPreferences', 'news_and_tips': 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 = emailpreferences.UpdateEmailPreferencesRequest.meta.fields["email_preferences"] + + 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["email_preferences"].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["email_preferences"][field])): + del request_init["email_preferences"][field][i][subfield] + else: + del request_init["email_preferences"][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 = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + + # 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 = emailpreferences.EmailPreferences.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.update_email_preferences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_email_preferences_rest_interceptors(null_interceptor): + transport = transports.EmailPreferencesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), + ) + client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences") as post, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_update_email_preferences") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = emailpreferences.UpdateEmailPreferencesRequest.pb(emailpreferences.UpdateEmailPreferencesRequest()) + 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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) + req.return_value.content = return_value + + request = emailpreferences.UpdateEmailPreferencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = emailpreferences.EmailPreferences() + post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata + + client.update_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = EmailPreferencesServiceClient( + 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_get_email_preferences_empty_call_rest(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + client.get_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.GetEmailPreferencesRequest() + + 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_update_email_preferences_empty_call_rest(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + client.update_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.UpdateEmailPreferencesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EmailPreferencesServiceGrpcTransport, + ) + +def test_email_preferences_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EmailPreferencesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_email_preferences_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EmailPreferencesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_email_preferences', + 'update_email_preferences', + ) + 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_email_preferences_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_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EmailPreferencesServiceTransport( + 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_email_preferences_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_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EmailPreferencesServiceTransport() + adc.assert_called_once() + + +def test_email_preferences_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) + EmailPreferencesServiceClient() + 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.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + ], +) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + transports.EmailPreferencesServiceRestTransport, + ], +) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, grpc_helpers), + (transports.EmailPreferencesServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +def test_email_preferences_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_email_preferences_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.EmailPreferencesServiceRestTransport ( + 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_email_preferences_service_host_no_port(transport_name): + client = EmailPreferencesServiceClient( + 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_email_preferences_service_host_with_port(transport_name): + client = EmailPreferencesServiceClient( + 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_email_preferences_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EmailPreferencesServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EmailPreferencesServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_email_preferences._session + session2 = client2.transport.get_email_preferences._session + assert session1 != session2 + session1 = client1.transport.update_email_preferences._session + session2 = client2.transport.update_email_preferences._session + assert session1 != session2 +def test_email_preferences_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EmailPreferencesServiceGrpcTransport( + 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_email_preferences_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EmailPreferencesServiceGrpcAsyncIOTransport( + 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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +def test_email_preferences_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_email_preferences_path(): + account = "squid" + email = "clam" + expected = "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) + actual = EmailPreferencesServiceClient.email_preferences_path(account, email) + assert expected == actual + + +def test_parse_email_preferences_path(): + expected = { + "account": "whelk", + "email": "octopus", + } + path = EmailPreferencesServiceClient.email_preferences_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_email_preferences_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EmailPreferencesServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = EmailPreferencesServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = EmailPreferencesServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = EmailPreferencesServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EmailPreferencesServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = EmailPreferencesServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = EmailPreferencesServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = EmailPreferencesServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EmailPreferencesServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = EmailPreferencesServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.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.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = EmailPreferencesServiceClient.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 = EmailPreferencesServiceClient( + 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 = EmailPreferencesServiceAsyncClient( + 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 = EmailPreferencesServiceClient( + 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 = EmailPreferencesServiceClient( + 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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py new file mode 100644 index 000000000000..42eb419c7ba8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py @@ -0,0 +1,3072 @@ +# -*- 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 empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import GbpAccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import GbpAccountsServiceClient +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import pagers +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import transports +from google.shopping.merchant_accounts_v1.types import gbpaccounts +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 GbpAccountsServiceClient._get_default_mtls_endpoint(None) is None + assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert GbpAccountsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + GbpAccountsServiceClient._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 GbpAccountsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + GbpAccountsServiceClient._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 GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, False) is None + assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert GbpAccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert GbpAccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert GbpAccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert GbpAccountsServiceClient._get_universe_domain(None, None) == GbpAccountsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + GbpAccountsServiceClient._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 = GbpAccountsServiceClient(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 = GbpAccountsServiceClient(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", [ + (GbpAccountsServiceClient, "grpc"), + (GbpAccountsServiceAsyncClient, "grpc_asyncio"), + (GbpAccountsServiceClient, "rest"), +]) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, "grpc"), + (transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GbpAccountsServiceRestTransport, "rest"), +]) +def test_gbp_accounts_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", [ + (GbpAccountsServiceClient, "grpc"), + (GbpAccountsServiceAsyncClient, "grpc_asyncio"), + (GbpAccountsServiceClient, "rest"), +]) +def test_gbp_accounts_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_gbp_accounts_service_client_get_transport_class(): + transport = GbpAccountsServiceClient.get_transport_class() + available_transports = [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceRestTransport, + ] + assert transport in available_transports + + transport = GbpAccountsServiceClient.get_transport_class("grpc") + assert transport == transports.GbpAccountsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), +]) +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +def test_gbp_accounts_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(GbpAccountsServiceClient, '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(GbpAccountsServiceClient, '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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "true"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "false"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "true"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_gbp_accounts_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", [ + GbpAccountsServiceClient, GbpAccountsServiceAsyncClient +]) +@mock.patch.object(GbpAccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceAsyncClient)) +def test_gbp_accounts_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", [ + GbpAccountsServiceClient, GbpAccountsServiceAsyncClient +]) +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +def test_gbp_accounts_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = GbpAccountsServiceClient._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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), +]) +def test_gbp_accounts_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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", None), +]) +def test_gbp_accounts_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_gbp_accounts_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = GbpAccountsServiceClient( + 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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_gbp_accounts_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", [ + gbpaccounts.ListGbpAccountsRequest, + dict, +]) +def test_list_gbp_accounts(request_type, transport: str = 'grpc'): + client = GbpAccountsServiceClient( + 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_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.ListGbpAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gbpaccounts.ListGbpAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGbpAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_gbp_accounts_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 = GbpAccountsServiceClient( + 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 = gbpaccounts.ListGbpAccountsRequest( + 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_gbp_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_gbp_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gbpaccounts.ListGbpAccountsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_gbp_accounts_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 = GbpAccountsServiceClient( + 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_gbp_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_gbp_accounts] = mock_rpc + request = {} + client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_gbp_accounts(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_gbp_accounts_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 = GbpAccountsServiceAsyncClient( + 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_gbp_accounts 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_gbp_accounts] = mock_rpc + + request = {} + await client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_gbp_accounts(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_gbp_accounts_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.ListGbpAccountsRequest): + client = GbpAccountsServiceAsyncClient( + 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_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gbpaccounts.ListGbpAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGbpAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_gbp_accounts_async_from_dict(): + await test_list_gbp_accounts_async(request_type=dict) + +def test_list_gbp_accounts_field_headers(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.ListGbpAccountsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + call.return_value = gbpaccounts.ListGbpAccountsResponse() + client.list_gbp_accounts(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_gbp_accounts_field_headers_async(): + client = GbpAccountsServiceAsyncClient( + 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 = gbpaccounts.ListGbpAccountsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) + await client.list_gbp_accounts(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_gbp_accounts_flattened(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.ListGbpAccountsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_gbp_accounts( + 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_gbp_accounts_flattened_error(): + client = GbpAccountsServiceClient( + 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_gbp_accounts( + gbpaccounts.ListGbpAccountsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_gbp_accounts_flattened_async(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.ListGbpAccountsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_gbp_accounts( + 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_gbp_accounts_flattened_error_async(): + client = GbpAccountsServiceAsyncClient( + 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_gbp_accounts( + gbpaccounts.ListGbpAccountsRequest(), + parent='parent_value', + ) + + +def test_list_gbp_accounts_pager(transport_name: str = "grpc"): + client = GbpAccountsServiceClient( + 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_gbp_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_gbp_accounts(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, gbpaccounts.GbpAccount) + for i in results) +def test_list_gbp_accounts_pages(transport_name: str = "grpc"): + client = GbpAccountsServiceClient( + 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_gbp_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + RuntimeError, + ) + pages = list(client.list_gbp_accounts(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_gbp_accounts_async_pager(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_gbp_accounts(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, gbpaccounts.GbpAccount) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_gbp_accounts_async_pages(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + 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_gbp_accounts(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", [ + gbpaccounts.LinkGbpAccountRequest, + dict, +]) +def test_link_gbp_account(request_type, transport: str = 'grpc'): + client = GbpAccountsServiceClient( + 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.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.LinkGbpAccountResponse( + ) + response = client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gbpaccounts.LinkGbpAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) + + +def test_link_gbp_account_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 = GbpAccountsServiceClient( + 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 = gbpaccounts.LinkGbpAccountRequest( + parent='parent_value', + gbp_email='gbp_email_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.link_gbp_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gbpaccounts.LinkGbpAccountRequest( + parent='parent_value', + gbp_email='gbp_email_value', + ) + +def test_link_gbp_account_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 = GbpAccountsServiceClient( + 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.link_gbp_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc + request = {} + client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_gbp_account(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_link_gbp_account_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 = GbpAccountsServiceAsyncClient( + 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.link_gbp_account 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.link_gbp_account] = mock_rpc + + request = {} + await client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.link_gbp_account(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_link_gbp_account_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.LinkGbpAccountRequest): + client = GbpAccountsServiceAsyncClient( + 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.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( + )) + response = await client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gbpaccounts.LinkGbpAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) + + +@pytest.mark.asyncio +async def test_link_gbp_account_async_from_dict(): + await test_link_gbp_account_async(request_type=dict) + +def test_link_gbp_account_field_headers(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.LinkGbpAccountRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value = gbpaccounts.LinkGbpAccountResponse() + client.link_gbp_account(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_link_gbp_account_field_headers_async(): + client = GbpAccountsServiceAsyncClient( + 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 = gbpaccounts.LinkGbpAccountRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) + await client.link_gbp_account(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_link_gbp_account_flattened(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.LinkGbpAccountResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.link_gbp_account( + 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_link_gbp_account_flattened_error(): + client = GbpAccountsServiceClient( + 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.link_gbp_account( + gbpaccounts.LinkGbpAccountRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_link_gbp_account_flattened_async(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.LinkGbpAccountResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.link_gbp_account( + 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_link_gbp_account_flattened_error_async(): + client = GbpAccountsServiceAsyncClient( + 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.link_gbp_account( + gbpaccounts.LinkGbpAccountRequest(), + parent='parent_value', + ) + + +def test_list_gbp_accounts_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 = GbpAccountsServiceClient( + 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_gbp_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_gbp_accounts] = mock_rpc + + request = {} + client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_gbp_accounts(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_gbp_accounts_rest_required_fields(request_type=gbpaccounts.ListGbpAccountsRequest): + transport_class = transports.GbpAccountsServiceRestTransport + + 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_gbp_accounts._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_gbp_accounts._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 = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.ListGbpAccountsResponse() + # 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_gbp_accounts_rest_unset_required_fields(): + transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_gbp_accounts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_gbp_accounts_rest_flattened(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.ListGbpAccountsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(**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/accounts/v1/{parent=accounts/*}/gbpAccounts" % client.transport._host, args[1]) + + +def test_list_gbp_accounts_rest_flattened_error(transport: str = 'rest'): + client = GbpAccountsServiceClient( + 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_gbp_accounts( + gbpaccounts.ListGbpAccountsRequest(), + parent='parent_value', + ) + + +def test_list_gbp_accounts_rest_pager(transport: str = 'rest'): + client = GbpAccountsServiceClient( + 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 = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gbpaccounts.ListGbpAccountsResponse.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'} + + pager = client.list_gbp_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gbpaccounts.GbpAccount) + for i in results) + + pages = list(client.list_gbp_accounts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_link_gbp_account_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 = GbpAccountsServiceClient( + 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.link_gbp_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc + + request = {} + client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_gbp_account(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_link_gbp_account_rest_required_fields(request_type=gbpaccounts.LinkGbpAccountRequest): + transport_class = transports.GbpAccountsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["gbp_email"] = "" + 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()).link_gbp_account._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["gbpEmail"] = 'gbp_email_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_gbp_account._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 "gbpEmail" in jsonified_request + assert jsonified_request["gbpEmail"] == 'gbp_email_value' + + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.LinkGbpAccountResponse() + # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_link_gbp_account_rest_unset_required_fields(): + transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.link_gbp_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "gbpEmail", ))) + + +def test_link_gbp_account_rest_flattened(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.LinkGbpAccountResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(**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/accounts/v1/{parent=accounts/*}/gbpAccounts:linkGbpAccount" % client.transport._host, args[1]) + + +def test_link_gbp_account_rest_flattened_error(transport: str = 'rest'): + client = GbpAccountsServiceClient( + 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.link_gbp_account( + gbpaccounts.LinkGbpAccountRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + 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 = GbpAccountsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GbpAccountsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GbpAccountsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + transports.GbpAccountsServiceRestTransport, +]) +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 = GbpAccountsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GbpAccountsServiceClient( + 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_gbp_accounts_empty_call_grpc(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + call.return_value = gbpaccounts.ListGbpAccountsResponse() + client.list_gbp_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.ListGbpAccountsRequest() + + 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_link_gbp_account_empty_call_grpc(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value = gbpaccounts.LinkGbpAccountResponse() + client.link_gbp_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.LinkGbpAccountRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GbpAccountsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GbpAccountsServiceAsyncClient( + 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_gbp_accounts_empty_call_grpc_asyncio(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( + next_page_token='next_page_token_value', + )) + await client.list_gbp_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.ListGbpAccountsRequest() + + 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_link_gbp_account_empty_call_grpc_asyncio(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( + )) + await client.link_gbp_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.LinkGbpAccountRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GbpAccountsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_gbp_accounts_rest_bad_request(request_type=gbpaccounts.ListGbpAccountsRequest): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_gbp_accounts(request) + + +@pytest.mark.parametrize("request_type", [ + gbpaccounts.ListGbpAccountsRequest, + dict, +]) +def test_list_gbp_accounts_rest_call_success(request_type): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.ListGbpAccountsResponse( + 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGbpAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_gbp_accounts_rest_interceptors(null_interceptor): + transport = transports.GbpAccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), + ) + client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts") as post, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_list_gbp_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gbpaccounts.ListGbpAccountsRequest.pb(gbpaccounts.ListGbpAccountsRequest()) + 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 = gbpaccounts.ListGbpAccountsResponse.to_json(gbpaccounts.ListGbpAccountsResponse()) + req.return_value.content = return_value + + request = gbpaccounts.ListGbpAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gbpaccounts.ListGbpAccountsResponse() + post_with_metadata.return_value = gbpaccounts.ListGbpAccountsResponse(), metadata + + client.list_gbp_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_link_gbp_account_rest_bad_request(request_type=gbpaccounts.LinkGbpAccountRequest): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.link_gbp_account(request) + + +@pytest.mark.parametrize("request_type", [ + gbpaccounts.LinkGbpAccountRequest, + dict, +]) +def test_link_gbp_account_rest_call_success(request_type): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.LinkGbpAccountResponse( + ) + + # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_link_gbp_account_rest_interceptors(null_interceptor): + transport = transports.GbpAccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), + ) + client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_link_gbp_account") as post, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_link_gbp_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_link_gbp_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gbpaccounts.LinkGbpAccountRequest.pb(gbpaccounts.LinkGbpAccountRequest()) + 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 = gbpaccounts.LinkGbpAccountResponse.to_json(gbpaccounts.LinkGbpAccountResponse()) + req.return_value.content = return_value + + request = gbpaccounts.LinkGbpAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gbpaccounts.LinkGbpAccountResponse() + post_with_metadata.return_value = gbpaccounts.LinkGbpAccountResponse(), metadata + + client.link_gbp_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = GbpAccountsServiceClient( + 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_gbp_accounts_empty_call_rest(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + client.list_gbp_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.ListGbpAccountsRequest() + + 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_link_gbp_account_empty_call_rest(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + client.link_gbp_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.LinkGbpAccountRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GbpAccountsServiceGrpcTransport, + ) + +def test_gbp_accounts_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GbpAccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_gbp_accounts_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.GbpAccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_gbp_accounts', + 'link_gbp_account', + ) + 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_gbp_accounts_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_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GbpAccountsServiceTransport( + 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_gbp_accounts_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_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GbpAccountsServiceTransport() + adc.assert_called_once() + + +def test_gbp_accounts_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) + GbpAccountsServiceClient() + 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.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + ], +) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + transports.GbpAccountsServiceRestTransport, + ], +) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, grpc_helpers), + (transports.GbpAccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +def test_gbp_accounts_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_gbp_accounts_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.GbpAccountsServiceRestTransport ( + 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_gbp_accounts_service_host_no_port(transport_name): + client = GbpAccountsServiceClient( + 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_gbp_accounts_service_host_with_port(transport_name): + client = GbpAccountsServiceClient( + 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_gbp_accounts_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GbpAccountsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GbpAccountsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_gbp_accounts._session + session2 = client2.transport.list_gbp_accounts._session + assert session1 != session2 + session1 = client1.transport.link_gbp_account._session + session2 = client2.transport.link_gbp_account._session + assert session1 != session2 +def test_gbp_accounts_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GbpAccountsServiceGrpcTransport( + 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_gbp_accounts_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GbpAccountsServiceGrpcAsyncIOTransport( + 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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +def test_gbp_accounts_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = GbpAccountsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = GbpAccountsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_account_path(path) + assert expected == actual + +def test_gbp_account_path(): + account = "whelk" + gbp_account = "octopus" + expected = "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) + actual = GbpAccountsServiceClient.gbp_account_path(account, gbp_account) + assert expected == actual + + +def test_parse_gbp_account_path(): + expected = { + "account": "oyster", + "gbp_account": "nudibranch", + } + path = GbpAccountsServiceClient.gbp_account_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_gbp_account_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = GbpAccountsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = GbpAccountsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = GbpAccountsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = GbpAccountsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = GbpAccountsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = GbpAccountsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = GbpAccountsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = GbpAccountsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = GbpAccountsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.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.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = GbpAccountsServiceClient.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 = GbpAccountsServiceClient( + 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 = GbpAccountsServiceAsyncClient( + 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 = GbpAccountsServiceClient( + 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 = GbpAccountsServiceClient( + 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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py new file mode 100644 index 000000000000..cae1a8c9f93f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py @@ -0,0 +1,3965 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.homepage_service import HomepageServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.homepage_service import HomepageServiceClient +from google.shopping.merchant_accounts_v1.services.homepage_service import transports +from google.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +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 HomepageServiceClient._get_default_mtls_endpoint(None) is None + assert HomepageServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HomepageServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + HomepageServiceClient._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 HomepageServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert HomepageServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + HomepageServiceClient._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 HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, False) is None + assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = HomepageServiceClient._DEFAULT_UNIVERSE + default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert HomepageServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + assert HomepageServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + HomepageServiceClient._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 HomepageServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert HomepageServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert HomepageServiceClient._get_universe_domain(None, None) == HomepageServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + HomepageServiceClient._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 = HomepageServiceClient(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 = HomepageServiceClient(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", [ + (HomepageServiceClient, "grpc"), + (HomepageServiceAsyncClient, "grpc_asyncio"), + (HomepageServiceClient, "rest"), +]) +def test_homepage_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.HomepageServiceGrpcTransport, "grpc"), + (transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.HomepageServiceRestTransport, "rest"), +]) +def test_homepage_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", [ + (HomepageServiceClient, "grpc"), + (HomepageServiceAsyncClient, "grpc_asyncio"), + (HomepageServiceClient, "rest"), +]) +def test_homepage_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_homepage_service_client_get_transport_class(): + transport = HomepageServiceClient.get_transport_class() + available_transports = [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceRestTransport, + ] + assert transport in available_transports + + transport = HomepageServiceClient.get_transport_class("grpc") + assert transport == transports.HomepageServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), +]) +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +def test_homepage_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(HomepageServiceClient, '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(HomepageServiceClient, '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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "true"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "false"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "true"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_homepage_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", [ + HomepageServiceClient, HomepageServiceAsyncClient +]) +@mock.patch.object(HomepageServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceAsyncClient)) +def test_homepage_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", [ + HomepageServiceClient, HomepageServiceAsyncClient +]) +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +def test_homepage_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = HomepageServiceClient._DEFAULT_UNIVERSE + default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = HomepageServiceClient._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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), +]) +def test_homepage_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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", None), +]) +def test_homepage_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_homepage_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = HomepageServiceClient( + 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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_homepage_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", [ + homepage.GetHomepageRequest, + dict, +]) +def test_get_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = homepage.GetHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_get_homepage_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 = HomepageServiceClient( + 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 = homepage.GetHomepageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == homepage.GetHomepageRequest( + name='name_value', + ) + +def test_get_homepage_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 = HomepageServiceClient( + 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.get_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc + request = {} + client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_homepage(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_get_homepage_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 = HomepageServiceAsyncClient( + 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.get_homepage in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_homepage] = mock_rpc + + request = {} + await client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_homepage(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_get_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.GetHomepageRequest): + client = HomepageServiceAsyncClient( + 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.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = homepage.GetHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_get_homepage_async_from_dict(): + await test_get_homepage_async(request_type=dict) + +def test_get_homepage_field_headers(): + client = HomepageServiceClient( + 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 = homepage.GetHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.get_homepage(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_get_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = homepage.GetHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + await client.get_homepage(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_get_homepage_flattened(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_homepage( + 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_get_homepage_flattened_error(): + client = HomepageServiceClient( + 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.get_homepage( + homepage.GetHomepageRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_homepage_flattened_async(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_homepage( + 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_get_homepage_flattened_error_async(): + client = HomepageServiceAsyncClient( + 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.get_homepage( + homepage.GetHomepageRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_homepage.UpdateHomepageRequest, + dict, +]) +def test_update_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_homepage.UpdateHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_update_homepage_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 = HomepageServiceClient( + 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 = gsma_homepage.UpdateHomepageRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_homepage.UpdateHomepageRequest( + ) + +def test_update_homepage_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 = HomepageServiceClient( + 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.update_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc + request = {} + client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_homepage(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_update_homepage_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 = HomepageServiceAsyncClient( + 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.update_homepage in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_homepage] = mock_rpc + + request = {} + await client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_homepage(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_update_homepage_async(transport: str = 'grpc_asyncio', request_type=gsma_homepage.UpdateHomepageRequest): + client = HomepageServiceAsyncClient( + 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.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_homepage.UpdateHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_update_homepage_async_from_dict(): + await test_update_homepage_async(request_type=dict) + +def test_update_homepage_field_headers(): + client = HomepageServiceClient( + 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 = gsma_homepage.UpdateHomepageRequest() + + request.homepage.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value = gsma_homepage.Homepage() + client.update_homepage(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', + 'homepage.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = gsma_homepage.UpdateHomepageRequest() + + request.homepage.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) + await client.update_homepage(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', + 'homepage.name=name_value', + ) in kw['metadata'] + + +def test_update_homepage_flattened(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_homepage.Homepage() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_homepage( + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].homepage + mock_val = gsma_homepage.Homepage(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_homepage_flattened_error(): + client = HomepageServiceClient( + 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.update_homepage( + gsma_homepage.UpdateHomepageRequest(), + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_homepage_flattened_async(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_homepage.Homepage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_homepage( + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].homepage + mock_val = gsma_homepage.Homepage(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_homepage_flattened_error_async(): + client = HomepageServiceAsyncClient( + 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.update_homepage( + gsma_homepage.UpdateHomepageRequest(), + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + homepage.ClaimHomepageRequest, + dict, +]) +def test_claim_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.claim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = homepage.ClaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_claim_homepage_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 = HomepageServiceClient( + 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 = homepage.ClaimHomepageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.claim_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == homepage.ClaimHomepageRequest( + name='name_value', + ) + +def test_claim_homepage_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 = HomepageServiceClient( + 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.claim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc + request = {} + client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.claim_homepage(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_claim_homepage_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 = HomepageServiceAsyncClient( + 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.claim_homepage 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.claim_homepage] = mock_rpc + + request = {} + await client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.claim_homepage(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_claim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.ClaimHomepageRequest): + client = HomepageServiceAsyncClient( + 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.claim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = homepage.ClaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_claim_homepage_async_from_dict(): + await test_claim_homepage_async(request_type=dict) + +def test_claim_homepage_field_headers(): + client = HomepageServiceClient( + 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 = homepage.ClaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.claim_homepage(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_claim_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = homepage.ClaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + await client.claim_homepage(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'] + + +@pytest.mark.parametrize("request_type", [ + homepage.UnclaimHomepageRequest, + dict, +]) +def test_unclaim_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.unclaim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = homepage.UnclaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_unclaim_homepage_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 = HomepageServiceClient( + 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 = homepage.UnclaimHomepageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.unclaim_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == homepage.UnclaimHomepageRequest( + name='name_value', + ) + +def test_unclaim_homepage_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 = HomepageServiceClient( + 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.unclaim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc + request = {} + client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.unclaim_homepage(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_unclaim_homepage_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 = HomepageServiceAsyncClient( + 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.unclaim_homepage 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.unclaim_homepage] = mock_rpc + + request = {} + await client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.unclaim_homepage(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_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.UnclaimHomepageRequest): + client = HomepageServiceAsyncClient( + 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.unclaim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = homepage.UnclaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_unclaim_homepage_async_from_dict(): + await test_unclaim_homepage_async(request_type=dict) + +def test_unclaim_homepage_field_headers(): + client = HomepageServiceClient( + 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 = homepage.UnclaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.unclaim_homepage(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_unclaim_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = homepage.UnclaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + await client.unclaim_homepage(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_get_homepage_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 = HomepageServiceClient( + 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.get_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc + + request = {} + client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_homepage(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_get_homepage_rest_required_fields(request_type=homepage.GetHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + 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()).get_homepage._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_homepage._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 = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = homepage.Homepage() + # 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 = homepage.Homepage.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.get_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_homepage_rest_flattened(): + client = HomepageServiceClient( + 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 = homepage.Homepage() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/homepage'} + + # 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 + # Convert return value to protobuf type + return_value = homepage.Homepage.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.get_homepage(**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/accounts/v1/{name=accounts/*/homepage}" % client.transport._host, args[1]) + + +def test_get_homepage_rest_flattened_error(transport: str = 'rest'): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_homepage( + homepage.GetHomepageRequest(), + name='name_value', + ) + + +def test_update_homepage_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 = HomepageServiceClient( + 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.update_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc + + request = {} + client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_homepage(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_update_homepage_rest_required_fields(request_type=gsma_homepage.UpdateHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_homepage.Homepage() + # 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': "patch", + '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 = gsma_homepage.Homepage.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.update_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("homepage", ))) + + +def test_update_homepage_rest_flattened(): + client = HomepageServiceClient( + 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 = gsma_homepage.Homepage() + + # get arguments that satisfy an http rule for this method + sample_request = {'homepage': {'name': 'accounts/sample1/homepage'}} + + # get truthy value for each flattened field + mock_args = dict( + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_homepage.Homepage.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.update_homepage(**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/accounts/v1/{homepage.name=accounts/*/homepage}" % client.transport._host, args[1]) + + +def test_update_homepage_rest_flattened_error(transport: str = 'rest'): + client = HomepageServiceClient( + 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.update_homepage( + gsma_homepage.UpdateHomepageRequest(), + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_claim_homepage_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 = HomepageServiceClient( + 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.claim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc + + request = {} + client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.claim_homepage(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_claim_homepage_rest_required_fields(request_type=homepage.ClaimHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + 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()).claim_homepage._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()).claim_homepage._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 = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = homepage.Homepage() + # 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 = homepage.Homepage.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.claim_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_claim_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.claim_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_unclaim_homepage_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 = HomepageServiceClient( + 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.unclaim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc + + request = {} + client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.unclaim_homepage(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_unclaim_homepage_rest_required_fields(request_type=homepage.UnclaimHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + 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()).unclaim_homepage._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()).unclaim_homepage._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 = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = homepage.Homepage() + # 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 = homepage.Homepage.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.unclaim_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_unclaim_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.unclaim_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HomepageServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HomepageServiceClient( + 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 = HomepageServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HomepageServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = HomepageServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.HomepageServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + transports.HomepageServiceRestTransport, +]) +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 = HomepageServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = HomepageServiceClient( + 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_get_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.get_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.GetHomepageRequest() + + 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_update_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value = gsma_homepage.Homepage() + client.update_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_homepage.UpdateHomepageRequest() + + 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_claim_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.claim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.ClaimHomepageRequest() + + 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_unclaim_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.unclaim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.UnclaimHomepageRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = HomepageServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = HomepageServiceAsyncClient( + 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_get_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.get_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.GetHomepageRequest() + + 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_update_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.update_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_homepage.UpdateHomepageRequest() + + 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_claim_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.claim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.ClaimHomepageRequest() + + 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_unclaim_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.unclaim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.UnclaimHomepageRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = HomepageServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_homepage_rest_bad_request(request_type=homepage.GetHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + 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.get_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + homepage.GetHomepageRequest, + dict, +]) +def test_get_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + request = request_type(**request_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 = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = homepage.Homepage.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.get_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_get_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_get_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_get_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = homepage.GetHomepageRequest.pb(homepage.GetHomepageRequest()) + 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 = homepage.Homepage.to_json(homepage.Homepage()) + req.return_value.content = return_value + + request = homepage.GetHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = homepage.Homepage() + post_with_metadata.return_value = homepage.Homepage(), metadata + + client.get_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_homepage_rest_bad_request(request_type=gsma_homepage.UpdateHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} + 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.update_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_homepage.UpdateHomepageRequest, + dict, +]) +def test_update_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} + request_init["homepage"] = {'name': 'accounts/sample1/homepage', 'uri': 'uri_value', 'claimed': True} + # 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 = gsma_homepage.UpdateHomepageRequest.meta.fields["homepage"] + + 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["homepage"].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["homepage"][field])): + del request_init["homepage"][field][i][subfield] + else: + del request_init["homepage"][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 = gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = gsma_homepage.Homepage.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.update_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_update_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_update_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_update_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_homepage.UpdateHomepageRequest.pb(gsma_homepage.UpdateHomepageRequest()) + 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 = gsma_homepage.Homepage.to_json(gsma_homepage.Homepage()) + req.return_value.content = return_value + + request = gsma_homepage.UpdateHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_homepage.Homepage() + post_with_metadata.return_value = gsma_homepage.Homepage(), metadata + + client.update_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_claim_homepage_rest_bad_request(request_type=homepage.ClaimHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + 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.claim_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + homepage.ClaimHomepageRequest, + dict, +]) +def test_claim_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + request = request_type(**request_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 = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = homepage.Homepage.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.claim_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_claim_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_claim_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_claim_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_claim_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = homepage.ClaimHomepageRequest.pb(homepage.ClaimHomepageRequest()) + 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 = homepage.Homepage.to_json(homepage.Homepage()) + req.return_value.content = return_value + + request = homepage.ClaimHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = homepage.Homepage() + post_with_metadata.return_value = homepage.Homepage(), metadata + + client.claim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_unclaim_homepage_rest_bad_request(request_type=homepage.UnclaimHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + 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.unclaim_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + homepage.UnclaimHomepageRequest, + dict, +]) +def test_unclaim_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + request = request_type(**request_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 = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = homepage.Homepage.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.unclaim_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_unclaim_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_unclaim_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_unclaim_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_unclaim_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = homepage.UnclaimHomepageRequest.pb(homepage.UnclaimHomepageRequest()) + 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 = homepage.Homepage.to_json(homepage.Homepage()) + req.return_value.content = return_value + + request = homepage.UnclaimHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = homepage.Homepage() + post_with_metadata.return_value = homepage.Homepage(), metadata + + client.unclaim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = HomepageServiceClient( + 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_get_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + client.get_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.GetHomepageRequest() + + 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_update_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + client.update_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_homepage.UpdateHomepageRequest() + + 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_claim_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + client.claim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.ClaimHomepageRequest() + + 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_unclaim_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + client.unclaim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.UnclaimHomepageRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.HomepageServiceGrpcTransport, + ) + +def test_homepage_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.HomepageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_homepage_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.HomepageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_homepage', + 'update_homepage', + 'claim_homepage', + 'unclaim_homepage', + ) + 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_homepage_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_accounts_v1.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HomepageServiceTransport( + 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_homepage_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_accounts_v1.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HomepageServiceTransport() + adc.assert_called_once() + + +def test_homepage_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) + HomepageServiceClient() + 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.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + ], +) +def test_homepage_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.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + transports.HomepageServiceRestTransport, + ], +) +def test_homepage_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.HomepageServiceGrpcTransport, grpc_helpers), + (transports.HomepageServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +def test_homepage_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_homepage_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.HomepageServiceRestTransport ( + 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_homepage_service_host_no_port(transport_name): + client = HomepageServiceClient( + 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_homepage_service_host_with_port(transport_name): + client = HomepageServiceClient( + 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_homepage_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = HomepageServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = HomepageServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_homepage._session + session2 = client2.transport.get_homepage._session + assert session1 != session2 + session1 = client1.transport.update_homepage._session + session2 = client2.transport.update_homepage._session + assert session1 != session2 + session1 = client1.transport.claim_homepage._session + session2 = client2.transport.claim_homepage._session + assert session1 != session2 + session1 = client1.transport.unclaim_homepage._session + session2 = client2.transport.unclaim_homepage._session + assert session1 != session2 +def test_homepage_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HomepageServiceGrpcTransport( + 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_homepage_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HomepageServiceGrpcAsyncIOTransport( + 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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +def test_homepage_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_homepage_path(): + account = "squid" + expected = "accounts/{account}/homepage".format(account=account, ) + actual = HomepageServiceClient.homepage_path(account) + assert expected == actual + + +def test_parse_homepage_path(): + expected = { + "account": "clam", + } + path = HomepageServiceClient.homepage_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_homepage_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = HomepageServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = HomepageServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = HomepageServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = HomepageServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = HomepageServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = HomepageServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = HomepageServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = HomepageServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = HomepageServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = HomepageServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.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.HomepageServiceTransport, '_prep_wrapped_messages') as prep: + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.HomepageServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = HomepageServiceClient.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 = HomepageServiceClient( + 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 = HomepageServiceAsyncClient( + 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 = HomepageServiceClient( + 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 = HomepageServiceClient( + 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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py new file mode 100644 index 000000000000..fb6cf03df6a2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py @@ -0,0 +1,3076 @@ +# -*- 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 empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import LfpProvidersServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import LfpProvidersServiceClient +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import pagers +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import transports +from google.shopping.merchant_accounts_v1.types import lfpproviders +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 LfpProvidersServiceClient._get_default_mtls_endpoint(None) is None + assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LfpProvidersServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LfpProvidersServiceClient._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 LfpProvidersServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpProvidersServiceClient._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 LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, False) is None + assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LfpProvidersServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpProvidersServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LfpProvidersServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LfpProvidersServiceClient._get_universe_domain(None, None) == LfpProvidersServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LfpProvidersServiceClient._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 = LfpProvidersServiceClient(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 = LfpProvidersServiceClient(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", [ + (LfpProvidersServiceClient, "grpc"), + (LfpProvidersServiceAsyncClient, "grpc_asyncio"), + (LfpProvidersServiceClient, "rest"), +]) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, "grpc"), + (transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LfpProvidersServiceRestTransport, "rest"), +]) +def test_lfp_providers_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", [ + (LfpProvidersServiceClient, "grpc"), + (LfpProvidersServiceAsyncClient, "grpc_asyncio"), + (LfpProvidersServiceClient, "rest"), +]) +def test_lfp_providers_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_lfp_providers_service_client_get_transport_class(): + transport = LfpProvidersServiceClient.get_transport_class() + available_transports = [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceRestTransport, + ] + assert transport in available_transports + + transport = LfpProvidersServiceClient.get_transport_class("grpc") + assert transport == transports.LfpProvidersServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), +]) +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +def test_lfp_providers_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(LfpProvidersServiceClient, '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(LfpProvidersServiceClient, '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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "true"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "false"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "true"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lfp_providers_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", [ + LfpProvidersServiceClient, LfpProvidersServiceAsyncClient +]) +@mock.patch.object(LfpProvidersServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceAsyncClient)) +def test_lfp_providers_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", [ + LfpProvidersServiceClient, LfpProvidersServiceAsyncClient +]) +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +def test_lfp_providers_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpProvidersServiceClient._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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), +]) +def test_lfp_providers_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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", None), +]) +def test_lfp_providers_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_lfp_providers_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LfpProvidersServiceClient( + 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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_lfp_providers_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", [ + lfpproviders.FindLfpProvidersRequest, + dict, +]) +def test_find_lfp_providers(request_type, transport: str = 'grpc'): + client = LfpProvidersServiceClient( + 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.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.FindLfpProvidersResponse( + next_page_token='next_page_token_value', + ) + response = client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpproviders.FindLfpProvidersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FindLfpProvidersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_find_lfp_providers_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 = LfpProvidersServiceClient( + 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 = lfpproviders.FindLfpProvidersRequest( + 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.find_lfp_providers), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.find_lfp_providers(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpproviders.FindLfpProvidersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_find_lfp_providers_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 = LfpProvidersServiceClient( + 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.find_lfp_providers in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc + request = {} + client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_lfp_providers(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_find_lfp_providers_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 = LfpProvidersServiceAsyncClient( + 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.find_lfp_providers 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.find_lfp_providers] = mock_rpc + + request = {} + await client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.find_lfp_providers(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_find_lfp_providers_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.FindLfpProvidersRequest): + client = LfpProvidersServiceAsyncClient( + 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.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( + next_page_token='next_page_token_value', + )) + response = await client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpproviders.FindLfpProvidersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FindLfpProvidersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_find_lfp_providers_async_from_dict(): + await test_find_lfp_providers_async(request_type=dict) + +def test_find_lfp_providers_field_headers(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.FindLfpProvidersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + call.return_value = lfpproviders.FindLfpProvidersResponse() + client.find_lfp_providers(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_find_lfp_providers_field_headers_async(): + client = LfpProvidersServiceAsyncClient( + 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 = lfpproviders.FindLfpProvidersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) + await client.find_lfp_providers(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_find_lfp_providers_flattened(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.FindLfpProvidersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.find_lfp_providers( + 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_find_lfp_providers_flattened_error(): + client = LfpProvidersServiceClient( + 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.find_lfp_providers( + lfpproviders.FindLfpProvidersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_find_lfp_providers_flattened_async(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.FindLfpProvidersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.find_lfp_providers( + 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_find_lfp_providers_flattened_error_async(): + client = LfpProvidersServiceAsyncClient( + 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.find_lfp_providers( + lfpproviders.FindLfpProvidersRequest(), + parent='parent_value', + ) + + +def test_find_lfp_providers_pager(transport_name: str = "grpc"): + client = LfpProvidersServiceClient( + 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.find_lfp_providers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.find_lfp_providers(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, lfpproviders.LfpProvider) + for i in results) +def test_find_lfp_providers_pages(transport_name: str = "grpc"): + client = LfpProvidersServiceClient( + 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.find_lfp_providers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + RuntimeError, + ) + pages = list(client.find_lfp_providers(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_find_lfp_providers_async_pager(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + RuntimeError, + ) + async_pager = await client.find_lfp_providers(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, lfpproviders.LfpProvider) + for i in responses) + + +@pytest.mark.asyncio +async def test_find_lfp_providers_async_pages(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + 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.find_lfp_providers(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", [ + lfpproviders.LinkLfpProviderRequest, + dict, +]) +def test_link_lfp_provider(request_type, transport: str = 'grpc'): + client = LfpProvidersServiceClient( + 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.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.LinkLfpProviderResponse( + ) + response = client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpproviders.LinkLfpProviderRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpproviders.LinkLfpProviderResponse) + + +def test_link_lfp_provider_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 = LfpProvidersServiceClient( + 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 = lfpproviders.LinkLfpProviderRequest( + name='name_value', + external_account_id='external_account_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.link_lfp_provider(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpproviders.LinkLfpProviderRequest( + name='name_value', + external_account_id='external_account_id_value', + ) + +def test_link_lfp_provider_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 = LfpProvidersServiceClient( + 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.link_lfp_provider in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc + request = {} + client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_lfp_provider(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_link_lfp_provider_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 = LfpProvidersServiceAsyncClient( + 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.link_lfp_provider 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.link_lfp_provider] = mock_rpc + + request = {} + await client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.link_lfp_provider(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_link_lfp_provider_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.LinkLfpProviderRequest): + client = LfpProvidersServiceAsyncClient( + 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.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( + )) + response = await client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpproviders.LinkLfpProviderRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpproviders.LinkLfpProviderResponse) + + +@pytest.mark.asyncio +async def test_link_lfp_provider_async_from_dict(): + await test_link_lfp_provider_async(request_type=dict) + +def test_link_lfp_provider_field_headers(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.LinkLfpProviderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value = lfpproviders.LinkLfpProviderResponse() + client.link_lfp_provider(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_link_lfp_provider_field_headers_async(): + client = LfpProvidersServiceAsyncClient( + 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 = lfpproviders.LinkLfpProviderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) + await client.link_lfp_provider(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_link_lfp_provider_flattened(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.LinkLfpProviderResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.link_lfp_provider( + 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_link_lfp_provider_flattened_error(): + client = LfpProvidersServiceClient( + 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.link_lfp_provider( + lfpproviders.LinkLfpProviderRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_link_lfp_provider_flattened_async(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.LinkLfpProviderResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.link_lfp_provider( + 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_link_lfp_provider_flattened_error_async(): + client = LfpProvidersServiceAsyncClient( + 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.link_lfp_provider( + lfpproviders.LinkLfpProviderRequest(), + name='name_value', + ) + + +def test_find_lfp_providers_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 = LfpProvidersServiceClient( + 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.find_lfp_providers in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc + + request = {} + client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_lfp_providers(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_find_lfp_providers_rest_required_fields(request_type=lfpproviders.FindLfpProvidersRequest): + transport_class = transports.LfpProvidersServiceRestTransport + + 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()).find_lfp_providers._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()).find_lfp_providers._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 = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpproviders.FindLfpProvidersResponse() + # 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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_find_lfp_providers_rest_unset_required_fields(): + transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.find_lfp_providers._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_find_lfp_providers_rest_flattened(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.FindLfpProvidersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(**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/accounts/v1/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find" % client.transport._host, args[1]) + + +def test_find_lfp_providers_rest_flattened_error(transport: str = 'rest'): + client = LfpProvidersServiceClient( + 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.find_lfp_providers( + lfpproviders.FindLfpProvidersRequest(), + parent='parent_value', + ) + + +def test_find_lfp_providers_rest_pager(transport: str = 'rest'): + client = LfpProvidersServiceClient( + 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 = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lfpproviders.FindLfpProvidersResponse.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/omnichannelSettings/sample2'} + + pager = client.find_lfp_providers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lfpproviders.LfpProvider) + for i in results) + + pages = list(client.find_lfp_providers(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_link_lfp_provider_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 = LfpProvidersServiceClient( + 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.link_lfp_provider in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc + + request = {} + client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_lfp_provider(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_link_lfp_provider_rest_required_fields(request_type=lfpproviders.LinkLfpProviderRequest): + transport_class = transports.LfpProvidersServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["external_account_id"] = "" + 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()).link_lfp_provider._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["externalAccountId"] = 'external_account_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_lfp_provider._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 "externalAccountId" in jsonified_request + assert jsonified_request["externalAccountId"] == 'external_account_id_value' + + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpproviders.LinkLfpProviderResponse() + # 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 = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_link_lfp_provider_rest_unset_required_fields(): + transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.link_lfp_provider._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "externalAccountId", ))) + + +def test_link_lfp_provider_rest_flattened(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.LinkLfpProviderResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 + # Convert return value to protobuf type + return_value = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(**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/accounts/v1/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider" % client.transport._host, args[1]) + + +def test_link_lfp_provider_rest_flattened_error(transport: str = 'rest'): + client = LfpProvidersServiceClient( + 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.link_lfp_provider( + lfpproviders.LinkLfpProviderRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + 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 = LfpProvidersServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LfpProvidersServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LfpProvidersServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + transports.LfpProvidersServiceRestTransport, +]) +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 = LfpProvidersServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LfpProvidersServiceClient( + 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_find_lfp_providers_empty_call_grpc(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + call.return_value = lfpproviders.FindLfpProvidersResponse() + client.find_lfp_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.FindLfpProvidersRequest() + + 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_link_lfp_provider_empty_call_grpc(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value = lfpproviders.LinkLfpProviderResponse() + client.link_lfp_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.LinkLfpProviderRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LfpProvidersServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LfpProvidersServiceAsyncClient( + 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_find_lfp_providers_empty_call_grpc_asyncio(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( + next_page_token='next_page_token_value', + )) + await client.find_lfp_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.FindLfpProvidersRequest() + + 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_link_lfp_provider_empty_call_grpc_asyncio(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( + )) + await client.link_lfp_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.LinkLfpProviderRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LfpProvidersServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_find_lfp_providers_rest_bad_request(request_type=lfpproviders.FindLfpProvidersRequest): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/omnichannelSettings/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.find_lfp_providers(request) + + +@pytest.mark.parametrize("request_type", [ + lfpproviders.FindLfpProvidersRequest, + dict, +]) +def test_find_lfp_providers_rest_call_success(request_type): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse( + 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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FindLfpProvidersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_find_lfp_providers_rest_interceptors(null_interceptor): + transport = transports.LfpProvidersServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), + ) + client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers") as post, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_find_lfp_providers") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = lfpproviders.FindLfpProvidersRequest.pb(lfpproviders.FindLfpProvidersRequest()) + 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 = lfpproviders.FindLfpProvidersResponse.to_json(lfpproviders.FindLfpProvidersResponse()) + req.return_value.content = return_value + + request = lfpproviders.FindLfpProvidersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpproviders.FindLfpProvidersResponse() + post_with_metadata.return_value = lfpproviders.FindLfpProvidersResponse(), metadata + + client.find_lfp_providers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_link_lfp_provider_rest_bad_request(request_type=lfpproviders.LinkLfpProviderRequest): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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.link_lfp_provider(request) + + +@pytest.mark.parametrize("request_type", [ + lfpproviders.LinkLfpProviderRequest, + dict, +]) +def test_link_lfp_provider_rest_call_success(request_type): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 = lfpproviders.LinkLfpProviderResponse( + ) + + # 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 = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpproviders.LinkLfpProviderResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_link_lfp_provider_rest_interceptors(null_interceptor): + transport = transports.LfpProvidersServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), + ) + client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider") as post, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_link_lfp_provider") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = lfpproviders.LinkLfpProviderRequest.pb(lfpproviders.LinkLfpProviderRequest()) + 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 = lfpproviders.LinkLfpProviderResponse.to_json(lfpproviders.LinkLfpProviderResponse()) + req.return_value.content = return_value + + request = lfpproviders.LinkLfpProviderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpproviders.LinkLfpProviderResponse() + post_with_metadata.return_value = lfpproviders.LinkLfpProviderResponse(), metadata + + client.link_lfp_provider(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = LfpProvidersServiceClient( + 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_find_lfp_providers_empty_call_rest(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + client.find_lfp_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.FindLfpProvidersRequest() + + 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_link_lfp_provider_empty_call_rest(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + client.link_lfp_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.LinkLfpProviderRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LfpProvidersServiceGrpcTransport, + ) + +def test_lfp_providers_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LfpProvidersServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lfp_providers_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LfpProvidersServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'find_lfp_providers', + 'link_lfp_provider', + ) + 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_lfp_providers_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_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpProvidersServiceTransport( + 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_lfp_providers_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_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpProvidersServiceTransport() + adc.assert_called_once() + + +def test_lfp_providers_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) + LfpProvidersServiceClient() + 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.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + ], +) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + transports.LfpProvidersServiceRestTransport, + ], +) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, grpc_helpers), + (transports.LfpProvidersServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +def test_lfp_providers_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_lfp_providers_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.LfpProvidersServiceRestTransport ( + 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_lfp_providers_service_host_no_port(transport_name): + client = LfpProvidersServiceClient( + 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_lfp_providers_service_host_with_port(transport_name): + client = LfpProvidersServiceClient( + 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_lfp_providers_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LfpProvidersServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LfpProvidersServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.find_lfp_providers._session + session2 = client2.transport.find_lfp_providers._session + assert session1 != session2 + session1 = client1.transport.link_lfp_provider._session + session2 = client2.transport.link_lfp_provider._session + assert session1 != session2 +def test_lfp_providers_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpProvidersServiceGrpcTransport( + 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_lfp_providers_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpProvidersServiceGrpcAsyncIOTransport( + 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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +def test_lfp_providers_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_lfp_provider_path(): + account = "squid" + omnichannel_setting = "clam" + lfp_provider = "whelk" + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) + actual = LfpProvidersServiceClient.lfp_provider_path(account, omnichannel_setting, lfp_provider) + assert expected == actual + + +def test_parse_lfp_provider_path(): + expected = { + "account": "octopus", + "omnichannel_setting": "oyster", + "lfp_provider": "nudibranch", + } + path = LfpProvidersServiceClient.lfp_provider_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_lfp_provider_path(path) + assert expected == actual + +def test_omnichannel_setting_path(): + account = "cuttlefish" + omnichannel_setting = "mussel" + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + actual = LfpProvidersServiceClient.omnichannel_setting_path(account, omnichannel_setting) + assert expected == actual + + +def test_parse_omnichannel_setting_path(): + expected = { + "account": "winkle", + "omnichannel_setting": "nautilus", + } + path = LfpProvidersServiceClient.omnichannel_setting_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_omnichannel_setting_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LfpProvidersServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = LfpProvidersServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = LfpProvidersServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = LfpProvidersServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LfpProvidersServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = LfpProvidersServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = LfpProvidersServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = LfpProvidersServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LfpProvidersServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = LfpProvidersServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.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.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LfpProvidersServiceClient.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 = LfpProvidersServiceClient( + 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 = LfpProvidersServiceAsyncClient( + 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 = LfpProvidersServiceClient( + 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 = LfpProvidersServiceClient( + 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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py new file mode 100644 index 000000000000..5ba89b473386 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py @@ -0,0 +1,5231 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import OmnichannelSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import pagers +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import transports +from google.shopping.merchant_accounts_v1.types import omnichannelsettings +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 OmnichannelSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, False) is None + assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert OmnichannelSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert OmnichannelSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert OmnichannelSettingsServiceClient._get_universe_domain(None, None) == OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient(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 = OmnichannelSettingsServiceClient(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", [ + (OmnichannelSettingsServiceClient, "grpc"), + (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, "rest"), +]) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OmnichannelSettingsServiceRestTransport, "rest"), +]) +def test_omnichannel_settings_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", [ + (OmnichannelSettingsServiceClient, "grpc"), + (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, "rest"), +]) +def test_omnichannel_settings_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_omnichannel_settings_service_client_get_transport_class(): + transport = OmnichannelSettingsServiceClient.get_transport_class() + available_transports = [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = OmnichannelSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.OmnichannelSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +def test_omnichannel_settings_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(OmnichannelSettingsServiceClient, '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(OmnichannelSettingsServiceClient, '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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "true"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "false"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "true"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_omnichannel_settings_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", [ + OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceAsyncClient)) +def test_omnichannel_settings_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", [ + OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +def test_omnichannel_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OmnichannelSettingsServiceClient._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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), +]) +def test_omnichannel_settings_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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", None), +]) +def test_omnichannel_settings_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_omnichannel_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OmnichannelSettingsServiceClient( + 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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_omnichannel_settings_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", [ + omnichannelsettings.GetOmnichannelSettingRequest, + dict, +]) +def test_get_omnichannel_setting(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + response = client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.GetOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.GetOmnichannelSettingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_omnichannel_setting(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.GetOmnichannelSettingRequest( + name='name_value', + ) + +def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc + request = {} + client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_omnichannel_setting(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_get_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( + 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.get_omnichannel_setting in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_omnichannel_setting] = mock_rpc + + request = {} + await client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_omnichannel_setting(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_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.GetOmnichannelSettingRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + response = await client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.GetOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.asyncio +async def test_get_omnichannel_setting_async_from_dict(): + await test_get_omnichannel_setting_async(request_type=dict) + +def test_get_omnichannel_setting_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.GetOmnichannelSettingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.get_omnichannel_setting(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_get_omnichannel_setting_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.GetOmnichannelSettingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + await client.get_omnichannel_setting(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_get_omnichannel_setting_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_omnichannel_setting( + 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_get_omnichannel_setting_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting( + omnichannelsettings.GetOmnichannelSettingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_omnichannel_setting_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_omnichannel_setting( + 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_get_omnichannel_setting_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.get_omnichannel_setting( + omnichannelsettings.GetOmnichannelSettingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.ListOmnichannelSettingsRequest, + dict, +]) +def test_list_omnichannel_settings(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.ListOmnichannelSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOmnichannelSettingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.ListOmnichannelSettingsRequest( + 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_omnichannel_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_omnichannel_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.ListOmnichannelSettingsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( + 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_omnichannel_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_omnichannel_settings] = mock_rpc + request = {} + client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_omnichannel_settings(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_omnichannel_settings_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 = OmnichannelSettingsServiceAsyncClient( + 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_omnichannel_settings 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_omnichannel_settings] = mock_rpc + + request = {} + await client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_omnichannel_settings(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_omnichannel_settings_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.ListOmnichannelSettingsRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.ListOmnichannelSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOmnichannelSettingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_omnichannel_settings_async_from_dict(): + await test_list_omnichannel_settings_async(request_type=dict) + +def test_list_omnichannel_settings_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.ListOmnichannelSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + client.list_omnichannel_settings(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_omnichannel_settings_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.ListOmnichannelSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) + await client.list_omnichannel_settings(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_omnichannel_settings_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_omnichannel_settings( + 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_omnichannel_settings_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings( + omnichannelsettings.ListOmnichannelSettingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_omnichannel_settings_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_omnichannel_settings( + 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_omnichannel_settings_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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_omnichannel_settings( + omnichannelsettings.ListOmnichannelSettingsRequest(), + parent='parent_value', + ) + + +def test_list_omnichannel_settings_pager(transport_name: str = "grpc"): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_omnichannel_settings(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, omnichannelsettings.OmnichannelSetting) + for i in results) +def test_list_omnichannel_settings_pages(transport_name: str = "grpc"): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + RuntimeError, + ) + pages = list(client.list_omnichannel_settings(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_omnichannel_settings_async_pager(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_omnichannel_settings(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, omnichannelsettings.OmnichannelSetting) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_omnichannel_settings_async_pages(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + 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_omnichannel_settings(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", [ + omnichannelsettings.CreateOmnichannelSettingRequest, + dict, +]) +def test_create_omnichannel_setting(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + response = client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.CreateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.CreateOmnichannelSettingRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_omnichannel_setting(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.CreateOmnichannelSettingRequest( + parent='parent_value', + ) + +def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc + request = {} + client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_omnichannel_setting(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_create_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( + 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.create_omnichannel_setting in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_omnichannel_setting] = mock_rpc + + request = {} + await client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_omnichannel_setting(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_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.CreateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + response = await client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.CreateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.asyncio +async def test_create_omnichannel_setting_async_from_dict(): + await test_create_omnichannel_setting_async(request_type=dict) + +def test_create_omnichannel_setting_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.CreateOmnichannelSettingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.create_omnichannel_setting(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_create_omnichannel_setting_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.CreateOmnichannelSettingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + await client.create_omnichannel_setting(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_create_omnichannel_setting_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_omnichannel_setting( + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + + +def test_create_omnichannel_setting_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting( + omnichannelsettings.CreateOmnichannelSettingRequest(), + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_omnichannel_setting_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_omnichannel_setting( + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_omnichannel_setting_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.create_omnichannel_setting( + omnichannelsettings.CreateOmnichannelSettingRequest(), + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.UpdateOmnichannelSettingRequest, + dict, +]) +def test_update_omnichannel_setting(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + response = client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.UpdateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.UpdateOmnichannelSettingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_omnichannel_setting(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.UpdateOmnichannelSettingRequest( + ) + +def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc + request = {} + client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_omnichannel_setting(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_update_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( + 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.update_omnichannel_setting in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_omnichannel_setting] = mock_rpc + + request = {} + await client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_omnichannel_setting(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_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + response = await client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.UpdateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_async_from_dict(): + await test_update_omnichannel_setting_async(request_type=dict) + +def test_update_omnichannel_setting_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.UpdateOmnichannelSettingRequest() + + request.omnichannel_setting.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.update_omnichannel_setting(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', + 'omnichannel_setting.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.UpdateOmnichannelSettingRequest() + + request.omnichannel_setting.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + await client.update_omnichannel_setting(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', + 'omnichannel_setting.name=name_value', + ) in kw['metadata'] + + +def test_update_omnichannel_setting_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_omnichannel_setting( + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_omnichannel_setting_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting( + omnichannelsettings.UpdateOmnichannelSettingRequest(), + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_omnichannel_setting( + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.update_omnichannel_setting( + omnichannelsettings.UpdateOmnichannelSettingRequest(), + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.RequestInventoryVerificationRequest, + dict, +]) +def test_request_inventory_verification(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse( + ) + response = client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.RequestInventoryVerificationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + + +def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.RequestInventoryVerificationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.request_inventory_verification(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.RequestInventoryVerificationRequest( + name='name_value', + ) + +def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( + 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.request_inventory_verification in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc + request = {} + client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.request_inventory_verification(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_request_inventory_verification_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 = OmnichannelSettingsServiceAsyncClient( + 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.request_inventory_verification 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.request_inventory_verification] = mock_rpc + + request = {} + await client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.request_inventory_verification(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_request_inventory_verification_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.RequestInventoryVerificationRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( + )) + response = await client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.RequestInventoryVerificationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + + +@pytest.mark.asyncio +async def test_request_inventory_verification_async_from_dict(): + await test_request_inventory_verification_async(request_type=dict) + +def test_request_inventory_verification_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.RequestInventoryVerificationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + client.request_inventory_verification(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_request_inventory_verification_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.RequestInventoryVerificationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) + await client.request_inventory_verification(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_request_inventory_verification_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.request_inventory_verification( + 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_request_inventory_verification_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.request_inventory_verification( + omnichannelsettings.RequestInventoryVerificationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_request_inventory_verification_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.request_inventory_verification( + 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_request_inventory_verification_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.request_inventory_verification( + omnichannelsettings.RequestInventoryVerificationRequest(), + name='name_value', + ) + + +def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc + + request = {} + client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_omnichannel_setting(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_get_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.GetOmnichannelSettingRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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()).get_omnichannel_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_omnichannel_setting._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.OmnichannelSetting() + # 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 = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_omnichannel_setting_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_omnichannel_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_omnichannel_setting_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.OmnichannelSetting() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(**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/accounts/v1/{name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) + + +def test_get_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_omnichannel_setting( + omnichannelsettings.GetOmnichannelSettingRequest(), + name='name_value', + ) + + +def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( + 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_omnichannel_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_omnichannel_settings] = mock_rpc + + request = {} + client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_omnichannel_settings(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_omnichannel_settings_rest_required_fields(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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_omnichannel_settings._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_omnichannel_settings._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + # 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_omnichannel_settings_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_omnichannel_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_omnichannel_settings_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.ListOmnichannelSettingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(**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/accounts/v1/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) + + +def test_list_omnichannel_settings_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings( + omnichannelsettings.ListOmnichannelSettingsRequest(), + parent='parent_value', + ) + + +def test_list_omnichannel_settings_rest_pager(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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 = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(omnichannelsettings.ListOmnichannelSettingsResponse.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'} + + pager = client.list_omnichannel_settings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, omnichannelsettings.OmnichannelSetting) + for i in results) + + pages = list(client.list_omnichannel_settings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc + + request = {} + client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_omnichannel_setting(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_create_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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()).create_omnichannel_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_omnichannel_setting._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.OmnichannelSetting() + # 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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_omnichannel_setting_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_omnichannel_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "omnichannelSetting", ))) + + +def test_create_omnichannel_setting_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.OmnichannelSetting() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(**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/accounts/v1/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) + + +def test_create_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting( + omnichannelsettings.CreateOmnichannelSettingRequest(), + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + ) + + +def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc + + request = {} + client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_omnichannel_setting(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_update_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.OmnichannelSetting() + # 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': "patch", + '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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_omnichannel_setting_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_omnichannel_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("omnichannelSetting", "updateMask", ))) + + +def test_update_omnichannel_setting_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.OmnichannelSetting() + + # get arguments that satisfy an http rule for this method + sample_request = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(**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/accounts/v1/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) + + +def test_update_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting( + omnichannelsettings.UpdateOmnichannelSettingRequest(), + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( + 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.request_inventory_verification in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc + + request = {} + client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.request_inventory_verification(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_request_inventory_verification_rest_required_fields(request_type=omnichannelsettings.RequestInventoryVerificationRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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()).request_inventory_verification._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()).request_inventory_verification._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.RequestInventoryVerificationResponse() + # 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 = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_request_inventory_verification_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.request_inventory_verification._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_request_inventory_verification_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.RequestInventoryVerificationResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(**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/accounts/v1/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification" % client.transport._host, args[1]) + + +def test_request_inventory_verification_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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.request_inventory_verification( + omnichannelsettings.RequestInventoryVerificationRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + 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 = OmnichannelSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OmnichannelSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OmnichannelSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + transports.OmnichannelSettingsServiceRestTransport, +]) +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 = OmnichannelSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OmnichannelSettingsServiceClient( + 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_get_omnichannel_setting_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.get_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.GetOmnichannelSettingRequest() + + 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_list_omnichannel_settings_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + client.list_omnichannel_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() + + 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_create_omnichannel_setting_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.create_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() + + 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_update_omnichannel_setting_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.update_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() + + 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_request_inventory_verification_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + client.request_inventory_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.RequestInventoryVerificationRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OmnichannelSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + 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_get_omnichannel_setting_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + await client.get_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.GetOmnichannelSettingRequest() + + 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_list_omnichannel_settings_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token='next_page_token_value', + )) + await client.list_omnichannel_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() + + 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_create_omnichannel_setting_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + await client.create_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() + + 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_update_omnichannel_setting_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + await client.update_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() + + 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_request_inventory_verification_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( + )) + await client.request_inventory_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.RequestInventoryVerificationRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OmnichannelSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.GetOmnichannelSettingRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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.get_omnichannel_setting(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.GetOmnichannelSettingRequest, + dict, +]) +def test_get_omnichannel_setting_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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 = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + + # 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 = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_omnichannel_setting_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_get_omnichannel_setting") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.GetOmnichannelSettingRequest.pb(omnichannelsettings.GetOmnichannelSettingRequest()) + 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + req.return_value.content = return_value + + request = omnichannelsettings.GetOmnichannelSettingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.OmnichannelSetting() + post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + + client.get_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_omnichannel_settings_rest_bad_request(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_omnichannel_settings(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.ListOmnichannelSettingsRequest, + dict, +]) +def test_list_omnichannel_settings_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.ListOmnichannelSettingsResponse( + 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOmnichannelSettingsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_omnichannel_settings_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_list_omnichannel_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.ListOmnichannelSettingsRequest.pb(omnichannelsettings.ListOmnichannelSettingsRequest()) + 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 = omnichannelsettings.ListOmnichannelSettingsResponse.to_json(omnichannelsettings.ListOmnichannelSettingsResponse()) + req.return_value.content = return_value + + request = omnichannelsettings.ListOmnichannelSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + post_with_metadata.return_value = omnichannelsettings.ListOmnichannelSettingsResponse(), metadata + + client.list_omnichannel_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_omnichannel_setting(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.CreateOmnichannelSettingRequest, + dict, +]) +def test_create_omnichannel_setting_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["omnichannel_setting"] = {'name': 'name_value', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 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 = omnichannelsettings.CreateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] + + 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["omnichannel_setting"].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["omnichannel_setting"][field])): + del request_init["omnichannel_setting"][field][i][subfield] + else: + del request_init["omnichannel_setting"][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 = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + + # 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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_omnichannel_setting_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_create_omnichannel_setting") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.CreateOmnichannelSettingRequest.pb(omnichannelsettings.CreateOmnichannelSettingRequest()) + 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + req.return_value.content = return_value + + request = omnichannelsettings.CreateOmnichannelSettingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.OmnichannelSetting() + post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + + client.create_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/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.update_omnichannel_setting(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.UpdateOmnichannelSettingRequest, + dict, +]) +def test_update_omnichannel_setting_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} + request_init["omnichannel_setting"] = {'name': 'accounts/sample1/omnichannelSettings/sample2', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 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 = omnichannelsettings.UpdateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] + + 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["omnichannel_setting"].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["omnichannel_setting"][field])): + del request_init["omnichannel_setting"][field][i][subfield] + else: + del request_init["omnichannel_setting"][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 = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + + # 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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_omnichannel_setting_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_update_omnichannel_setting") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.UpdateOmnichannelSettingRequest.pb(omnichannelsettings.UpdateOmnichannelSettingRequest()) + 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + req.return_value.content = return_value + + request = omnichannelsettings.UpdateOmnichannelSettingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.OmnichannelSetting() + post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + + client.update_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_request_inventory_verification_rest_bad_request(request_type=omnichannelsettings.RequestInventoryVerificationRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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.request_inventory_verification(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.RequestInventoryVerificationRequest, + dict, +]) +def test_request_inventory_verification_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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 = omnichannelsettings.RequestInventoryVerificationResponse( + ) + + # 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 = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_request_inventory_verification_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_request_inventory_verification") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.RequestInventoryVerificationRequest.pb(omnichannelsettings.RequestInventoryVerificationRequest()) + 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 = omnichannelsettings.RequestInventoryVerificationResponse.to_json(omnichannelsettings.RequestInventoryVerificationResponse()) + req.return_value.content = return_value + + request = omnichannelsettings.RequestInventoryVerificationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + post_with_metadata.return_value = omnichannelsettings.RequestInventoryVerificationResponse(), metadata + + client.request_inventory_verification(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = OmnichannelSettingsServiceClient( + 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_get_omnichannel_setting_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + client.get_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.GetOmnichannelSettingRequest() + + 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_list_omnichannel_settings_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + client.list_omnichannel_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() + + 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_create_omnichannel_setting_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + client.create_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() + + 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_update_omnichannel_setting_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + client.update_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() + + 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_request_inventory_verification_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + client.request_inventory_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.RequestInventoryVerificationRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OmnichannelSettingsServiceGrpcTransport, + ) + +def test_omnichannel_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OmnichannelSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_omnichannel_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OmnichannelSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_omnichannel_setting', + 'list_omnichannel_settings', + 'create_omnichannel_setting', + 'update_omnichannel_setting', + 'request_inventory_verification', + ) + 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_omnichannel_settings_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_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OmnichannelSettingsServiceTransport( + 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_omnichannel_settings_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_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OmnichannelSettingsServiceTransport() + adc.assert_called_once() + + +def test_omnichannel_settings_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) + OmnichannelSettingsServiceClient() + 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.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + transports.OmnichannelSettingsServiceRestTransport, + ], +) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, grpc_helpers), + (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +def test_omnichannel_settings_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_omnichannel_settings_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.OmnichannelSettingsServiceRestTransport ( + 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_omnichannel_settings_service_host_no_port(transport_name): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings_service_host_with_port(transport_name): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OmnichannelSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OmnichannelSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_omnichannel_setting._session + session2 = client2.transport.get_omnichannel_setting._session + assert session1 != session2 + session1 = client1.transport.list_omnichannel_settings._session + session2 = client2.transport.list_omnichannel_settings._session + assert session1 != session2 + session1 = client1.transport.create_omnichannel_setting._session + session2 = client2.transport.create_omnichannel_setting._session + assert session1 != session2 + session1 = client1.transport.update_omnichannel_setting._session + session2 = client2.transport.update_omnichannel_setting._session + assert session1 != session2 + session1 = client1.transport.request_inventory_verification._session + session2 = client2.transport.request_inventory_verification._session + assert session1 != session2 +def test_omnichannel_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + 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_omnichannel_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OmnichannelSettingsServiceGrpcAsyncIOTransport( + 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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +def test_omnichannel_settings_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = OmnichannelSettingsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = OmnichannelSettingsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_account_path(path) + assert expected == actual + +def test_omnichannel_setting_path(): + account = "whelk" + omnichannel_setting = "octopus" + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + actual = OmnichannelSettingsServiceClient.omnichannel_setting_path(account, omnichannel_setting) + assert expected == actual + + +def test_parse_omnichannel_setting_path(): + expected = { + "account": "oyster", + "omnichannel_setting": "nudibranch", + } + path = OmnichannelSettingsServiceClient.omnichannel_setting_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_omnichannel_setting_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OmnichannelSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = OmnichannelSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = OmnichannelSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = OmnichannelSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OmnichannelSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = OmnichannelSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = OmnichannelSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = OmnichannelSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = OmnichannelSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.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.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient( + 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 = OmnichannelSettingsServiceAsyncClient( + 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 = OmnichannelSettingsServiceClient( + 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 = OmnichannelSettingsServiceClient( + 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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py new file mode 100644 index 000000000000..fba11b1b3556 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py @@ -0,0 +1,4561 @@ +# -*- 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.shopping.merchant_accounts_v1.services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.online_return_policy_service import OnlineReturnPolicyServiceClient +from google.shopping.merchant_accounts_v1.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1.services.online_return_policy_service import transports +from google.shopping.merchant_accounts_v1.types import online_return_policy +from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy +from google.shopping.type.types import types +from google.type import date_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 OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(None) is None + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, False) is None + assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert OnlineReturnPolicyServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert OnlineReturnPolicyServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert OnlineReturnPolicyServiceClient._get_universe_domain(None, None) == OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient(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 = OnlineReturnPolicyServiceClient(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", [ + (OnlineReturnPolicyServiceClient, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, "rest"), +]) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +def test_online_return_policy_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", [ + (OnlineReturnPolicyServiceClient, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, "rest"), +]) +def test_online_return_policy_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_online_return_policy_service_client_get_transport_class(): + transport = OnlineReturnPolicyServiceClient.get_transport_class() + available_transports = [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceRestTransport, + ] + assert transport in available_transports + + transport = OnlineReturnPolicyServiceClient.get_transport_class("grpc") + assert transport == transports.OnlineReturnPolicyServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +def test_online_return_policy_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(OnlineReturnPolicyServiceClient, '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(OnlineReturnPolicyServiceClient, '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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "true"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "false"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "true"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_online_return_policy_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", [ + OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceAsyncClient)) +def test_online_return_policy_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", [ + OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +def test_online_return_policy_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OnlineReturnPolicyServiceClient._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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +def test_online_return_policy_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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", None), +]) +def test_online_return_policy_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_online_return_policy_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OnlineReturnPolicyServiceClient( + 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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_online_return_policy_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", [ + online_return_policy.GetOnlineReturnPolicyRequest, + dict, +]) +def test_get_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + response = client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = online_return_policy.GetOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.GetOnlineReturnPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == online_return_policy.GetOnlineReturnPolicyRequest( + name='name_value', + ) + +def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc + request = {} + client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_online_return_policy(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_get_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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.get_online_return_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_online_return_policy] = mock_rpc + + request = {} + await client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_online_return_policy(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_get_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.GetOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + response = await client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = online_return_policy.GetOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.asyncio +async def test_get_online_return_policy_async_from_dict(): + await test_get_online_return_policy_async(request_type=dict) + +def test_get_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.GetOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value = online_return_policy.OnlineReturnPolicy() + client.get_online_return_policy(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_get_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = online_return_policy.GetOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) + await client.get_online_return_policy(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_get_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.OnlineReturnPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_online_return_policy( + 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_get_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy( + online_return_policy.GetOnlineReturnPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.OnlineReturnPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_online_return_policy( + 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_get_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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.get_online_return_policy( + online_return_policy.GetOnlineReturnPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.ListOnlineReturnPoliciesRequest, + dict, +]) +def test_list_online_return_policies(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = online_return_policy.ListOnlineReturnPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.ListOnlineReturnPoliciesRequest( + 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_online_return_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_online_return_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == online_return_policy.ListOnlineReturnPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policies] = mock_rpc + request = {} + client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_online_return_policies(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_online_return_policies_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 = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policies 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_online_return_policies] = mock_rpc + + request = {} + await client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_online_return_policies(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_online_return_policies_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.ListOnlineReturnPoliciesRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = online_return_policy.ListOnlineReturnPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOnlineReturnPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_online_return_policies_async_from_dict(): + await test_list_online_return_policies_async(request_type=dict) + +def test_list_online_return_policies_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.ListOnlineReturnPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + client.list_online_return_policies(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_online_return_policies_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = online_return_policy.ListOnlineReturnPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) + await client.list_online_return_policies(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_online_return_policies_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_online_return_policies( + 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_online_return_policies_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies( + online_return_policy.ListOnlineReturnPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_online_return_policies_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_online_return_policies( + 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_online_return_policies_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policies( + online_return_policy.ListOnlineReturnPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_online_return_policies_pager(transport_name: str = "grpc"): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_online_return_policies(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, online_return_policy.OnlineReturnPolicy) + for i in results) +def test_list_online_return_policies_pages(transport_name: str = "grpc"): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_online_return_policies(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_online_return_policies_async_pager(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_online_return_policies(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, online_return_policy.OnlineReturnPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_online_return_policies_async_pages(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + 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_online_return_policies(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", [ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + dict, +]) +def test_create_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + response = client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_online_return_policy.CreateOnlineReturnPolicyRequest( + parent='parent_value', + ) + +def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc + request = {} + client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_online_return_policy(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_create_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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.create_online_return_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_online_return_policy] = mock_rpc + + request = {} + await client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_online_return_policy(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_create_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + response = await client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.asyncio +async def test_create_online_return_policy_async_from_dict(): + await test_create_online_return_policy_async(request_type=dict) + +def test_create_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + client.create_online_return_policy(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_create_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + await client.create_online_return_policy(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_create_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_online_return_policy( + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].online_return_policy + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + assert arg == mock_val + + +def test_create_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_online_return_policy( + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].online_return_policy + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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.create_online_return_policy( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.DeleteOnlineReturnPolicyRequest, + dict, +]) +def test_delete_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = online_return_policy.DeleteOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == online_return_policy.DeleteOnlineReturnPolicyRequest( + name='name_value', + ) + +def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policy] = mock_rpc + request = {} + client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_online_return_policy(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_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policy 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_online_return_policy] = mock_rpc + + request = {} + await client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_online_return_policy(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_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = online_return_policy.DeleteOnlineReturnPolicyRequest() + 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_online_return_policy_async_from_dict(): + await test_delete_online_return_policy_async(request_type=dict) + +def test_delete_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value = None + client.delete_online_return_policy(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_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_online_return_policy(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_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__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_online_return_policy( + 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_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy( + online_return_policy.DeleteOnlineReturnPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__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_online_return_policy( + 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_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policy( + online_return_policy.DeleteOnlineReturnPolicyRequest(), + name='name_value', + ) + + +def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc + + request = {} + client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_online_return_policy(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_get_online_return_policy_rest_required_fields(request_type=online_return_policy.GetOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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()).get_online_return_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_online_return_policy._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 = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = online_return_policy.OnlineReturnPolicy() + # 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 = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.OnlineReturnPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(**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/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + + +def test_get_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_online_return_policy( + online_return_policy.GetOnlineReturnPolicyRequest(), + name='name_value', + ) + + +def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policies] = mock_rpc + + request = {} + client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_online_return_policies(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_online_return_policies_rest_required_fields(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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_online_return_policies._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_online_return_policies._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 = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + # 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_online_return_policies_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_online_return_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_online_return_policies_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.ListOnlineReturnPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(**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/accounts/v1/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) + + +def test_list_online_return_policies_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies( + online_return_policy.ListOnlineReturnPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_online_return_policies_rest_pager(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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 = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(online_return_policy.ListOnlineReturnPoliciesResponse.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'} + + pager = client.list_online_return_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, online_return_policy.OnlineReturnPolicy) + for i in results) + + pages = list(client.list_online_return_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc + + request = {} + client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_online_return_policy(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_create_online_return_policy_rest_required_fields(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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()).create_online_return_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_online_return_policy._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 = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_online_return_policy.OnlineReturnPolicy() + # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "onlineReturnPolicy", ))) + + +def test_create_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.OnlineReturnPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(**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/accounts/v1/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) + + +def test_create_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + ) + + +def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policy] = mock_rpc + + request = {} + client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_online_return_policy(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_online_return_policy_rest_required_fields(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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_online_return_policy._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_online_return_policy._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 = OnlineReturnPolicyServiceClient( + 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_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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/onlineReturnPolicies/sample2'} + + # 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_online_return_policy(**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/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy( + online_return_policy.DeleteOnlineReturnPolicyRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + 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 = OnlineReturnPolicyServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OnlineReturnPolicyServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + transports.OnlineReturnPolicyServiceRestTransport, +]) +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 = OnlineReturnPolicyServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OnlineReturnPolicyServiceClient( + 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_get_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value = online_return_policy.OnlineReturnPolicy() + client.get_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.GetOnlineReturnPolicyRequest() + + 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_list_online_return_policies_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + client.list_online_return_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() + + 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_create_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + client.create_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + 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_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value = None + client.delete_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OnlineReturnPolicyServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + 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_get_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + await client.get_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.GetOnlineReturnPolicyRequest() + + 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_list_online_return_policies_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_online_return_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() + + 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_create_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + await client.create_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + 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_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OnlineReturnPolicyServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_online_return_policy_rest_bad_request(request_type=online_return_policy.GetOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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.get_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.GetOnlineReturnPolicyRequest, + dict, +]) +def test_get_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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 = online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + + # 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 = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_get_online_return_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = online_return_policy.GetOnlineReturnPolicyRequest.pb(online_return_policy.GetOnlineReturnPolicyRequest()) + 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 = online_return_policy.OnlineReturnPolicy.to_json(online_return_policy.OnlineReturnPolicy()) + req.return_value.content = return_value + + request = online_return_policy.GetOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = online_return_policy.OnlineReturnPolicy() + post_with_metadata.return_value = online_return_policy.OnlineReturnPolicy(), metadata + + client.get_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_online_return_policies_rest_bad_request(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_online_return_policies(request) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.ListOnlineReturnPoliciesRequest, + dict, +]) +def test_list_online_return_policies_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = online_return_policy.ListOnlineReturnPoliciesResponse( + 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_online_return_policies_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_list_online_return_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = online_return_policy.ListOnlineReturnPoliciesRequest.pb(online_return_policy.ListOnlineReturnPoliciesRequest()) + 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 = online_return_policy.ListOnlineReturnPoliciesResponse.to_json(online_return_policy.ListOnlineReturnPoliciesResponse()) + req.return_value.content = return_value + + request = online_return_policy.ListOnlineReturnPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + post_with_metadata.return_value = online_return_policy.ListOnlineReturnPoliciesResponse(), metadata + + client.list_online_return_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_online_return_policy_rest_bad_request(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + dict, +]) +def test_create_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["online_return_policy"] = {'name': 'name_value', 'return_policy_id': 'return_policy_id_value', 'label': 'label_value', 'countries': ['countries_value1', 'countries_value2'], 'policy': {'type_': 1, 'days': 433}, 'seasonal_overrides': [{'return_days': 1200, 'return_until_date': {'year': 433, 'month': 550, 'day': 318}, 'label': 'label_value', 'start_date': {}, 'end_date': {}}], 'restocking_fee': {'fixed_fee': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'micro_percent': 1386}, 'return_methods': [1], 'item_conditions': [1], 'return_shipping_fee': {'type_': 1, 'fixed_fee': {}}, 'return_policy_uri': 'return_policy_uri_value', 'accept_defective_only': True, 'process_refund_days': 2034, 'accept_exchange': True, 'return_label_source': 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.meta.fields["online_return_policy"] + + 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["online_return_policy"].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["online_return_policy"][field])): + del request_init["online_return_policy"][field][i][subfield] + else: + del request_init["online_return_policy"][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 = gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + + # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_create_online_return_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb(gsma_online_return_policy.CreateOnlineReturnPolicyRequest()) + 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 = gsma_online_return_policy.OnlineReturnPolicy.to_json(gsma_online_return_policy.OnlineReturnPolicy()) + req.return_value.content = return_value + + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_online_return_policy.OnlineReturnPolicy() + post_with_metadata.return_value = gsma_online_return_policy.OnlineReturnPolicy(), metadata + + client.create_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_online_return_policy_rest_bad_request(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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.delete_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.DeleteOnlineReturnPolicyRequest, + dict, +]) +def test_delete_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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 = 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_online_return_policy(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_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "pre_delete_online_return_policy") as pre: + pre.assert_not_called() + pb_message = online_return_policy.DeleteOnlineReturnPolicyRequest.pb(online_return_policy.DeleteOnlineReturnPolicyRequest()) + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = OnlineReturnPolicyServiceClient( + 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_get_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + client.get_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.GetOnlineReturnPolicyRequest() + + 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_list_online_return_policies_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + client.list_online_return_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() + + 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_create_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + client.create_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + 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_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + client.delete_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OnlineReturnPolicyServiceGrpcTransport, + ) + +def test_online_return_policy_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OnlineReturnPolicyServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_online_return_policy_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OnlineReturnPolicyServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_online_return_policy', + 'list_online_return_policies', + 'create_online_return_policy', + 'delete_online_return_policy', + ) + 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_online_return_policy_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_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OnlineReturnPolicyServiceTransport( + 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_online_return_policy_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_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OnlineReturnPolicyServiceTransport() + adc.assert_called_once() + + +def test_online_return_policy_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) + OnlineReturnPolicyServiceClient() + 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.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + ], +) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + transports.OnlineReturnPolicyServiceRestTransport, + ], +) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, grpc_helpers), + (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +def test_online_return_policy_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_online_return_policy_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.OnlineReturnPolicyServiceRestTransport ( + 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_online_return_policy_service_host_no_port(transport_name): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy_service_host_with_port(transport_name): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OnlineReturnPolicyServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OnlineReturnPolicyServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_online_return_policy._session + session2 = client2.transport.get_online_return_policy._session + assert session1 != session2 + session1 = client1.transport.list_online_return_policies._session + session2 = client2.transport.list_online_return_policies._session + assert session1 != session2 + session1 = client1.transport.create_online_return_policy._session + session2 = client2.transport.create_online_return_policy._session + assert session1 != session2 + session1 = client1.transport.delete_online_return_policy._session + session2 = client2.transport.delete_online_return_policy._session + assert session1 != session2 +def test_online_return_policy_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + 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_online_return_policy_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport( + 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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +def test_online_return_policy_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_online_return_policy_path(): + account = "squid" + return_policy = "clam" + expected = "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) + actual = OnlineReturnPolicyServiceClient.online_return_policy_path(account, return_policy) + assert expected == actual + + +def test_parse_online_return_policy_path(): + expected = { + "account": "whelk", + "return_policy": "octopus", + } + path = OnlineReturnPolicyServiceClient.online_return_policy_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_online_return_policy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OnlineReturnPolicyServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = OnlineReturnPolicyServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = OnlineReturnPolicyServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = OnlineReturnPolicyServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OnlineReturnPolicyServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = OnlineReturnPolicyServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = OnlineReturnPolicyServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = OnlineReturnPolicyServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = OnlineReturnPolicyServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = OnlineReturnPolicyServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.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.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OnlineReturnPolicyServiceClient.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 = OnlineReturnPolicyServiceClient( + 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 = OnlineReturnPolicyServiceAsyncClient( + 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 = OnlineReturnPolicyServiceClient( + 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 = OnlineReturnPolicyServiceClient( + 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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py new file mode 100644 index 000000000000..1762b7ef772c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py @@ -0,0 +1,4435 @@ +# -*- 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.shopping.merchant_accounts_v1.services.programs_service import ProgramsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.programs_service import ProgramsServiceClient +from google.shopping.merchant_accounts_v1.services.programs_service import pagers +from google.shopping.merchant_accounts_v1.services.programs_service import transports +from google.shopping.merchant_accounts_v1.types import programs +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 ProgramsServiceClient._get_default_mtls_endpoint(None) is None + assert ProgramsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ProgramsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ProgramsServiceClient._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 ProgramsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ProgramsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ProgramsServiceClient._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 ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, False) is None + assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ProgramsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProgramsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ProgramsServiceClient._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 ProgramsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProgramsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProgramsServiceClient._get_universe_domain(None, None) == ProgramsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ProgramsServiceClient._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 = ProgramsServiceClient(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 = ProgramsServiceClient(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", [ + (ProgramsServiceClient, "grpc"), + (ProgramsServiceAsyncClient, "grpc_asyncio"), + (ProgramsServiceClient, "rest"), +]) +def test_programs_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.ProgramsServiceGrpcTransport, "grpc"), + (transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProgramsServiceRestTransport, "rest"), +]) +def test_programs_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", [ + (ProgramsServiceClient, "grpc"), + (ProgramsServiceAsyncClient, "grpc_asyncio"), + (ProgramsServiceClient, "rest"), +]) +def test_programs_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_programs_service_client_get_transport_class(): + transport = ProgramsServiceClient.get_transport_class() + available_transports = [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceRestTransport, + ] + assert transport in available_transports + + transport = ProgramsServiceClient.get_transport_class("grpc") + assert transport == transports.ProgramsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), +]) +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +def test_programs_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(ProgramsServiceClient, '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(ProgramsServiceClient, '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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "true"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "false"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "true"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_programs_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", [ + ProgramsServiceClient, ProgramsServiceAsyncClient +]) +@mock.patch.object(ProgramsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceAsyncClient)) +def test_programs_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", [ + ProgramsServiceClient, ProgramsServiceAsyncClient +]) +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +def test_programs_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProgramsServiceClient._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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), +]) +def test_programs_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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", None), +]) +def test_programs_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_programs_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProgramsServiceClient( + 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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_programs_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", [ + programs.GetProgramRequest, + dict, +]) +def test_get_program(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + ) + response = client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.GetProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +def test_get_program_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 = ProgramsServiceClient( + 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 = programs.GetProgramRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_program(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.GetProgramRequest( + name='name_value', + ) + +def test_get_program_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 = ProgramsServiceClient( + 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.get_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_program] = mock_rpc + request = {} + client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_program(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_get_program_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 = ProgramsServiceAsyncClient( + 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.get_program in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_program] = mock_rpc + + request = {} + await client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_program(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_get_program_async(transport: str = 'grpc_asyncio', request_type=programs.GetProgramRequest): + client = ProgramsServiceAsyncClient( + 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.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + response = await client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.GetProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.asyncio +async def test_get_program_async_from_dict(): + await test_get_program_async(request_type=dict) + +def test_get_program_field_headers(): + client = ProgramsServiceClient( + 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 = programs.GetProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value = programs.Program() + client.get_program(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_get_program_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.GetProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + await client.get_program(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_get_program_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_program( + 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_get_program_flattened_error(): + client = ProgramsServiceClient( + 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.get_program( + programs.GetProgramRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_program_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_program( + 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_get_program_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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.get_program( + programs.GetProgramRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + programs.ListProgramsRequest, + dict, +]) +def test_list_programs(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.ListProgramsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.ListProgramsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProgramsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_programs_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 = ProgramsServiceClient( + 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 = programs.ListProgramsRequest( + 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_programs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_programs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.ListProgramsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_programs_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 = ProgramsServiceClient( + 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_programs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_programs] = mock_rpc + request = {} + client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_programs(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_programs_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 = ProgramsServiceAsyncClient( + 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_programs 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_programs] = mock_rpc + + request = {} + await client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_programs(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_programs_async(transport: str = 'grpc_asyncio', request_type=programs.ListProgramsRequest): + client = ProgramsServiceAsyncClient( + 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_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.ListProgramsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProgramsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_programs_async_from_dict(): + await test_list_programs_async(request_type=dict) + +def test_list_programs_field_headers(): + client = ProgramsServiceClient( + 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 = programs.ListProgramsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + call.return_value = programs.ListProgramsResponse() + client.list_programs(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_programs_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.ListProgramsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) + await client.list_programs(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_programs_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.ListProgramsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_programs( + 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_programs_flattened_error(): + client = ProgramsServiceClient( + 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_programs( + programs.ListProgramsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_programs_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.ListProgramsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_programs( + 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_programs_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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_programs( + programs.ListProgramsRequest(), + parent='parent_value', + ) + + +def test_list_programs_pager(transport_name: str = "grpc"): + client = ProgramsServiceClient( + 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_programs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_programs(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, programs.Program) + for i in results) +def test_list_programs_pages(transport_name: str = "grpc"): + client = ProgramsServiceClient( + 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_programs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + RuntimeError, + ) + pages = list(client.list_programs(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_programs_async_pager(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_programs(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, programs.Program) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_programs_async_pages(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + 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_programs(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", [ + programs.EnableProgramRequest, + dict, +]) +def test_enable_program(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + ) + response = client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.EnableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +def test_enable_program_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 = ProgramsServiceClient( + 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 = programs.EnableProgramRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.enable_program(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.EnableProgramRequest( + name='name_value', + ) + +def test_enable_program_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 = ProgramsServiceClient( + 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.enable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc + request = {} + client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enable_program(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_enable_program_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 = ProgramsServiceAsyncClient( + 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.enable_program 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.enable_program] = mock_rpc + + request = {} + await client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.enable_program(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_enable_program_async(transport: str = 'grpc_asyncio', request_type=programs.EnableProgramRequest): + client = ProgramsServiceAsyncClient( + 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.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + response = await client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.EnableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.asyncio +async def test_enable_program_async_from_dict(): + await test_enable_program_async(request_type=dict) + +def test_enable_program_field_headers(): + client = ProgramsServiceClient( + 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 = programs.EnableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value = programs.Program() + client.enable_program(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_enable_program_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.EnableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + await client.enable_program(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_enable_program_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.enable_program( + 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_enable_program_flattened_error(): + client = ProgramsServiceClient( + 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.enable_program( + programs.EnableProgramRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_enable_program_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.enable_program( + 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_enable_program_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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.enable_program( + programs.EnableProgramRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + programs.DisableProgramRequest, + dict, +]) +def test_disable_program(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + ) + response = client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.DisableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +def test_disable_program_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 = ProgramsServiceClient( + 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 = programs.DisableProgramRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.disable_program(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.DisableProgramRequest( + name='name_value', + ) + +def test_disable_program_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 = ProgramsServiceClient( + 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.disable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc + request = {} + client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.disable_program(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_disable_program_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 = ProgramsServiceAsyncClient( + 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.disable_program 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.disable_program] = mock_rpc + + request = {} + await client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.disable_program(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_disable_program_async(transport: str = 'grpc_asyncio', request_type=programs.DisableProgramRequest): + client = ProgramsServiceAsyncClient( + 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.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + response = await client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.DisableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.asyncio +async def test_disable_program_async_from_dict(): + await test_disable_program_async(request_type=dict) + +def test_disable_program_field_headers(): + client = ProgramsServiceClient( + 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 = programs.DisableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value = programs.Program() + client.disable_program(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_disable_program_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.DisableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + await client.disable_program(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_disable_program_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.disable_program( + 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_disable_program_flattened_error(): + client = ProgramsServiceClient( + 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.disable_program( + programs.DisableProgramRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_disable_program_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.disable_program( + 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_disable_program_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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.disable_program( + programs.DisableProgramRequest(), + name='name_value', + ) + + +def test_get_program_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 = ProgramsServiceClient( + 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.get_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_program] = mock_rpc + + request = {} + client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_program(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_get_program_rest_required_fields(request_type=programs.GetProgramRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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()).get_program._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_program._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.Program() + # 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 = programs.Program.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.get_program(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_program_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_program._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_program_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.Program() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = programs.Program.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.get_program(**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/accounts/v1/{name=accounts/*/programs/*}" % client.transport._host, args[1]) + + +def test_get_program_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_program( + programs.GetProgramRequest(), + name='name_value', + ) + + +def test_list_programs_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 = ProgramsServiceClient( + 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_programs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_programs] = mock_rpc + + request = {} + client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_programs(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_programs_rest_required_fields(request_type=programs.ListProgramsRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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_programs._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_programs._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.ListProgramsResponse() + # 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 = programs.ListProgramsResponse.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_programs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_programs_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_programs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_programs_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.ListProgramsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = programs.ListProgramsResponse.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_programs(**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/accounts/v1/{parent=accounts/*}/programs" % client.transport._host, args[1]) + + +def test_list_programs_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + 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_programs( + programs.ListProgramsRequest(), + parent='parent_value', + ) + + +def test_list_programs_rest_pager(transport: str = 'rest'): + client = ProgramsServiceClient( + 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 = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(programs.ListProgramsResponse.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'} + + pager = client.list_programs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, programs.Program) + for i in results) + + pages = list(client.list_programs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_enable_program_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 = ProgramsServiceClient( + 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.enable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc + + request = {} + client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enable_program(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_enable_program_rest_required_fields(request_type=programs.EnableProgramRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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()).enable_program._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()).enable_program._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.Program() + # 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 = programs.Program.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.enable_program(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_enable_program_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.enable_program._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_enable_program_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.Program() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = programs.Program.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.enable_program(**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/accounts/v1/{name=accounts/*/programs/*}:enable" % client.transport._host, args[1]) + + +def test_enable_program_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + 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.enable_program( + programs.EnableProgramRequest(), + name='name_value', + ) + + +def test_disable_program_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 = ProgramsServiceClient( + 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.disable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc + + request = {} + client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.disable_program(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_disable_program_rest_required_fields(request_type=programs.DisableProgramRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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()).disable_program._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()).disable_program._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.Program() + # 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 = programs.Program.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.disable_program(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_disable_program_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.disable_program._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_disable_program_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.Program() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = programs.Program.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.disable_program(**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/accounts/v1/{name=accounts/*/programs/*}:disable" % client.transport._host, args[1]) + + +def test_disable_program_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + 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.disable_program( + programs.DisableProgramRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProgramsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProgramsServiceClient( + 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 = ProgramsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProgramsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProgramsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProgramsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + transports.ProgramsServiceRestTransport, +]) +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 = ProgramsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProgramsServiceClient( + 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_get_program_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value = programs.Program() + client.get_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.GetProgramRequest() + + 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_list_programs_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + call.return_value = programs.ListProgramsResponse() + client.list_programs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.ListProgramsRequest() + + 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_enable_program_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value = programs.Program() + client.enable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.EnableProgramRequest() + + 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_disable_program_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value = programs.Program() + client.disable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.DisableProgramRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProgramsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + 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_get_program_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + await client.get_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.GetProgramRequest() + + 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_list_programs_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( + next_page_token='next_page_token_value', + )) + await client.list_programs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.ListProgramsRequest() + + 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_enable_program_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + await client.enable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.EnableProgramRequest() + + 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_disable_program_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + await client.disable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.DisableProgramRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProgramsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_program_rest_bad_request(request_type=programs.GetProgramRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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.get_program(request) + + +@pytest.mark.parametrize("request_type", [ + programs.GetProgramRequest, + dict, +]) +def test_get_program_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_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 = programs.Program.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.get_program(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_program_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_get_program") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_get_program_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_get_program") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.GetProgramRequest.pb(programs.GetProgramRequest()) + 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 = programs.Program.to_json(programs.Program()) + req.return_value.content = return_value + + request = programs.GetProgramRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.Program() + post_with_metadata.return_value = programs.Program(), metadata + + client.get_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_programs_rest_bad_request(request_type=programs.ListProgramsRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_programs(request) + + +@pytest.mark.parametrize("request_type", [ + programs.ListProgramsRequest, + dict, +]) +def test_list_programs_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = programs.ListProgramsResponse( + 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 = programs.ListProgramsResponse.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_programs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProgramsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_programs_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_list_programs") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_list_programs_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_list_programs") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.ListProgramsRequest.pb(programs.ListProgramsRequest()) + 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 = programs.ListProgramsResponse.to_json(programs.ListProgramsResponse()) + req.return_value.content = return_value + + request = programs.ListProgramsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.ListProgramsResponse() + post_with_metadata.return_value = programs.ListProgramsResponse(), metadata + + client.list_programs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_enable_program_rest_bad_request(request_type=programs.EnableProgramRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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.enable_program(request) + + +@pytest.mark.parametrize("request_type", [ + programs.EnableProgramRequest, + dict, +]) +def test_enable_program_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_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 = programs.Program.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.enable_program(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_program_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_enable_program") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_enable_program_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_enable_program") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.EnableProgramRequest.pb(programs.EnableProgramRequest()) + 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 = programs.Program.to_json(programs.Program()) + req.return_value.content = return_value + + request = programs.EnableProgramRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.Program() + post_with_metadata.return_value = programs.Program(), metadata + + client.enable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_disable_program_rest_bad_request(request_type=programs.DisableProgramRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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.disable_program(request) + + +@pytest.mark.parametrize("request_type", [ + programs.DisableProgramRequest, + dict, +]) +def test_disable_program_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_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 = programs.Program.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.disable_program(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_program_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_disable_program") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_disable_program_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_disable_program") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.DisableProgramRequest.pb(programs.DisableProgramRequest()) + 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 = programs.Program.to_json(programs.Program()) + req.return_value.content = return_value + + request = programs.DisableProgramRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.Program() + post_with_metadata.return_value = programs.Program(), metadata + + client.disable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = ProgramsServiceClient( + 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_get_program_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + client.get_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.GetProgramRequest() + + 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_list_programs_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + client.list_programs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.ListProgramsRequest() + + 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_enable_program_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + client.enable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.EnableProgramRequest() + + 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_disable_program_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + client.disable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.DisableProgramRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProgramsServiceGrpcTransport, + ) + +def test_programs_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProgramsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_programs_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProgramsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_program', + 'list_programs', + 'enable_program', + 'disable_program', + ) + 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_programs_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_accounts_v1.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProgramsServiceTransport( + 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_programs_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_accounts_v1.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProgramsServiceTransport() + adc.assert_called_once() + + +def test_programs_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) + ProgramsServiceClient() + 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.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + ], +) +def test_programs_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.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + transports.ProgramsServiceRestTransport, + ], +) +def test_programs_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.ProgramsServiceGrpcTransport, grpc_helpers), + (transports.ProgramsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +def test_programs_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_programs_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.ProgramsServiceRestTransport ( + 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_programs_service_host_no_port(transport_name): + client = ProgramsServiceClient( + 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_programs_service_host_with_port(transport_name): + client = ProgramsServiceClient( + 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_programs_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProgramsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProgramsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_program._session + session2 = client2.transport.get_program._session + assert session1 != session2 + session1 = client1.transport.list_programs._session + session2 = client2.transport.list_programs._session + assert session1 != session2 + session1 = client1.transport.enable_program._session + session2 = client2.transport.enable_program._session + assert session1 != session2 + session1 = client1.transport.disable_program._session + session2 = client2.transport.disable_program._session + assert session1 != session2 +def test_programs_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProgramsServiceGrpcTransport( + 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_programs_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProgramsServiceGrpcAsyncIOTransport( + 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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +def test_programs_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_program_path(): + account = "squid" + program = "clam" + expected = "accounts/{account}/programs/{program}".format(account=account, program=program, ) + actual = ProgramsServiceClient.program_path(account, program) + assert expected == actual + + +def test_parse_program_path(): + expected = { + "account": "whelk", + "program": "octopus", + } + path = ProgramsServiceClient.program_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_program_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProgramsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ProgramsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProgramsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ProgramsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProgramsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ProgramsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ProgramsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ProgramsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProgramsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ProgramsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.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.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProgramsServiceClient.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 = ProgramsServiceClient( + 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 = ProgramsServiceAsyncClient( + 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 = ProgramsServiceClient( + 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 = ProgramsServiceClient( + 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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py new file mode 100644 index 000000000000..dcda19f62337 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py @@ -0,0 +1,5216 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.regions_service import RegionsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.regions_service import RegionsServiceClient +from google.shopping.merchant_accounts_v1.services.regions_service import pagers +from google.shopping.merchant_accounts_v1.services.regions_service import transports +from google.shopping.merchant_accounts_v1.types import regions +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 RegionsServiceClient._get_default_mtls_endpoint(None) is None + assert RegionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RegionsServiceClient._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 RegionsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionsServiceClient._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 RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, False) is None + assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionsServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RegionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionsServiceClient._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 RegionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RegionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RegionsServiceClient._get_universe_domain(None, None) == RegionsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RegionsServiceClient._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 = RegionsServiceClient(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 = RegionsServiceClient(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", [ + (RegionsServiceClient, "grpc"), + (RegionsServiceAsyncClient, "grpc_asyncio"), + (RegionsServiceClient, "rest"), +]) +def test_regions_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.RegionsServiceGrpcTransport, "grpc"), + (transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionsServiceRestTransport, "rest"), +]) +def test_regions_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", [ + (RegionsServiceClient, "grpc"), + (RegionsServiceAsyncClient, "grpc_asyncio"), + (RegionsServiceClient, "rest"), +]) +def test_regions_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_regions_service_client_get_transport_class(): + transport = RegionsServiceClient.get_transport_class() + available_transports = [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceRestTransport, + ] + assert transport in available_transports + + transport = RegionsServiceClient.get_transport_class("grpc") + assert transport == transports.RegionsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), +]) +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +def test_regions_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(RegionsServiceClient, '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(RegionsServiceClient, '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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "true"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "false"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "true"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_regions_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", [ + RegionsServiceClient, RegionsServiceAsyncClient +]) +@mock.patch.object(RegionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceAsyncClient)) +def test_regions_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", [ + RegionsServiceClient, RegionsServiceAsyncClient +]) +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +def test_regions_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionsServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionsServiceClient._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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), +]) +def test_regions_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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", None), +]) +def test_regions_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_regions_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegionsServiceClient( + 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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_regions_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", [ + regions.GetRegionRequest, + dict, +]) +def test_get_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region( + name='name_value', + display_name='display_name_value', + ) + response = client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.GetRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_region_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 = RegionsServiceClient( + 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 = regions.GetRegionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.GetRegionRequest( + name='name_value', + ) + +def test_get_region_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 = RegionsServiceClient( + 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.get_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_region] = mock_rpc + request = {} + client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_region(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_get_region_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 = RegionsServiceAsyncClient( + 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.get_region in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_region] = mock_rpc + + request = {} + await client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_region(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_get_region_async(transport: str = 'grpc_asyncio', request_type=regions.GetRegionRequest): + client = RegionsServiceAsyncClient( + 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.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.GetRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_region_async_from_dict(): + await test_get_region_async(request_type=dict) + +def test_get_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.GetRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value = regions.Region() + client.get_region(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_get_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.GetRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + await client.get_region(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_get_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_region( + 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_get_region_flattened_error(): + client = RegionsServiceClient( + 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.get_region( + regions.GetRegionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_region( + 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_get_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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.get_region( + regions.GetRegionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + regions.CreateRegionRequest, + dict, +]) +def test_create_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region( + name='name_value', + display_name='display_name_value', + ) + response = client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.CreateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_region_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 = RegionsServiceClient( + 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 = regions.CreateRegionRequest( + parent='parent_value', + region_id='region_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.CreateRegionRequest( + parent='parent_value', + region_id='region_id_value', + ) + +def test_create_region_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 = RegionsServiceClient( + 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.create_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_region] = mock_rpc + request = {} + client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_region(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_create_region_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 = RegionsServiceAsyncClient( + 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.create_region in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_region] = mock_rpc + + request = {} + await client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_region(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_create_region_async(transport: str = 'grpc_asyncio', request_type=regions.CreateRegionRequest): + client = RegionsServiceAsyncClient( + 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.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + response = await client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.CreateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_region_async_from_dict(): + await test_create_region_async(request_type=dict) + +def test_create_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.CreateRegionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value = regions.Region() + client.create_region(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_create_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.CreateRegionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + await client.create_region(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_create_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_region( + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_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 + arg = args[0].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].region_id + mock_val = 'region_id_value' + assert arg == mock_val + + +def test_create_region_flattened_error(): + client = RegionsServiceClient( + 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.create_region( + regions.CreateRegionRequest(), + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_value', + ) + +@pytest.mark.asyncio +async def test_create_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_region( + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_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 + arg = args[0].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].region_id + mock_val = 'region_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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.create_region( + regions.CreateRegionRequest(), + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + regions.UpdateRegionRequest, + dict, +]) +def test_update_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region( + name='name_value', + display_name='display_name_value', + ) + response = client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.UpdateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_region_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 = RegionsServiceClient( + 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 = regions.UpdateRegionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.UpdateRegionRequest( + ) + +def test_update_region_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 = RegionsServiceClient( + 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.update_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_region] = mock_rpc + request = {} + client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_region(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_update_region_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 = RegionsServiceAsyncClient( + 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.update_region in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_region] = mock_rpc + + request = {} + await client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_region(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_update_region_async(transport: str = 'grpc_asyncio', request_type=regions.UpdateRegionRequest): + client = RegionsServiceAsyncClient( + 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.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.UpdateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_region_async_from_dict(): + await test_update_region_async(request_type=dict) + +def test_update_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.UpdateRegionRequest() + + request.region.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value = regions.Region() + client.update_region(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', + 'region.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.UpdateRegionRequest() + + request.region.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + await client.update_region(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', + 'region.name=name_value', + ) in kw['metadata'] + + +def test_update_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_region( + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_region_flattened_error(): + client = RegionsServiceClient( + 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.update_region( + regions.UpdateRegionRequest(), + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_region( + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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.update_region( + regions.UpdateRegionRequest(), + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + regions.DeleteRegionRequest, + dict, +]) +def test_delete_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.DeleteRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_region_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 = RegionsServiceClient( + 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 = regions.DeleteRegionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.DeleteRegionRequest( + name='name_value', + ) + +def test_delete_region_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 = RegionsServiceClient( + 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_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_region] = mock_rpc + request = {} + client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_region(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_region_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 = RegionsServiceAsyncClient( + 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_region 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_region] = mock_rpc + + request = {} + await client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_region(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_region_async(transport: str = 'grpc_asyncio', request_type=regions.DeleteRegionRequest): + client = RegionsServiceAsyncClient( + 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_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.DeleteRegionRequest() + 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_region_async_from_dict(): + await test_delete_region_async(request_type=dict) + +def test_delete_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.DeleteRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value = None + client.delete_region(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_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.DeleteRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_region(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_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__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_region( + 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_region_flattened_error(): + client = RegionsServiceClient( + 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_region( + regions.DeleteRegionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__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_region( + 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_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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_region( + regions.DeleteRegionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + regions.ListRegionsRequest, + dict, +]) +def test_list_regions(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.ListRegionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.ListRegionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_regions_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 = RegionsServiceClient( + 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 = regions.ListRegionsRequest( + 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_regions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_regions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.ListRegionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_regions_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 = RegionsServiceClient( + 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_regions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regions] = mock_rpc + request = {} + client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regions(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_regions_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 = RegionsServiceAsyncClient( + 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_regions 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_regions] = mock_rpc + + request = {} + await client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_regions(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_regions_async(transport: str = 'grpc_asyncio', request_type=regions.ListRegionsRequest): + client = RegionsServiceAsyncClient( + 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_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.ListRegionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_regions_async_from_dict(): + await test_list_regions_async(request_type=dict) + +def test_list_regions_field_headers(): + client = RegionsServiceClient( + 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 = regions.ListRegionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + call.return_value = regions.ListRegionsResponse() + client.list_regions(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_regions_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.ListRegionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) + await client.list_regions(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_regions_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.ListRegionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_regions( + 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_regions_flattened_error(): + client = RegionsServiceClient( + 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_regions( + regions.ListRegionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_regions_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.ListRegionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_regions( + 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_regions_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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_regions( + regions.ListRegionsRequest(), + parent='parent_value', + ) + + +def test_list_regions_pager(transport_name: str = "grpc"): + client = RegionsServiceClient( + 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_regions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_regions(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, regions.Region) + for i in results) +def test_list_regions_pages(transport_name: str = "grpc"): + client = RegionsServiceClient( + 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_regions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + RuntimeError, + ) + pages = list(client.list_regions(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_regions_async_pager(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_regions(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, regions.Region) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_regions_async_pages(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + 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_regions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_region_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 = RegionsServiceClient( + 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.get_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_region] = mock_rpc + + request = {} + client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_region(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_get_region_rest_required_fields(request_type=regions.GetRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + 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()).get_region._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_region._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 = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.Region() + # 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 = regions.Region.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.get_region(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_region_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.Region() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/regions/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = regions.Region.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.get_region(**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/accounts/v1/{name=accounts/*/regions/*}" % client.transport._host, args[1]) + + +def test_get_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_region( + regions.GetRegionRequest(), + name='name_value', + ) + + +def test_create_region_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 = RegionsServiceClient( + 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.create_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_region] = mock_rpc + + request = {} + client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_region(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_create_region_rest_required_fields(request_type=regions.CreateRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["region_id"] = "" + 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 + assert "regionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "regionId" in jsonified_request + assert jsonified_request["regionId"] == request_init["region_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["regionId"] = 'region_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("region_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "regionId" in jsonified_request + assert jsonified_request["regionId"] == 'region_id_value' + + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.Region() + # 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 = regions.Region.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.create_region(request) + + expected_params = [ + ( + "regionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(("regionId", )) & set(("parent", "regionId", "region", ))) + + +def test_create_region_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.Region() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_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 = regions.Region.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.create_region(**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/accounts/v1/{parent=accounts/*}/regions" % client.transport._host, args[1]) + + +def test_create_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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.create_region( + regions.CreateRegionRequest(), + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_value', + ) + + +def test_update_region_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 = RegionsServiceClient( + 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.update_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_region] = mock_rpc + + request = {} + client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_region(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_update_region_rest_required_fields(request_type=regions.UpdateRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.Region() + # 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': "patch", + '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 = regions.Region.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.update_region(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("region", ))) + + +def test_update_region_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.Region() + + # get arguments that satisfy an http rule for this method + sample_request = {'region': {'name': 'accounts/sample1/regions/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = regions.Region.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.update_region(**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/accounts/v1/{region.name=accounts/*/regions/*}" % client.transport._host, args[1]) + + +def test_update_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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.update_region( + regions.UpdateRegionRequest(), + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_region_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 = RegionsServiceClient( + 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_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_region] = mock_rpc + + request = {} + client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_region(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_region_rest_required_fields(request_type=regions.DeleteRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + 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_region._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_region._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 = RegionsServiceClient( + 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_region(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_region_rest_flattened(): + client = RegionsServiceClient( + 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/regions/sample2'} + + # 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_region(**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/accounts/v1/{name=accounts/*/regions/*}" % client.transport._host, args[1]) + + +def test_delete_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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_region( + regions.DeleteRegionRequest(), + name='name_value', + ) + + +def test_list_regions_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 = RegionsServiceClient( + 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_regions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regions] = mock_rpc + + request = {} + client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regions(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_regions_rest_required_fields(request_type=regions.ListRegionsRequest): + transport_class = transports.RegionsServiceRestTransport + + 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_regions._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_regions._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 = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.ListRegionsResponse() + # 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 = regions.ListRegionsResponse.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_regions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_regions_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_regions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_regions_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.ListRegionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = regions.ListRegionsResponse.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_regions(**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/accounts/v1/{parent=accounts/*}/regions" % client.transport._host, args[1]) + + +def test_list_regions_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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_regions( + regions.ListRegionsRequest(), + parent='parent_value', + ) + + +def test_list_regions_rest_pager(transport: str = 'rest'): + client = RegionsServiceClient( + 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 = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(regions.ListRegionsResponse.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'} + + pager = client.list_regions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regions.Region) + for i in results) + + pages = list(client.list_regions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionsServiceClient( + 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 = RegionsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegionsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + transports.RegionsServiceRestTransport, +]) +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 = RegionsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RegionsServiceClient( + 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_get_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value = regions.Region() + client.get_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.GetRegionRequest() + + 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_create_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value = regions.Region() + client.create_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.CreateRegionRequest() + + 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_update_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value = regions.Region() + client.update_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.UpdateRegionRequest() + + 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_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value = None + client.delete_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.DeleteRegionRequest() + + 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_list_regions_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + call.return_value = regions.ListRegionsResponse() + client.list_regions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.ListRegionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RegionsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RegionsServiceAsyncClient( + 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_get_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + await client.get_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.GetRegionRequest() + + 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_create_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + await client.create_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.CreateRegionRequest() + + 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_update_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + await client.update_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.UpdateRegionRequest() + + 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_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.DeleteRegionRequest() + + 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_list_regions_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_regions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.ListRegionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RegionsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_region_rest_bad_request(request_type=regions.GetRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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.get_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.GetRegionRequest, + dict, +]) +def test_get_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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 = regions.Region( + name='name_value', + display_name='display_name_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 = regions.Region.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.get_region(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_get_region") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_get_region_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_get_region") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.GetRegionRequest.pb(regions.GetRegionRequest()) + 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 = regions.Region.to_json(regions.Region()) + req.return_value.content = return_value + + request = regions.GetRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.Region() + post_with_metadata.return_value = regions.Region(), metadata + + client.get_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_region_rest_bad_request(request_type=regions.CreateRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.CreateRegionRequest, + dict, +]) +def test_create_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["region"] = {'name': 'name_value', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} + # 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 = regions.CreateRegionRequest.meta.fields["region"] + + 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["region"].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["region"][field])): + del request_init["region"][field][i][subfield] + else: + del request_init["region"][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 = regions.Region( + name='name_value', + display_name='display_name_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 = regions.Region.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.create_region(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_create_region") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_create_region_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_create_region") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.CreateRegionRequest.pb(regions.CreateRegionRequest()) + 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 = regions.Region.to_json(regions.Region()) + req.return_value.content = return_value + + request = regions.CreateRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.Region() + post_with_metadata.return_value = regions.Region(), metadata + + client.create_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_region_rest_bad_request(request_type=regions.UpdateRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'region': {'name': 'accounts/sample1/regions/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.update_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.UpdateRegionRequest, + dict, +]) +def test_update_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'region': {'name': 'accounts/sample1/regions/sample2'}} + request_init["region"] = {'name': 'accounts/sample1/regions/sample2', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} + # 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 = regions.UpdateRegionRequest.meta.fields["region"] + + 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["region"].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["region"][field])): + del request_init["region"][field][i][subfield] + else: + del request_init["region"][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 = regions.Region( + name='name_value', + display_name='display_name_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 = regions.Region.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.update_region(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_update_region") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_update_region_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_update_region") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.UpdateRegionRequest.pb(regions.UpdateRegionRequest()) + 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 = regions.Region.to_json(regions.Region()) + req.return_value.content = return_value + + request = regions.UpdateRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.Region() + post_with_metadata.return_value = regions.Region(), metadata + + client.update_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_region_rest_bad_request(request_type=regions.DeleteRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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.delete_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.DeleteRegionRequest, + dict, +]) +def test_delete_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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 = 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_region(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_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "pre_delete_region") as pre: + pre.assert_not_called() + pb_message = regions.DeleteRegionRequest.pb(regions.DeleteRegionRequest()) + 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 = regions.DeleteRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_regions_rest_bad_request(request_type=regions.ListRegionsRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_regions(request) + + +@pytest.mark.parametrize("request_type", [ + regions.ListRegionsRequest, + dict, +]) +def test_list_regions_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regions.ListRegionsResponse( + 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 = regions.ListRegionsResponse.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_regions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_regions_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_list_regions") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_list_regions_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_list_regions") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.ListRegionsRequest.pb(regions.ListRegionsRequest()) + 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 = regions.ListRegionsResponse.to_json(regions.ListRegionsResponse()) + req.return_value.content = return_value + + request = regions.ListRegionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.ListRegionsResponse() + post_with_metadata.return_value = regions.ListRegionsResponse(), metadata + + client.list_regions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = RegionsServiceClient( + 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_get_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + client.get_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.GetRegionRequest() + + 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_create_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + client.create_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.CreateRegionRequest() + + 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_update_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + client.update_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.UpdateRegionRequest() + + 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_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + client.delete_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.DeleteRegionRequest() + + 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_list_regions_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + client.list_regions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.ListRegionsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegionsServiceGrpcTransport, + ) + +def test_regions_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_regions_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_region', + 'create_region', + 'update_region', + 'delete_region', + 'list_regions', + ) + 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_regions_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_accounts_v1.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionsServiceTransport( + 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_regions_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_accounts_v1.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionsServiceTransport() + adc.assert_called_once() + + +def test_regions_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) + RegionsServiceClient() + 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.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + ], +) +def test_regions_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.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + transports.RegionsServiceRestTransport, + ], +) +def test_regions_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.RegionsServiceGrpcTransport, grpc_helpers), + (transports.RegionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +def test_regions_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_regions_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.RegionsServiceRestTransport ( + 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_regions_service_host_no_port(transport_name): + client = RegionsServiceClient( + 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_regions_service_host_with_port(transport_name): + client = RegionsServiceClient( + 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_regions_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_region._session + session2 = client2.transport.get_region._session + assert session1 != session2 + session1 = client1.transport.create_region._session + session2 = client2.transport.create_region._session + assert session1 != session2 + session1 = client1.transport.update_region._session + session2 = client2.transport.update_region._session + assert session1 != session2 + session1 = client1.transport.delete_region._session + session2 = client2.transport.delete_region._session + assert session1 != session2 + session1 = client1.transport.list_regions._session + session2 = client2.transport.list_regions._session + assert session1 != session2 +def test_regions_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionsServiceGrpcTransport( + 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_regions_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionsServiceGrpcAsyncIOTransport( + 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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +def test_regions_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = RegionsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = RegionsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_account_path(path) + assert expected == actual + +def test_region_path(): + account = "whelk" + region = "octopus" + expected = "accounts/{account}/regions/{region}".format(account=account, region=region, ) + actual = RegionsServiceClient.region_path(account, region) + assert expected == actual + + +def test_parse_region_path(): + expected = { + "account": "oyster", + "region": "nudibranch", + } + path = RegionsServiceClient.region_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_region_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegionsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RegionsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegionsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RegionsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegionsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RegionsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RegionsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RegionsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.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 = RegionsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RegionsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.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.RegionsServiceTransport, '_prep_wrapped_messages') as prep: + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegionsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegionsServiceClient.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 = RegionsServiceClient( + 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 = RegionsServiceAsyncClient( + 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 = RegionsServiceClient( + 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 = RegionsServiceClient( + 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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py new file mode 100644 index 000000000000..5918e0d8b4e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py @@ -0,0 +1,2750 @@ +# -*- 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.shopping.merchant_accounts_v1.services.shipping_settings_service import ShippingSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.shipping_settings_service import ShippingSettingsServiceClient +from google.shopping.merchant_accounts_v1.services.shipping_settings_service import transports +from google.shopping.merchant_accounts_v1.types import shippingsettings +from google.shopping.type.types import types +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 ShippingSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, False) is None + assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ShippingSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ShippingSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ShippingSettingsServiceClient._get_universe_domain(None, None) == ShippingSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient(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 = ShippingSettingsServiceClient(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", [ + (ShippingSettingsServiceClient, "grpc"), + (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), + (ShippingSettingsServiceClient, "rest"), +]) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, "grpc"), + (transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ShippingSettingsServiceRestTransport, "rest"), +]) +def test_shipping_settings_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", [ + (ShippingSettingsServiceClient, "grpc"), + (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), + (ShippingSettingsServiceClient, "rest"), +]) +def test_shipping_settings_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_shipping_settings_service_client_get_transport_class(): + transport = ShippingSettingsServiceClient.get_transport_class() + available_transports = [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = ShippingSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.ShippingSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +def test_shipping_settings_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(ShippingSettingsServiceClient, '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(ShippingSettingsServiceClient, '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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "true"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "false"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "true"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_shipping_settings_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", [ + ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient +]) +@mock.patch.object(ShippingSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceAsyncClient)) +def test_shipping_settings_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", [ + ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient +]) +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +def test_shipping_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ShippingSettingsServiceClient._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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), +]) +def test_shipping_settings_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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", None), +]) +def test_shipping_settings_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_shipping_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ShippingSettingsServiceClient( + 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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_shipping_settings_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", [ + shippingsettings.GetShippingSettingsRequest, + dict, +]) +def test_get_shipping_settings(request_type, transport: str = 'grpc'): + client = ShippingSettingsServiceClient( + 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.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + ) + response = client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = shippingsettings.GetShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_get_shipping_settings_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 = ShippingSettingsServiceClient( + 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 = shippingsettings.GetShippingSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_shipping_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == shippingsettings.GetShippingSettingsRequest( + name='name_value', + ) + +def test_get_shipping_settings_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 = ShippingSettingsServiceClient( + 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.get_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc + request = {} + client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_shipping_settings(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_get_shipping_settings_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 = ShippingSettingsServiceAsyncClient( + 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.get_shipping_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_shipping_settings] = mock_rpc + + request = {} + await client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_shipping_settings(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_get_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.GetShippingSettingsRequest): + client = ShippingSettingsServiceAsyncClient( + 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.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + response = await client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = shippingsettings.GetShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_shipping_settings_async_from_dict(): + await test_get_shipping_settings_async(request_type=dict) + +def test_get_shipping_settings_field_headers(): + client = ShippingSettingsServiceClient( + 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 = shippingsettings.GetShippingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.get_shipping_settings(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_get_shipping_settings_field_headers_async(): + client = ShippingSettingsServiceAsyncClient( + 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 = shippingsettings.GetShippingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + await client.get_shipping_settings(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_get_shipping_settings_flattened(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_shipping_settings( + 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_get_shipping_settings_flattened_error(): + client = ShippingSettingsServiceClient( + 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.get_shipping_settings( + shippingsettings.GetShippingSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_shipping_settings_flattened_async(): + client = ShippingSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_shipping_settings( + 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_get_shipping_settings_flattened_error_async(): + client = ShippingSettingsServiceAsyncClient( + 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.get_shipping_settings( + shippingsettings.GetShippingSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + shippingsettings.InsertShippingSettingsRequest, + dict, +]) +def test_insert_shipping_settings(request_type, transport: str = 'grpc'): + client = ShippingSettingsServiceClient( + 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_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + ) + response = client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = shippingsettings.InsertShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( + 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 = shippingsettings.InsertShippingSettingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_shipping_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == shippingsettings.InsertShippingSettingsRequest( + parent='parent_value', + ) + +def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( + 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_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_shipping_settings] = mock_rpc + request = {} + client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_shipping_settings(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_shipping_settings_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 = ShippingSettingsServiceAsyncClient( + 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_shipping_settings 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_shipping_settings] = mock_rpc + + request = {} + await client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_shipping_settings(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_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.InsertShippingSettingsRequest): + client = ShippingSettingsServiceAsyncClient( + 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_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + response = await client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = shippingsettings.InsertShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_insert_shipping_settings_async_from_dict(): + await test_insert_shipping_settings_async(request_type=dict) + +def test_insert_shipping_settings_field_headers(): + client = ShippingSettingsServiceClient( + 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 = shippingsettings.InsertShippingSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.insert_shipping_settings(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_shipping_settings_field_headers_async(): + client = ShippingSettingsServiceAsyncClient( + 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 = shippingsettings.InsertShippingSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + await client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_get_shipping_settings_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 = ShippingSettingsServiceClient( + 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.get_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc + + request = {} + client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_shipping_settings(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_get_shipping_settings_rest_required_fields(request_type=shippingsettings.GetShippingSettingsRequest): + transport_class = transports.ShippingSettingsServiceRestTransport + + 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()).get_shipping_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_shipping_settings._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 = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = shippingsettings.ShippingSettings() + # 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 = shippingsettings.ShippingSettings.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.get_shipping_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_shipping_settings_rest_unset_required_fields(): + transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_shipping_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_shipping_settings_rest_flattened(): + client = ShippingSettingsServiceClient( + 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 = shippingsettings.ShippingSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/shippingSettings'} + + # 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 + # Convert return value to protobuf type + return_value = shippingsettings.ShippingSettings.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.get_shipping_settings(**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/accounts/v1/{name=accounts/*/shippingSettings}" % client.transport._host, args[1]) + + +def test_get_shipping_settings_rest_flattened_error(transport: str = 'rest'): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_shipping_settings( + shippingsettings.GetShippingSettingsRequest(), + name='name_value', + ) + + +def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( + 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_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_shipping_settings] = mock_rpc + + request = {} + client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_shipping_settings(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_shipping_settings_rest_required_fields(request_type=shippingsettings.InsertShippingSettingsRequest): + transport_class = transports.ShippingSettingsServiceRestTransport + + 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_shipping_settings._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_shipping_settings._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 = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = shippingsettings.ShippingSettings() + # 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 = shippingsettings.ShippingSettings.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_shipping_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_shipping_settings_rest_unset_required_fields(): + transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_shipping_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "shippingSetting", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + 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 = ShippingSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ShippingSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ShippingSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + transports.ShippingSettingsServiceRestTransport, +]) +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 = ShippingSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ShippingSettingsServiceClient( + 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_get_shipping_settings_empty_call_grpc(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.get_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.GetShippingSettingsRequest() + + 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_shipping_settings_empty_call_grpc(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.insert_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.InsertShippingSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ShippingSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ShippingSettingsServiceAsyncClient( + 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_get_shipping_settings_empty_call_grpc_asyncio(): + client = ShippingSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + await client.get_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.GetShippingSettingsRequest() + + 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_shipping_settings_empty_call_grpc_asyncio(): + client = ShippingSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + await client.insert_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.InsertShippingSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ShippingSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_shipping_settings_rest_bad_request(request_type=shippingsettings.GetShippingSettingsRequest): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/shippingSettings'} + 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.get_shipping_settings(request) + + +@pytest.mark.parametrize("request_type", [ + shippingsettings.GetShippingSettingsRequest, + dict, +]) +def test_get_shipping_settings_rest_call_success(request_type): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/shippingSettings'} + request = request_type(**request_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 = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_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 = shippingsettings.ShippingSettings.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.get_shipping_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_shipping_settings_rest_interceptors(null_interceptor): + transport = transports.ShippingSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), + ) + client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings") as post, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_get_shipping_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = shippingsettings.GetShippingSettingsRequest.pb(shippingsettings.GetShippingSettingsRequest()) + 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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) + req.return_value.content = return_value + + request = shippingsettings.GetShippingSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = shippingsettings.ShippingSettings() + post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata + + client.get_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_shipping_settings_rest_bad_request(request_type=shippingsettings.InsertShippingSettingsRequest): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_shipping_settings(request) + + +@pytest.mark.parametrize("request_type", [ + shippingsettings.InsertShippingSettingsRequest, + dict, +]) +def test_insert_shipping_settings_rest_call_success(request_type): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["shipping_setting"] = {'name': 'name_value', 'services': [{'service_name': 'service_name_value', 'active': True, 'delivery_countries': ['delivery_countries_value1', 'delivery_countries_value2'], 'currency_code': 'currency_code_value', 'delivery_time': {'min_transit_days': 1720, 'max_transit_days': 1722, 'cutoff_time': {'hour': 446, 'minute': 658, 'time_zone': 'time_zone_value'}, 'min_handling_days': 1784, 'max_handling_days': 1786, 'transit_time_table': {'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'transit_time_labels': ['transit_time_labels_value1', 'transit_time_labels_value2'], 'rows': [{'values': [{'min_transit_days': 1720, 'max_transit_days': 1722}]}]}, 'handling_business_day_config': {'business_days': [1]}, 'transit_business_day_config': {}, 'warehouse_based_delivery_times': [{'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'warehouse': 'warehouse_value'}]}, 'rate_groups': [{'applicable_shipping_labels': ['applicable_shipping_labels_value1', 'applicable_shipping_labels_value2'], 'single_value': {'no_shipping': True, 'flat_rate': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'price_percentage': 'price_percentage_value', 'carrier_rate': 'carrier_rate_value', 'subtable': 'subtable_value'}, 'main_table': {'name': 'name_value', 'row_headers': {'prices': {}, 'weights': [{'amount_micros': 1408, 'unit': 1}], 'number_of_items': ['number_of_items_value1', 'number_of_items_value2'], 'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'locations': [{'location_ids': ['location_ids_value1', 'location_ids_value2']}]}, 'column_headers': {}, 'rows': [{'cells': {}}]}, 'subtables': {}, 'carrier_rates': [{'name': 'name_value', 'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'origin_postal_code': 'origin_postal_code_value', 'percentage_adjustment': 'percentage_adjustment_value', 'flat_adjustment': {}}], 'name': 'name_value'}], 'shipment_type': 1, 'minimum_order_value': {}, 'minimum_order_value_table': {'store_code_set_with_movs': [{'store_codes': ['store_codes_value1', 'store_codes_value2'], 'value': {}}]}, 'store_config': {'store_service_type': 1, 'store_codes': ['store_codes_value1', 'store_codes_value2'], 'cutoff_config': {'local_cutoff_time': {'hour': 446, 'minute': 658}, 'store_close_offset_hours': 2584, 'no_delivery_post_cutoff': True}, 'service_radius': {'value': 541, 'unit': 1}}, 'loyalty_programs': [{'program_label': 'program_label_value', 'loyalty_program_tiers': [{'tier_label': 'tier_label_value'}]}]}], 'warehouses': [{'name': 'name_value', 'shipping_address': {'street_address': 'street_address_value', 'city': 'city_value', 'administrative_area': 'administrative_area_value', 'postal_code': 'postal_code_value', 'region_code': 'region_code_value'}, 'cutoff_time': {'hour': 446, 'minute': 658}, 'handling_days': 1365, 'business_day_config': {}}], 'etag': 'etag_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 = shippingsettings.InsertShippingSettingsRequest.meta.fields["shipping_setting"] + + 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["shipping_setting"].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["shipping_setting"][field])): + del request_init["shipping_setting"][field][i][subfield] + else: + del request_init["shipping_setting"][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 = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_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 = shippingsettings.ShippingSettings.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_shipping_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_shipping_settings_rest_interceptors(null_interceptor): + transport = transports.ShippingSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), + ) + client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings") as post, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_insert_shipping_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = shippingsettings.InsertShippingSettingsRequest.pb(shippingsettings.InsertShippingSettingsRequest()) + 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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) + req.return_value.content = return_value + + request = shippingsettings.InsertShippingSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = shippingsettings.ShippingSettings() + post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata + + client.insert_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = ShippingSettingsServiceClient( + 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_get_shipping_settings_empty_call_rest(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + client.get_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.GetShippingSettingsRequest() + + 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_shipping_settings_empty_call_rest(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + client.insert_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.InsertShippingSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ShippingSettingsServiceGrpcTransport, + ) + +def test_shipping_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ShippingSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_shipping_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ShippingSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_shipping_settings', + 'insert_shipping_settings', + ) + 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_shipping_settings_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_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ShippingSettingsServiceTransport( + 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_shipping_settings_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_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ShippingSettingsServiceTransport() + adc.assert_called_once() + + +def test_shipping_settings_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) + ShippingSettingsServiceClient() + 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.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + transports.ShippingSettingsServiceRestTransport, + ], +) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, grpc_helpers), + (transports.ShippingSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +def test_shipping_settings_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_shipping_settings_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.ShippingSettingsServiceRestTransport ( + 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_shipping_settings_service_host_no_port(transport_name): + client = ShippingSettingsServiceClient( + 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_shipping_settings_service_host_with_port(transport_name): + client = ShippingSettingsServiceClient( + 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_shipping_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ShippingSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ShippingSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_shipping_settings._session + session2 = client2.transport.get_shipping_settings._session + assert session1 != session2 + session1 = client1.transport.insert_shipping_settings._session + session2 = client2.transport.insert_shipping_settings._session + assert session1 != session2 +def test_shipping_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ShippingSettingsServiceGrpcTransport( + 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_shipping_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ShippingSettingsServiceGrpcAsyncIOTransport( + 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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +def test_shipping_settings_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = ShippingSettingsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = ShippingSettingsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_account_path(path) + assert expected == actual + +def test_shipping_settings_path(): + account = "whelk" + expected = "accounts/{account}/shippingSettings".format(account=account, ) + actual = ShippingSettingsServiceClient.shipping_settings_path(account) + assert expected == actual + + +def test_parse_shipping_settings_path(): + expected = { + "account": "octopus", + } + path = ShippingSettingsServiceClient.shipping_settings_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_shipping_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ShippingSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ShippingSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ShippingSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ShippingSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ShippingSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ShippingSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ShippingSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ShippingSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ShippingSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ShippingSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.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.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ShippingSettingsServiceClient.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 = ShippingSettingsServiceClient( + 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 = ShippingSettingsServiceAsyncClient( + 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 = ShippingSettingsServiceClient( + 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 = ShippingSettingsServiceClient( + 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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py new file mode 100644 index 000000000000..6c2a2184becb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py @@ -0,0 +1,2854 @@ +# -*- 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.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import transports +from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind +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 TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(None) is None + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, False) is None + assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, None) == TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 = TermsOfServiceAgreementStateServiceClient(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 = TermsOfServiceAgreementStateServiceClient(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", [ + (TermsOfServiceAgreementStateServiceClient, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, "rest"), +]) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +def test_terms_of_service_agreement_state_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", [ + (TermsOfServiceAgreementStateServiceClient, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, "rest"), +]) +def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_service_client_get_transport_class(): + transport = TermsOfServiceAgreementStateServiceClient.get_transport_class() + available_transports = [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, + ] + assert transport in available_transports + + transport = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc") + assert transport == transports.TermsOfServiceAgreementStateServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +def test_terms_of_service_agreement_state_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(TermsOfServiceAgreementStateServiceClient, '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(TermsOfServiceAgreementStateServiceClient, '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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "true"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "false"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "true"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_terms_of_service_agreement_state_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", [ + TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceAsyncClient)) +def test_terms_of_service_agreement_state_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", [ + TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +def test_terms_of_service_agreement_state_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceAgreementStateServiceClient._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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +def test_terms_of_service_agreement_state_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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", None), +]) +def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TermsOfServiceAgreementStateServiceClient( + 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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_terms_of_service_agreement_state_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", [ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, +]) +def test_get_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): + client = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + response = client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_terms_of_service_agreement_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + name='name_value', + ) + +def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc + request = {} + client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceAsyncClient( + 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.get_terms_of_service_agreement_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service_agreement_state] = mock_rpc + + request = {} + await client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + response = await client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.asyncio +async def test_get_terms_of_service_agreement_state_async_from_dict(): + await test_get_terms_of_service_agreement_state_async(request_type=dict) + +def test_get_terms_of_service_agreement_state_field_headers(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_field_headers_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + await client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_terms_of_service_agreement_state( + 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_get_terms_of_service_agreement_state_flattened_error(): + client = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_terms_of_service_agreement_state_flattened_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_terms_of_service_agreement_state( + 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_get_terms_of_service_agreement_state_flattened_error_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.get_terms_of_service_agreement_state( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + dict, +]) +def test_retrieve_for_application_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): + client = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + response = client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.retrieve_for_application_terms_of_service_agreement_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent='parent_value', + ) + +def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + request = {} + client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceAsyncClient( + 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.retrieve_for_application_terms_of_service_agreement_state 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.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + + request = {} + await client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + response = await client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.asyncio +async def test_retrieve_for_application_terms_of_service_agreement_state_async_from_dict(): + await test_retrieve_for_application_terms_of_service_agreement_state_async(request_type=dict) + +def test_retrieve_for_application_terms_of_service_agreement_state_field_headers(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_field_headers_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + await client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.retrieve_for_application_terms_of_service_agreement_state( + 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error(): + client = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_retrieve_for_application_terms_of_service_agreement_state_flattened_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.retrieve_for_application_terms_of_service_agreement_state( + 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.retrieve_for_application_terms_of_service_agreement_state( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), + parent='parent_value', + ) + + +def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc + + request = {} + client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport + + 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()).get_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_terms_of_service_agreement_state_rest_unset_required_fields(): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_terms_of_service_agreement_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_terms_of_service_agreement_state_rest_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/termsOfServiceAgreementStates/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(**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/accounts/v1/{name=accounts/*/termsOfServiceAgreementStates/*}" % client.transport._host, args[1]) + + +def test_get_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_terms_of_service_agreement_state( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), + name='name_value', + ) + + +def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + + request = {} + client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport + + 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()).retrieve_for_application_terms_of_service_agreement_state._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()).retrieve_for_application_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_unset_required_fields(): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(**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/accounts/v1/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication" % client.transport._host, args[1]) + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + 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 = TermsOfServiceAgreementStateServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TermsOfServiceAgreementStateServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, +]) +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 = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TermsOfServiceAgreementStateServiceClient( + 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_get_terms_of_service_agreement_state_empty_call_grpc(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.get_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_grpc(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.retrieve_for_application_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TermsOfServiceAgreementStateServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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_get_terms_of_service_agreement_state_empty_call_grpc_asyncio(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + await client.get_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_grpc_asyncio(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + await client.retrieve_for_application_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TermsOfServiceAgreementStateServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/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.get_terms_of_service_agreement_state(request) + + +@pytest.mark.parametrize("request_type", [ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, +]) +def test_get_terms_of_service_agreement_state_rest_call_success(request_type): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/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 = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_terms_of_service_agreement_state_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), + ) + client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state") as post, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_get_terms_of_service_agreement_state") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest()) + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) + req.return_value.content = return_value + + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata + + client.get_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.retrieve_for_application_terms_of_service_agreement_state(request) + + +@pytest.mark.parametrize("request_type", [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + dict, +]) +def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_success(request_type): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_for_application_terms_of_service_agreement_state_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), + ) + client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state") as post, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_retrieve_for_application_terms_of_service_agreement_state") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest()) + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) + req.return_value.content = return_value + + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata + + client.retrieve_for_application_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = TermsOfServiceAgreementStateServiceClient( + 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_get_terms_of_service_agreement_state_empty_call_rest(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + client.get_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_rest(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + client.retrieve_for_application_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + ) + +def test_terms_of_service_agreement_state_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TermsOfServiceAgreementStateServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_terms_of_service_agreement_state_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TermsOfServiceAgreementStateServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_terms_of_service_agreement_state', + 'retrieve_for_application_terms_of_service_agreement_state', + ) + 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_terms_of_service_agreement_state_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_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceAgreementStateServiceTransport( + 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_terms_of_service_agreement_state_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_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceAgreementStateServiceTransport() + adc.assert_called_once() + + +def test_terms_of_service_agreement_state_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) + TermsOfServiceAgreementStateServiceClient() + 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.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + ], +) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, + ], +) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, grpc_helpers), + (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceRestTransport ( + 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_terms_of_service_agreement_state_service_host_no_port(transport_name): + client = TermsOfServiceAgreementStateServiceClient( + 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_terms_of_service_agreement_state_service_host_with_port(transport_name): + client = TermsOfServiceAgreementStateServiceClient( + 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_terms_of_service_agreement_state_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TermsOfServiceAgreementStateServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TermsOfServiceAgreementStateServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_terms_of_service_agreement_state._session + session2 = client2.transport.get_terms_of_service_agreement_state._session + assert session1 != session2 + session1 = client1.transport.retrieve_for_application_terms_of_service_agreement_state._session + session2 = client2.transport.retrieve_for_application_terms_of_service_agreement_state._session + assert session1 != session2 +def test_terms_of_service_agreement_state_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + 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_terms_of_service_agreement_state_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( + 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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +def test_terms_of_service_agreement_state_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = TermsOfServiceAgreementStateServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = TermsOfServiceAgreementStateServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_account_path(path) + assert expected == actual + +def test_terms_of_service_path(): + version = "whelk" + expected = "termsOfService/{version}".format(version=version, ) + actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(version) + assert expected == actual + + +def test_parse_terms_of_service_path(): + expected = { + "version": "octopus", + } + path = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path(path) + assert expected == actual + +def test_terms_of_service_agreement_state_path(): + account = "oyster" + identifier = "nudibranch" + expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(account, identifier) + assert expected == actual + + +def test_parse_terms_of_service_agreement_state_path(): + expected = { + "account": "cuttlefish", + "identifier": "mussel", + } + path = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = TermsOfServiceAgreementStateServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = TermsOfServiceAgreementStateServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TermsOfServiceAgreementStateServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = TermsOfServiceAgreementStateServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = TermsOfServiceAgreementStateServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = TermsOfServiceAgreementStateServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TermsOfServiceAgreementStateServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = TermsOfServiceAgreementStateServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.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.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TermsOfServiceAgreementStateServiceClient.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 = TermsOfServiceAgreementStateServiceClient( + 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 = TermsOfServiceAgreementStateServiceAsyncClient( + 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 = TermsOfServiceAgreementStateServiceClient( + 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 = TermsOfServiceAgreementStateServiceClient( + 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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py new file mode 100644 index 000000000000..6106a91fa450 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py @@ -0,0 +1,3373 @@ +# -*- 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.shopping.merchant_accounts_v1.services.terms_of_service_service import TermsOfServiceServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_service import TermsOfServiceServiceClient +from google.shopping.merchant_accounts_v1.services.terms_of_service_service import transports +from google.shopping.merchant_accounts_v1.types import termsofservice +from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1.types import termsofservicekind +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 TermsOfServiceServiceClient._get_default_mtls_endpoint(None) is None + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, False) is None + assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert TermsOfServiceServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert TermsOfServiceServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert TermsOfServiceServiceClient._get_universe_domain(None, None) == TermsOfServiceServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient(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 = TermsOfServiceServiceClient(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", [ + (TermsOfServiceServiceClient, "grpc"), + (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceServiceClient, "rest"), +]) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, "grpc"), + (transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TermsOfServiceServiceRestTransport, "rest"), +]) +def test_terms_of_service_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", [ + (TermsOfServiceServiceClient, "grpc"), + (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceServiceClient, "rest"), +]) +def test_terms_of_service_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_terms_of_service_service_client_get_transport_class(): + transport = TermsOfServiceServiceClient.get_transport_class() + available_transports = [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceRestTransport, + ] + assert transport in available_transports + + transport = TermsOfServiceServiceClient.get_transport_class("grpc") + assert transport == transports.TermsOfServiceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), +]) +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +def test_terms_of_service_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(TermsOfServiceServiceClient, '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(TermsOfServiceServiceClient, '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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "true"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "false"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "true"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_terms_of_service_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", [ + TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceAsyncClient)) +def test_terms_of_service_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", [ + TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +def test_terms_of_service_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceServiceClient._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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), +]) +def test_terms_of_service_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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", None), +]) +def test_terms_of_service_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_terms_of_service_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TermsOfServiceServiceClient( + 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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_terms_of_service_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", [ + termsofservice.GetTermsOfServiceRequest, + dict, +]) +def test_get_terms_of_service(request_type, transport: str = 'grpc'): + client = TermsOfServiceServiceClient( + 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.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + response = client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofservice.GetTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +def test_get_terms_of_service_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 = TermsOfServiceServiceClient( + 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 = termsofservice.GetTermsOfServiceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_terms_of_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofservice.GetTermsOfServiceRequest( + name='name_value', + ) + +def test_get_terms_of_service_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 = TermsOfServiceServiceClient( + 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.get_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc + request = {} + client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service(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_get_terms_of_service_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 = TermsOfServiceServiceAsyncClient( + 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.get_terms_of_service in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service] = mock_rpc + + request = {} + await client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_terms_of_service(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_get_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.GetTermsOfServiceRequest): + client = TermsOfServiceServiceAsyncClient( + 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.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + response = await client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofservice.GetTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.asyncio +async def test_get_terms_of_service_async_from_dict(): + await test_get_terms_of_service_async(request_type=dict) + +def test_get_terms_of_service_field_headers(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.GetTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.TermsOfService() + client.get_terms_of_service(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_get_terms_of_service_field_headers_async(): + client = TermsOfServiceServiceAsyncClient( + 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 = termsofservice.GetTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) + await client.get_terms_of_service(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_get_terms_of_service_flattened(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_terms_of_service( + 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_get_terms_of_service_flattened_error(): + client = TermsOfServiceServiceClient( + 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.get_terms_of_service( + termsofservice.GetTermsOfServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_terms_of_service_flattened_async(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_terms_of_service( + 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_get_terms_of_service_flattened_error_async(): + client = TermsOfServiceServiceAsyncClient( + 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.get_terms_of_service( + termsofservice.GetTermsOfServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.RetrieveLatestTermsOfServiceRequest, + dict, +]) +def test_retrieve_latest_terms_of_service(request_type, transport: str = 'grpc'): + client = TermsOfServiceServiceClient( + 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.retrieve_latest_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + response = client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofservice.RetrieveLatestTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( + 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 = termsofservice.RetrieveLatestTermsOfServiceRequest( + region_code='region_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.retrieve_latest_terms_of_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofservice.RetrieveLatestTermsOfServiceRequest( + region_code='region_code_value', + ) + +def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( + 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.retrieve_latest_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc + request = {} + client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceAsyncClient( + 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.retrieve_latest_terms_of_service 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.retrieve_latest_terms_of_service] = mock_rpc + + request = {} + await client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): + client = TermsOfServiceServiceAsyncClient( + 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.retrieve_latest_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + response = await client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofservice.RetrieveLatestTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.asyncio +async def test_retrieve_latest_terms_of_service_async_from_dict(): + await test_retrieve_latest_terms_of_service_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.AcceptTermsOfServiceRequest, + dict, +]) +def test_accept_terms_of_service(request_type, transport: str = 'grpc'): + client = TermsOfServiceServiceClient( + 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.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.AcceptTermsOfServiceResponse( + ) + response = client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofservice.AcceptTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.AcceptTermsOfServiceResponse) + + +def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( + 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 = termsofservice.AcceptTermsOfServiceRequest( + name='name_value', + account='account_value', + region_code='region_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.accept_terms_of_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofservice.AcceptTermsOfServiceRequest( + name='name_value', + account='account_value', + region_code='region_code_value', + ) + +def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( + 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.accept_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc + request = {} + client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.accept_terms_of_service(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_accept_terms_of_service_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 = TermsOfServiceServiceAsyncClient( + 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.accept_terms_of_service 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.accept_terms_of_service] = mock_rpc + + request = {} + await client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.accept_terms_of_service(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_accept_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.AcceptTermsOfServiceRequest): + client = TermsOfServiceServiceAsyncClient( + 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.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse( + )) + response = await client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofservice.AcceptTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.AcceptTermsOfServiceResponse) + + +@pytest.mark.asyncio +async def test_accept_terms_of_service_async_from_dict(): + await test_accept_terms_of_service_async(request_type=dict) + +def test_accept_terms_of_service_field_headers(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.AcceptTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.AcceptTermsOfServiceResponse() + client.accept_terms_of_service(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_accept_terms_of_service_field_headers_async(): + client = TermsOfServiceServiceAsyncClient( + 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 = termsofservice.AcceptTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse()) + await client.accept_terms_of_service(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_accept_terms_of_service_flattened(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.AcceptTermsOfServiceResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.accept_terms_of_service( + 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_accept_terms_of_service_flattened_error(): + client = TermsOfServiceServiceClient( + 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.accept_terms_of_service( + termsofservice.AcceptTermsOfServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_accept_terms_of_service_flattened_async(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.AcceptTermsOfServiceResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.accept_terms_of_service( + 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_accept_terms_of_service_flattened_error_async(): + client = TermsOfServiceServiceAsyncClient( + 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.accept_terms_of_service( + termsofservice.AcceptTermsOfServiceRequest(), + name='name_value', + ) + + +def test_get_terms_of_service_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 = TermsOfServiceServiceClient( + 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.get_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc + + request = {} + client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service(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_get_terms_of_service_rest_required_fields(request_type=termsofservice.GetTermsOfServiceRequest): + transport_class = transports.TermsOfServiceServiceRestTransport + + 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()).get_terms_of_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service._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 = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService() + # 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 = termsofservice.TermsOfService.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.get_terms_of_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_terms_of_service_rest_unset_required_fields(): + transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_terms_of_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_terms_of_service_rest_flattened(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.TermsOfService() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'termsOfService/sample1'} + + # 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 + # Convert return value to protobuf type + return_value = termsofservice.TermsOfService.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.get_terms_of_service(**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/accounts/v1/{name=termsOfService/*}" % client.transport._host, args[1]) + + +def test_get_terms_of_service_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_terms_of_service( + termsofservice.GetTermsOfServiceRequest(), + name='name_value', + ) + + +def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( + 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.retrieve_latest_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc + + request = {} + client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_rest_required_fields(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): + transport_class = transports.TermsOfServiceServiceRestTransport + + request_init = {} + request_init["region_code"] = "" + 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 + assert "regionCode" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == request_init["region_code"] + + jsonified_request["regionCode"] = 'region_code_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("kind", "region_code", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == 'region_code_value' + + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService() + # 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 = termsofservice.TermsOfService.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.retrieve_latest_terms_of_service(request) + + expected_params = [ + ( + "regionCode", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_retrieve_latest_terms_of_service_rest_unset_required_fields(): + transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.retrieve_latest_terms_of_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("kind", "regionCode", )) & set(("regionCode", "kind", ))) + + +def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( + 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.accept_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc + + request = {} + client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.accept_terms_of_service(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_accept_terms_of_service_rest_required_fields(request_type=termsofservice.AcceptTermsOfServiceRequest): + transport_class = transports.TermsOfServiceServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["account"] = "" + request_init["region_code"] = "" + 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 + assert "account" not in jsonified_request + assert "regionCode" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "account" in jsonified_request + assert jsonified_request["account"] == request_init["account"] + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == request_init["region_code"] + + jsonified_request["name"] = 'name_value' + jsonified_request["account"] = 'account_value' + jsonified_request["regionCode"] = 'region_code_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("account", "region_code", )) + 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 "account" in jsonified_request + assert jsonified_request["account"] == 'account_value' + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == 'region_code_value' + + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofservice.AcceptTermsOfServiceResponse() + # 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.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = termsofservice.AcceptTermsOfServiceResponse.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.accept_terms_of_service(request) + + expected_params = [ + ( + "account", + "", + ), + ( + "regionCode", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_accept_terms_of_service_rest_unset_required_fields(): + transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.accept_terms_of_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("account", "regionCode", )) & set(("name", "account", "regionCode", ))) + + +def test_accept_terms_of_service_rest_flattened(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.AcceptTermsOfServiceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'termsOfService/sample1'} + + # 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 + # Convert return value to protobuf type + return_value = termsofservice.AcceptTermsOfServiceResponse.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.accept_terms_of_service(**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/accounts/v1/{name=termsOfService/*}:accept" % client.transport._host, args[1]) + + +def test_accept_terms_of_service_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceServiceClient( + 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.accept_terms_of_service( + termsofservice.AcceptTermsOfServiceRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + 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 = TermsOfServiceServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TermsOfServiceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TermsOfServiceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + transports.TermsOfServiceServiceRestTransport, +]) +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 = TermsOfServiceServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TermsOfServiceServiceClient( + 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_get_terms_of_service_empty_call_grpc(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.TermsOfService() + client.get_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.GetTermsOfServiceRequest() + + 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_retrieve_latest_terms_of_service_empty_call_grpc(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.TermsOfService() + client.retrieve_latest_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() + + 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_accept_terms_of_service_empty_call_grpc(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.AcceptTermsOfServiceResponse() + client.accept_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.AcceptTermsOfServiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TermsOfServiceServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + 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_get_terms_of_service_empty_call_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + await client.get_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.GetTermsOfServiceRequest() + + 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_retrieve_latest_terms_of_service_empty_call_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + await client.retrieve_latest_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() + + 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_accept_terms_of_service_empty_call_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse( + )) + await client.accept_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.AcceptTermsOfServiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TermsOfServiceServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_terms_of_service_rest_bad_request(request_type=termsofservice.GetTermsOfServiceRequest): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + 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.get_terms_of_service(request) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.GetTermsOfServiceRequest, + dict, +]) +def test_get_terms_of_service_rest_call_success(request_type): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + + # 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 = termsofservice.TermsOfService.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.get_terms_of_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_terms_of_service_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), + ) + client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service") as post, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_get_terms_of_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofservice.GetTermsOfServiceRequest.pb(termsofservice.GetTermsOfServiceRequest()) + 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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) + req.return_value.content = return_value + + request = termsofservice.GetTermsOfServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofservice.TermsOfService() + post_with_metadata.return_value = termsofservice.TermsOfService(), metadata + + client.get_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_retrieve_latest_terms_of_service_rest_bad_request(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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.retrieve_latest_terms_of_service(request) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.RetrieveLatestTermsOfServiceRequest, + dict, +]) +def test_retrieve_latest_terms_of_service_rest_call_success(request_type): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + + # 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 = termsofservice.TermsOfService.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.retrieve_latest_terms_of_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_latest_terms_of_service_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), + ) + client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service") as post, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_retrieve_latest_terms_of_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofservice.RetrieveLatestTermsOfServiceRequest.pb(termsofservice.RetrieveLatestTermsOfServiceRequest()) + 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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) + req.return_value.content = return_value + + request = termsofservice.RetrieveLatestTermsOfServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofservice.TermsOfService() + post_with_metadata.return_value = termsofservice.TermsOfService(), metadata + + client.retrieve_latest_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_accept_terms_of_service_rest_bad_request(request_type=termsofservice.AcceptTermsOfServiceRequest): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + 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.accept_terms_of_service(request) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.AcceptTermsOfServiceRequest, + dict, +]) +def test_accept_terms_of_service_rest_call_success(request_type): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofservice.AcceptTermsOfServiceResponse( + ) + + # 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 = termsofservice.AcceptTermsOfServiceResponse.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.accept_terms_of_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.AcceptTermsOfServiceResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_accept_terms_of_service_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), + ) + client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_accept_terms_of_service") as post, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_accept_terms_of_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_accept_terms_of_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofservice.AcceptTermsOfServiceRequest.pb(termsofservice.AcceptTermsOfServiceRequest()) + 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 = termsofservice.AcceptTermsOfServiceResponse.to_json(termsofservice.AcceptTermsOfServiceResponse()) + req.return_value.content = return_value + + request = termsofservice.AcceptTermsOfServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofservice.AcceptTermsOfServiceResponse() + post_with_metadata.return_value = termsofservice.AcceptTermsOfServiceResponse(), metadata + + client.accept_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = TermsOfServiceServiceClient( + 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_get_terms_of_service_empty_call_rest(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + client.get_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.GetTermsOfServiceRequest() + + 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_retrieve_latest_terms_of_service_empty_call_rest(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + client.retrieve_latest_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() + + 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_accept_terms_of_service_empty_call_rest(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + client.accept_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.AcceptTermsOfServiceRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TermsOfServiceServiceGrpcTransport, + ) + +def test_terms_of_service_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TermsOfServiceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_terms_of_service_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TermsOfServiceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_terms_of_service', + 'retrieve_latest_terms_of_service', + 'accept_terms_of_service', + ) + 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_terms_of_service_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_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceServiceTransport( + 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_terms_of_service_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_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceServiceTransport() + adc.assert_called_once() + + +def test_terms_of_service_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) + TermsOfServiceServiceClient() + 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.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + ], +) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + transports.TermsOfServiceServiceRestTransport, + ], +) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, grpc_helpers), + (transports.TermsOfServiceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +def test_terms_of_service_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_terms_of_service_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.TermsOfServiceServiceRestTransport ( + 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_terms_of_service_service_host_no_port(transport_name): + client = TermsOfServiceServiceClient( + 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_terms_of_service_service_host_with_port(transport_name): + client = TermsOfServiceServiceClient( + 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_terms_of_service_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TermsOfServiceServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TermsOfServiceServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_terms_of_service._session + session2 = client2.transport.get_terms_of_service._session + assert session1 != session2 + session1 = client1.transport.retrieve_latest_terms_of_service._session + session2 = client2.transport.retrieve_latest_terms_of_service._session + assert session1 != session2 + session1 = client1.transport.accept_terms_of_service._session + session2 = client2.transport.accept_terms_of_service._session + assert session1 != session2 +def test_terms_of_service_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceServiceGrpcTransport( + 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_terms_of_service_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceServiceGrpcAsyncIOTransport( + 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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +def test_terms_of_service_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = TermsOfServiceServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = TermsOfServiceServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_account_path(path) + assert expected == actual + +def test_terms_of_service_path(): + version = "whelk" + expected = "termsOfService/{version}".format(version=version, ) + actual = TermsOfServiceServiceClient.terms_of_service_path(version) + assert expected == actual + + +def test_parse_terms_of_service_path(): + expected = { + "version": "octopus", + } + path = TermsOfServiceServiceClient.terms_of_service_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_terms_of_service_path(path) + assert expected == actual + +def test_terms_of_service_agreement_state_path(): + account = "oyster" + identifier = "nudibranch" + expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + actual = TermsOfServiceServiceClient.terms_of_service_agreement_state_path(account, identifier) + assert expected == actual + + +def test_parse_terms_of_service_agreement_state_path(): + expected = { + "account": "cuttlefish", + "identifier": "mussel", + } + path = TermsOfServiceServiceClient.terms_of_service_agreement_state_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_terms_of_service_agreement_state_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TermsOfServiceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = TermsOfServiceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = TermsOfServiceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = TermsOfServiceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TermsOfServiceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = TermsOfServiceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = TermsOfServiceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = TermsOfServiceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TermsOfServiceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = TermsOfServiceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.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.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TermsOfServiceServiceClient.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 = TermsOfServiceServiceClient( + 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 = TermsOfServiceServiceAsyncClient( + 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 = TermsOfServiceServiceClient( + 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 = TermsOfServiceServiceClient( + 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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport), +]) +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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py new file mode 100644 index 000000000000..55cb564a9d26 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py @@ -0,0 +1,5238 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1.services.user_service import UserServiceAsyncClient +from google.shopping.merchant_accounts_v1.services.user_service import UserServiceClient +from google.shopping.merchant_accounts_v1.services.user_service import pagers +from google.shopping.merchant_accounts_v1.services.user_service import transports +from google.shopping.merchant_accounts_v1.types import accessright +from google.shopping.merchant_accounts_v1.types import user +from google.shopping.merchant_accounts_v1.types import user as gsma_user +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 UserServiceClient._get_default_mtls_endpoint(None) is None + assert UserServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert UserServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert UserServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert UserServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + UserServiceClient._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 UserServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert UserServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert UserServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + UserServiceClient._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 UserServiceClient._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 UserServiceClient._get_client_cert_source(None, False) is None + assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert UserServiceClient._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 UserServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = UserServiceClient._DEFAULT_UNIVERSE + default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert UserServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == UserServiceClient.DEFAULT_MTLS_ENDPOINT + assert UserServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert UserServiceClient._get_api_endpoint(None, None, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT + assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT + assert UserServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert UserServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + UserServiceClient._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 UserServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert UserServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert UserServiceClient._get_universe_domain(None, None) == UserServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + UserServiceClient._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 = UserServiceClient(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 = UserServiceClient(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", [ + (UserServiceClient, "grpc"), + (UserServiceAsyncClient, "grpc_asyncio"), + (UserServiceClient, "rest"), +]) +def test_user_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.UserServiceGrpcTransport, "grpc"), + (transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserServiceRestTransport, "rest"), +]) +def test_user_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", [ + (UserServiceClient, "grpc"), + (UserServiceAsyncClient, "grpc_asyncio"), + (UserServiceClient, "rest"), +]) +def test_user_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_user_service_client_get_transport_class(): + transport = UserServiceClient.get_transport_class() + available_transports = [ + transports.UserServiceGrpcTransport, + transports.UserServiceRestTransport, + ] + assert transport in available_transports + + transport = UserServiceClient.get_transport_class("grpc") + assert transport == transports.UserServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), +]) +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +def test_user_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(UserServiceClient, '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(UserServiceClient, '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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "true"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "false"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (UserServiceClient, transports.UserServiceRestTransport, "rest", "true"), + (UserServiceClient, transports.UserServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_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", [ + UserServiceClient, UserServiceAsyncClient +]) +@mock.patch.object(UserServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceAsyncClient)) +def test_user_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", [ + UserServiceClient, UserServiceAsyncClient +]) +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +def test_user_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = UserServiceClient._DEFAULT_UNIVERSE + default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = UserServiceClient._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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), +]) +def test_user_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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (UserServiceClient, transports.UserServiceRestTransport, "rest", None), +]) +def test_user_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_user_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserServiceClient( + 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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_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", [ + user.GetUserRequest, + dict, +]) +def test_get_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = user.GetUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, user.User) + assert response.name == 'name_value' + assert response.state == user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +def test_get_user_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 = UserServiceClient( + 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 = user.GetUserRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user.GetUserRequest( + name='name_value', + ) + +def test_get_user_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 = UserServiceClient( + 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.get_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_user] = mock_rpc + request = {} + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user(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_get_user_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 = UserServiceAsyncClient( + 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.get_user in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_user] = mock_rpc + + request = {} + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user(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_get_user_async(transport: str = 'grpc_asyncio', request_type=user.GetUserRequest): + client = UserServiceAsyncClient( + 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.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = user.GetUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, user.User) + assert response.name == 'name_value' + assert response.state == user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + +def test_get_user_field_headers(): + client = UserServiceClient( + 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 = user.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = user.User() + client.get_user(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_get_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = user.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) + await client.get_user(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_get_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user( + 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_get_user_flattened_error(): + client = UserServiceClient( + 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.get_user( + user.GetUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user( + 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_get_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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.get_user( + user.GetUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.CreateUserRequest, + dict, +]) +def test_create_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + response = client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_user.CreateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +def test_create_user_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 = UserServiceClient( + 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 = gsma_user.CreateUserRequest( + parent='parent_value', + user_id='user_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_user.CreateUserRequest( + parent='parent_value', + user_id='user_id_value', + ) + +def test_create_user_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 = UserServiceClient( + 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.create_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_user] = mock_rpc + request = {} + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user(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_create_user_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 = UserServiceAsyncClient( + 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.create_user in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_user] = mock_rpc + + request = {} + await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user(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_create_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.CreateUserRequest): + client = UserServiceAsyncClient( + 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.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + response = await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_user.CreateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.asyncio +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) + +def test_create_user_field_headers(): + client = UserServiceClient( + 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 = gsma_user.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.create_user(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_create_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = gsma_user.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + await client.create_user(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_create_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user( + parent='parent_value', + user=gsma_user.User(name='name_value'), + user_id='user_id_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 + arg = args[0].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + + +def test_create_user_flattened_error(): + client = UserServiceClient( + 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.create_user( + gsma_user.CreateUserRequest(), + parent='parent_value', + user=gsma_user.User(name='name_value'), + user_id='user_id_value', + ) + +@pytest.mark.asyncio +async def test_create_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user( + parent='parent_value', + user=gsma_user.User(name='name_value'), + user_id='user_id_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 + arg = args[0].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + arg = args[0].user_id + mock_val = 'user_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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.create_user( + gsma_user.CreateUserRequest(), + parent='parent_value', + user=gsma_user.User(name='name_value'), + user_id='user_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + user.DeleteUserRequest, + dict, +]) +def test_delete_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = user.DeleteUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_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 = UserServiceClient( + 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 = user.DeleteUserRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user.DeleteUserRequest( + name='name_value', + ) + +def test_delete_user_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 = UserServiceClient( + 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_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_user] = mock_rpc + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(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_user_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 = UserServiceAsyncClient( + 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_user 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_user] = mock_rpc + + request = {} + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user(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_user_async(transport: str = 'grpc_asyncio', request_type=user.DeleteUserRequest): + client = UserServiceAsyncClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = user.DeleteUserRequest() + 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_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + +def test_delete_user_field_headers(): + client = UserServiceClient( + 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 = user.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(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_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = user.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(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_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__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_user( + 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_user_flattened_error(): + client = UserServiceClient( + 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_user( + user.DeleteUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__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_user( + 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_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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_user( + user.DeleteUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.UpdateUserRequest, + dict, +]) +def test_update_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + response = client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_user.UpdateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +def test_update_user_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 = UserServiceClient( + 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 = gsma_user.UpdateUserRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_user.UpdateUserRequest( + ) + +def test_update_user_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 = UserServiceClient( + 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.update_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_user] = mock_rpc + request = {} + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user(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_update_user_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 = UserServiceAsyncClient( + 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.update_user in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_user] = mock_rpc + + request = {} + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user(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_update_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.UpdateUserRequest): + client = UserServiceAsyncClient( + 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.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + response = await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_user.UpdateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + +def test_update_user_field_headers(): + client = UserServiceClient( + 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 = gsma_user.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.update_user(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', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = gsma_user.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + await client.update_user(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', + 'user.name=name_value', + ) in kw['metadata'] + + +def test_update_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_user_flattened_error(): + client = UserServiceClient( + 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.update_user( + gsma_user.UpdateUserRequest(), + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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.update_user( + gsma_user.UpdateUserRequest(), + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + user.ListUsersRequest, + dict, +]) +def test_list_users(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.ListUsersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = user.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_users_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 = UserServiceClient( + 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 = user.ListUsersRequest( + 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_users), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_users(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user.ListUsersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_users_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 = UserServiceClient( + 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_users in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_users] = mock_rpc + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_users(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_users_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 = UserServiceAsyncClient( + 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_users 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_users] = mock_rpc + + request = {} + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_users(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_users_async(transport: str = 'grpc_asyncio', request_type=user.ListUsersRequest): + client = UserServiceAsyncClient( + 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = user.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) + +def test_list_users_field_headers(): + client = UserServiceClient( + 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 = user.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = user.ListUsersResponse() + client.list_users(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_users_field_headers_async(): + client = UserServiceAsyncClient( + 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 = user.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) + await client.list_users(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_users_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.ListUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_users( + 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_users_flattened_error(): + client = UserServiceClient( + 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_users( + user.ListUsersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_users_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.ListUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_users( + 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_users_flattened_error_async(): + client = UserServiceAsyncClient( + 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_users( + user.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_pager(transport_name: str = "grpc"): + client = UserServiceClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_users(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, user.User) + for i in results) +def test_list_users_pages(transport_name: str = "grpc"): + client = UserServiceClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_users_async_pager(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users(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, user.User) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + 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_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_user_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 = UserServiceClient( + 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.get_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_user] = mock_rpc + + request = {} + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user(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_get_user_rest_required_fields(request_type=user.GetUserRequest): + transport_class = transports.UserServiceRestTransport + + 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()).get_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_user._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 = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user.User() + # 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 = user.User.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.get_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_rest_flattened(): + client = UserServiceClient( + 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 = user.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/users/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = user.User.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.get_user(**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/accounts/v1/{name=accounts/*/users/*}" % client.transport._host, args[1]) + + +def test_get_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user( + user.GetUserRequest(), + name='name_value', + ) + + +def test_create_user_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 = UserServiceClient( + 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.create_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_user] = mock_rpc + + request = {} + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user(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_create_user_rest_required_fields(request_type=gsma_user.CreateUserRequest): + transport_class = transports.UserServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_id"] = "" + 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 + assert "userId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userId" in jsonified_request + assert jsonified_request["userId"] == request_init["user_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userId"] = 'user_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("user_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "userId" in jsonified_request + assert jsonified_request["userId"] == 'user_id_value' + + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_user.User() + # 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 = gsma_user.User.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.create_user(request) + + expected_params = [ + ( + "userId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("userId", )) & set(("parent", "userId", ))) + + +def test_create_user_rest_flattened(): + client = UserServiceClient( + 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 = gsma_user.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user=gsma_user.User(name='name_value'), + user_id='user_id_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 = gsma_user.User.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.create_user(**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/accounts/v1/{parent=accounts/*}/users" % client.transport._host, args[1]) + + +def test_create_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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.create_user( + gsma_user.CreateUserRequest(), + parent='parent_value', + user=gsma_user.User(name='name_value'), + user_id='user_id_value', + ) + + +def test_delete_user_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 = UserServiceClient( + 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_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_user] = mock_rpc + + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(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_user_rest_required_fields(request_type=user.DeleteUserRequest): + transport_class = transports.UserServiceRestTransport + + 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_user._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_user._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 = UserServiceClient( + 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_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_rest_flattened(): + client = UserServiceClient( + 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/users/sample2'} + + # 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_user(**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/accounts/v1/{name=accounts/*/users/*}" % client.transport._host, args[1]) + + +def test_delete_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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_user( + user.DeleteUserRequest(), + name='name_value', + ) + + +def test_update_user_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 = UserServiceClient( + 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.update_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_user] = mock_rpc + + request = {} + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user(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_update_user_rest_required_fields(request_type=gsma_user.UpdateUserRequest): + transport_class = transports.UserServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_user.User() + # 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': "patch", + '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 = gsma_user.User.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.update_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("user", ))) + + +def test_update_user_rest_flattened(): + client = UserServiceClient( + 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 = gsma_user.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'user': {'name': 'accounts/sample1/users/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_user.User.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.update_user(**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/accounts/v1/{user.name=accounts/*/users/*}" % client.transport._host, args[1]) + + +def test_update_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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.update_user( + gsma_user.UpdateUserRequest(), + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_users_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 = UserServiceClient( + 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_users in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_users] = mock_rpc + + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_users(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_users_rest_required_fields(request_type=user.ListUsersRequest): + transport_class = transports.UserServiceRestTransport + + 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_users._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_users._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 = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user.ListUsersResponse() + # 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 = user.ListUsersResponse.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_users(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_users_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_users._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_users_rest_flattened(): + client = UserServiceClient( + 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 = user.ListUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = user.ListUsersResponse.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_users(**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/accounts/v1/{parent=accounts/*}/users" % client.transport._host, args[1]) + + +def test_list_users_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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_users( + user.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_rest_pager(transport: str = 'rest'): + client = UserServiceClient( + 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 = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(user.ListUsersResponse.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'} + + pager = client.list_users(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, user.User) + for i in results) + + pages = list(client.list_users(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserServiceClient( + 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 = UserServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + transports.UserServiceRestTransport, +]) +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 = UserServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = UserServiceClient( + 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_get_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = user.User() + client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.GetUserRequest() + + 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_create_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.CreateUserRequest() + + 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_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.DeleteUserRequest() + + 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_update_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.UpdateUserRequest() + + 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_list_users_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = user.ListUsersResponse() + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.ListUsersRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = UserServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = UserServiceAsyncClient( + 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_get_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + await client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.GetUserRequest() + + 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_create_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + await client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.CreateUserRequest() + + 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_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.DeleteUserRequest() + + 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_update_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + await client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.UpdateUserRequest() + + 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_list_users_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( + next_page_token='next_page_token_value', + )) + await client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.ListUsersRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = UserServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_user_rest_bad_request(request_type=user.GetUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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.get_user(request) + + +@pytest.mark.parametrize("request_type", [ + user.GetUserRequest, + dict, +]) +def test_get_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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 = user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + + # 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 = user.User.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.get_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user.User) + assert response.name == 'name_value' + assert response.state == user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_get_user") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_get_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_get_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = user.GetUserRequest.pb(user.GetUserRequest()) + 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 = user.User.to_json(user.User()) + req.return_value.content = return_value + + request = user.GetUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user.User() + post_with_metadata.return_value = user.User(), metadata + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_user_rest_bad_request(request_type=gsma_user.CreateUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_user(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.CreateUserRequest, + dict, +]) +def test_create_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["user"] = {'name': 'name_value', 'state': 1, 'access_rights': [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 = gsma_user.CreateUserRequest.meta.fields["user"] + + 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["user"].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["user"][field])): + del request_init["user"][field][i][subfield] + else: + del request_init["user"][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 = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + + # 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 = gsma_user.User.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.create_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_create_user") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_create_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_create_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_user.CreateUserRequest.pb(gsma_user.CreateUserRequest()) + 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 = gsma_user.User.to_json(gsma_user.User()) + req.return_value.content = return_value + + request = gsma_user.CreateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_user.User() + post_with_metadata.return_value = gsma_user.User(), metadata + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_rest_bad_request(request_type=user.DeleteUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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.delete_user(request) + + +@pytest.mark.parametrize("request_type", [ + user.DeleteUserRequest, + dict, +]) +def test_delete_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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 = 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_user(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_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "pre_delete_user") as pre: + pre.assert_not_called() + pb_message = user.DeleteUserRequest.pb(user.DeleteUserRequest()) + 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 = user.DeleteUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_update_user_rest_bad_request(request_type=gsma_user.UpdateUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'accounts/sample1/users/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.update_user(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.UpdateUserRequest, + dict, +]) +def test_update_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'accounts/sample1/users/sample2'}} + request_init["user"] = {'name': 'accounts/sample1/users/sample2', 'state': 1, 'access_rights': [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 = gsma_user.UpdateUserRequest.meta.fields["user"] + + 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["user"].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["user"][field])): + del request_init["user"][field][i][subfield] + else: + del request_init["user"][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 = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + + # 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 = gsma_user.User.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.update_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_update_user") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_update_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_update_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_user.UpdateUserRequest.pb(gsma_user.UpdateUserRequest()) + 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 = gsma_user.User.to_json(gsma_user.User()) + req.return_value.content = return_value + + request = gsma_user.UpdateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_user.User() + post_with_metadata.return_value = gsma_user.User(), metadata + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_users_rest_bad_request(request_type=user.ListUsersRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_users(request) + + +@pytest.mark.parametrize("request_type", [ + user.ListUsersRequest, + dict, +]) +def test_list_users_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = user.ListUsersResponse( + 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 = user.ListUsersResponse.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_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_users_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_list_users") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_list_users_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_list_users") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = user.ListUsersRequest.pb(user.ListUsersRequest()) + 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 = user.ListUsersResponse.to_json(user.ListUsersResponse()) + req.return_value.content = return_value + + request = user.ListUsersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user.ListUsersResponse() + post_with_metadata.return_value = user.ListUsersResponse(), metadata + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = UserServiceClient( + 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_get_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.GetUserRequest() + + 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_create_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.CreateUserRequest() + + 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_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.DeleteUserRequest() + + 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_update_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.UpdateUserRequest() + + 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_list_users_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.ListUsersRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserServiceGrpcTransport, + ) + +def test_user_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_user', + 'create_user', + 'delete_user', + 'update_user', + 'list_users', + ) + 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_user_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_accounts_v1.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserServiceTransport( + 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_user_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_accounts_v1.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserServiceTransport() + adc.assert_called_once() + + +def test_user_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) + UserServiceClient() + 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.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + ], +) +def test_user_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.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + transports.UserServiceRestTransport, + ], +) +def test_user_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.UserServiceGrpcTransport, grpc_helpers), + (transports.UserServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) +def test_user_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_user_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.UserServiceRestTransport ( + 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_user_service_host_no_port(transport_name): + client = UserServiceClient( + 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_user_service_host_with_port(transport_name): + client = UserServiceClient( + 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_user_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = UserServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = UserServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_user._session + session2 = client2.transport.get_user._session + assert session1 != session2 + session1 = client1.transport.create_user._session + session2 = client2.transport.create_user._session + assert session1 != session2 + session1 = client1.transport.delete_user._session + session2 = client2.transport.delete_user._session + assert session1 != session2 + session1 = client1.transport.update_user._session + session2 = client2.transport.update_user._session + assert session1 != session2 + session1 = client1.transport.list_users._session + session2 = client2.transport.list_users._session + assert session1 != session2 +def test_user_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserServiceGrpcTransport( + 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_user_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserServiceGrpcAsyncIOTransport( + 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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) +def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) +def test_user_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = UserServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = UserServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_account_path(path) + assert expected == actual + +def test_user_path(): + account = "whelk" + email = "octopus" + expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) + actual = UserServiceClient.user_path(account, email) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "account": "oyster", + "email": "nudibranch", + } + path = UserServiceClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = UserServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = UserServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = UserServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = UserServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = UserServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.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 = UserServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = UserServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.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.UserServiceTransport, '_prep_wrapped_messages') as prep: + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserServiceClient.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 = UserServiceClient( + 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 = UserServiceAsyncClient( + 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 = UserServiceClient( + 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 = UserServiceClient( + 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", [ + (UserServiceClient, transports.UserServiceGrpcTransport), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.coveragerc new file mode 100644 index 000000000000..8338bbe3403b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/shopping/merchant_accounts/__init__.py + google/shopping/merchant_accounts/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-accounts/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/LICENSE b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst new file mode 100644 index 000000000000..419480c445c5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Shopping Merchant Accounts 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 Accounts 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-accounts/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/conf.py new file mode 100644 index 000000000000..11bd96e58d11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts 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-accounts" +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-accounts", + "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-accounts-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-accounts.tex", + u"google-shopping-merchant-accounts 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-accounts", + "google-shopping-merchant-accounts 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-accounts", + "google-shopping-merchant-accounts Documentation", + author, + "google-shopping-merchant-accounts", + "google-shopping-merchant-accounts 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-accounts/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst new file mode 100644 index 000000000000..eabb28aa260e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_accounts_v1beta/services_ + merchant_accounts_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst new file mode 100644 index 000000000000..a5f41b61ad72 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst @@ -0,0 +1,10 @@ +AccountIssueService +------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_issue_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_issue_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst new file mode 100644 index 000000000000..1693b3a3f8bd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst @@ -0,0 +1,10 @@ +AccountTaxService +----------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_tax_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_tax_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst new file mode 100644 index 000000000000..4b22494597e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst @@ -0,0 +1,10 @@ +AccountsService +--------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.accounts_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.accounts_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst new file mode 100644 index 000000000000..7d16dfb96a4b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst @@ -0,0 +1,6 @@ +AutofeedSettingsService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst new file mode 100644 index 000000000000..b6303ccd115d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst @@ -0,0 +1,6 @@ +AutomaticImprovementsService +---------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst new file mode 100644 index 000000000000..a80c213d4edf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst @@ -0,0 +1,6 @@ +BusinessIdentityService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.business_identity_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst new file mode 100644 index 000000000000..f5aa91c9d676 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst @@ -0,0 +1,6 @@ +BusinessInfoService +------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.business_info_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst new file mode 100644 index 000000000000..fb09ef58f132 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst @@ -0,0 +1,6 @@ +CheckoutSettingsService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.checkout_settings_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst new file mode 100644 index 000000000000..28be8558fb89 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst @@ -0,0 +1,6 @@ +EmailPreferencesService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.email_preferences_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst new file mode 100644 index 000000000000..0e88935e0a26 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst @@ -0,0 +1,10 @@ +GbpAccountsService +------------------------------------ + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst new file mode 100644 index 000000000000..ce83ca532741 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst @@ -0,0 +1,6 @@ +HomepageService +--------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.homepage_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst new file mode 100644 index 000000000000..922ff6981cdc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst @@ -0,0 +1,10 @@ +LfpProvidersService +------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.lfp_providers_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst new file mode 100644 index 000000000000..a4bb28c60424 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst @@ -0,0 +1,10 @@ +OmnichannelSettingsService +-------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst new file mode 100644 index 000000000000..4ebc9d8a8966 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst @@ -0,0 +1,10 @@ +OnlineReturnPolicyService +------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.online_return_policy_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst new file mode 100644 index 000000000000..b69123082e7d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst @@ -0,0 +1,10 @@ +ProgramsService +--------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.programs_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.programs_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst new file mode 100644 index 000000000000..5516e7ccd805 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst @@ -0,0 +1,10 @@ +RegionsService +-------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.regions_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.regions_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst new file mode 100644 index 000000000000..7867c8a21080 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst @@ -0,0 +1,25 @@ +Services for Google Shopping Merchant Accounts v1beta API +========================================================= +.. toctree:: + :maxdepth: 2 + + account_issue_service + accounts_service + account_tax_service + autofeed_settings_service + automatic_improvements_service + business_identity_service + business_info_service + checkout_settings_service + email_preferences_service + gbp_accounts_service + homepage_service + lfp_providers_service + omnichannel_settings_service + online_return_policy_service + programs_service + regions_service + shipping_settings_service + terms_of_service_agreement_state_service + terms_of_service_service + user_service diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst new file mode 100644 index 000000000000..95f333afb030 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst @@ -0,0 +1,6 @@ +ShippingSettingsService +----------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.shipping_settings_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst new file mode 100644 index 000000000000..ea377121c221 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst @@ -0,0 +1,6 @@ +TermsOfServiceAgreementStateService +----------------------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst new file mode 100644 index 000000000000..2aae813b00c9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst @@ -0,0 +1,6 @@ +TermsOfServiceService +--------------------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.terms_of_service_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst new file mode 100644 index 000000000000..3a0ebb568c5a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Shopping Merchant Accounts v1beta API +====================================================== + +.. automodule:: google.shopping.merchant_accounts_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst new file mode 100644 index 000000000000..4179b3c56145 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst @@ -0,0 +1,10 @@ +UserService +----------------------------- + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.user_service + :members: + :inherited-members: + +.. automodule:: google.shopping.merchant_accounts_v1beta.services.user_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/google/shopping/merchant_accounts/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py new file mode 100644 index 000000000000..6c30f934f357 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py @@ -0,0 +1,371 @@ +# -*- 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_accounts import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.shopping.merchant_accounts_v1beta.services.account_issue_service.client import AccountIssueServiceClient +from google.shopping.merchant_accounts_v1beta.services.account_issue_service.async_client import AccountIssueServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.accounts_service.client import AccountsServiceClient +from google.shopping.merchant_accounts_v1beta.services.accounts_service.async_client import AccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.account_tax_service.client import AccountTaxServiceClient +from google.shopping.merchant_accounts_v1beta.services.account_tax_service.async_client import AccountTaxServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.client import AutofeedSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.async_client import AutofeedSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.client import AutomaticImprovementsServiceClient +from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.async_client import AutomaticImprovementsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.business_identity_service.client import BusinessIdentityServiceClient +from google.shopping.merchant_accounts_v1beta.services.business_identity_service.async_client import BusinessIdentityServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.business_info_service.client import BusinessInfoServiceClient +from google.shopping.merchant_accounts_v1beta.services.business_info_service.async_client import BusinessInfoServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.client import CheckoutSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.async_client import CheckoutSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.email_preferences_service.client import EmailPreferencesServiceClient +from google.shopping.merchant_accounts_v1beta.services.email_preferences_service.async_client import EmailPreferencesServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.client import GbpAccountsServiceClient +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.async_client import GbpAccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.homepage_service.client import HomepageServiceClient +from google.shopping.merchant_accounts_v1beta.services.homepage_service.async_client import HomepageServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.client import LfpProvidersServiceClient +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.async_client import LfpProvidersServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.client import OmnichannelSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.async_client import OmnichannelSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.client import OnlineReturnPolicyServiceClient +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.async_client import OnlineReturnPolicyServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.programs_service.client import ProgramsServiceClient +from google.shopping.merchant_accounts_v1beta.services.programs_service.async_client import ProgramsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.regions_service.client import RegionsServiceClient +from google.shopping.merchant_accounts_v1beta.services.regions_service.async_client import RegionsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.client import ShippingSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.async_client import ShippingSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.client import TermsOfServiceAgreementStateServiceClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.async_client import TermsOfServiceAgreementStateServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.client import TermsOfServiceServiceClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.async_client import TermsOfServiceServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.user_service.client import UserServiceClient +from google.shopping.merchant_accounts_v1beta.services.user_service.async_client import UserServiceAsyncClient + +from google.shopping.merchant_accounts_v1beta.types.accessright import AccessRight +from google.shopping.merchant_accounts_v1beta.types.account_tax import AccountTax +from google.shopping.merchant_accounts_v1beta.types.account_tax import GetAccountTaxRequest +from google.shopping.merchant_accounts_v1beta.types.account_tax import ListAccountTaxRequest +from google.shopping.merchant_accounts_v1beta.types.account_tax import ListAccountTaxResponse +from google.shopping.merchant_accounts_v1beta.types.account_tax import UpdateAccountTaxRequest +from google.shopping.merchant_accounts_v1beta.types.accountissue import AccountIssue +from google.shopping.merchant_accounts_v1beta.types.accountissue import ListAccountIssuesRequest +from google.shopping.merchant_accounts_v1beta.types.accountissue import ListAccountIssuesResponse +from google.shopping.merchant_accounts_v1beta.types.accounts import Account +from google.shopping.merchant_accounts_v1beta.types.accounts import CreateAndConfigureAccountRequest +from google.shopping.merchant_accounts_v1beta.types.accounts import DeleteAccountRequest +from google.shopping.merchant_accounts_v1beta.types.accounts import GetAccountRequest +from google.shopping.merchant_accounts_v1beta.types.accounts import ListAccountsRequest +from google.shopping.merchant_accounts_v1beta.types.accounts import ListAccountsResponse +from google.shopping.merchant_accounts_v1beta.types.accounts import ListSubAccountsRequest +from google.shopping.merchant_accounts_v1beta.types.accounts import ListSubAccountsResponse +from google.shopping.merchant_accounts_v1beta.types.accounts import UpdateAccountRequest +from google.shopping.merchant_accounts_v1beta.types.accountservices import AccountAggregation +from google.shopping.merchant_accounts_v1beta.types.autofeedsettings import AutofeedSettings +from google.shopping.merchant_accounts_v1beta.types.autofeedsettings import GetAutofeedSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.autofeedsettings import UpdateAutofeedSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticImageImprovements +from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticImprovements +from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticItemUpdates +from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticShippingImprovements +from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import GetAutomaticImprovementsRequest +from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import UpdateAutomaticImprovementsRequest +from google.shopping.merchant_accounts_v1beta.types.businessidentity import BusinessIdentity +from google.shopping.merchant_accounts_v1beta.types.businessidentity import GetBusinessIdentityRequest +from google.shopping.merchant_accounts_v1beta.types.businessidentity import UpdateBusinessIdentityRequest +from google.shopping.merchant_accounts_v1beta.types.businessinfo import BusinessInfo +from google.shopping.merchant_accounts_v1beta.types.businessinfo import GetBusinessInfoRequest +from google.shopping.merchant_accounts_v1beta.types.businessinfo import UpdateBusinessInfoRequest +from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import CheckoutSettings +from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import CreateCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import DeleteCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import GetCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import UpdateCheckoutSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import UriSettings +from google.shopping.merchant_accounts_v1beta.types.customerservice import CustomerService +from google.shopping.merchant_accounts_v1beta.types.emailpreferences import EmailPreferences +from google.shopping.merchant_accounts_v1beta.types.emailpreferences import GetEmailPreferencesRequest +from google.shopping.merchant_accounts_v1beta.types.emailpreferences import UpdateEmailPreferencesRequest +from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import GbpAccount +from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import LinkGbpAccountRequest +from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import LinkGbpAccountResponse +from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import ListGbpAccountsRequest +from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import ListGbpAccountsResponse +from google.shopping.merchant_accounts_v1beta.types.homepage import ClaimHomepageRequest +from google.shopping.merchant_accounts_v1beta.types.homepage import GetHomepageRequest +from google.shopping.merchant_accounts_v1beta.types.homepage import Homepage +from google.shopping.merchant_accounts_v1beta.types.homepage import UnclaimHomepageRequest +from google.shopping.merchant_accounts_v1beta.types.homepage import UpdateHomepageRequest +from google.shopping.merchant_accounts_v1beta.types.lfpproviders import FindLfpProvidersRequest +from google.shopping.merchant_accounts_v1beta.types.lfpproviders import FindLfpProvidersResponse +from google.shopping.merchant_accounts_v1beta.types.lfpproviders import LfpProvider +from google.shopping.merchant_accounts_v1beta.types.lfpproviders import LinkLfpProviderRequest +from google.shopping.merchant_accounts_v1beta.types.lfpproviders import LinkLfpProviderResponse +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import About +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import CreateOmnichannelSettingRequest +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import GetOmnichannelSettingRequest +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import InStock +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import InventoryVerification +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import LfpLink +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import ListOmnichannelSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import ListOmnichannelSettingsResponse +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import OmnichannelSetting +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import OnDisplayToOrder +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import Pickup +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import RequestInventoryVerificationRequest +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import RequestInventoryVerificationResponse +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import ReviewState +from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import UpdateOmnichannelSettingRequest +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import CreateOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import DeleteOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import GetOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import ListOnlineReturnPoliciesRequest +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import ListOnlineReturnPoliciesResponse +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import OnlineReturnPolicy +from google.shopping.merchant_accounts_v1beta.types.online_return_policy import UpdateOnlineReturnPolicyRequest +from google.shopping.merchant_accounts_v1beta.types.phoneverificationstate import PhoneVerificationState +from google.shopping.merchant_accounts_v1beta.types.programs import DisableProgramRequest +from google.shopping.merchant_accounts_v1beta.types.programs import EnableProgramRequest +from google.shopping.merchant_accounts_v1beta.types.programs import GetProgramRequest +from google.shopping.merchant_accounts_v1beta.types.programs import ListProgramsRequest +from google.shopping.merchant_accounts_v1beta.types.programs import ListProgramsResponse +from google.shopping.merchant_accounts_v1beta.types.programs import Program +from google.shopping.merchant_accounts_v1beta.types.regions import CreateRegionRequest +from google.shopping.merchant_accounts_v1beta.types.regions import DeleteRegionRequest +from google.shopping.merchant_accounts_v1beta.types.regions import GetRegionRequest +from google.shopping.merchant_accounts_v1beta.types.regions import ListRegionsRequest +from google.shopping.merchant_accounts_v1beta.types.regions import ListRegionsResponse +from google.shopping.merchant_accounts_v1beta.types.regions import Region +from google.shopping.merchant_accounts_v1beta.types.regions import UpdateRegionRequest +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Address +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import BusinessDayConfig +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import CarrierRate +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import CutoffTime +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import DeliveryTime +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Distance +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import GetShippingSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Headers +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import InsertShippingSettingsRequest +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import LocationIdSet +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import MinimumOrderValueTable +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import RateGroup +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Row +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Service +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import ShippingSettings +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Table +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import TransitTable +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Value +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Warehouse +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import WarehouseBasedDeliveryTime +from google.shopping.merchant_accounts_v1beta.types.shippingsettings import WarehouseCutoffTime +from google.shopping.merchant_accounts_v1beta.types.tax_rule import TaxRule +from google.shopping.merchant_accounts_v1beta.types.termsofservice import AcceptTermsOfServiceRequest +from google.shopping.merchant_accounts_v1beta.types.termsofservice import GetTermsOfServiceRequest +from google.shopping.merchant_accounts_v1beta.types.termsofservice import RetrieveLatestTermsOfServiceRequest +from google.shopping.merchant_accounts_v1beta.types.termsofservice import TermsOfService +from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import Accepted +from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest +from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import Required +from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest +from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import TermsOfServiceAgreementState +from google.shopping.merchant_accounts_v1beta.types.termsofservicekind import TermsOfServiceKind +from google.shopping.merchant_accounts_v1beta.types.user import CreateUserRequest +from google.shopping.merchant_accounts_v1beta.types.user import DeleteUserRequest +from google.shopping.merchant_accounts_v1beta.types.user import GetUserRequest +from google.shopping.merchant_accounts_v1beta.types.user import ListUsersRequest +from google.shopping.merchant_accounts_v1beta.types.user import ListUsersResponse +from google.shopping.merchant_accounts_v1beta.types.user import UpdateUserRequest +from google.shopping.merchant_accounts_v1beta.types.user import User + +__all__ = ('AccountIssueServiceClient', + 'AccountIssueServiceAsyncClient', + 'AccountsServiceClient', + 'AccountsServiceAsyncClient', + 'AccountTaxServiceClient', + 'AccountTaxServiceAsyncClient', + 'AutofeedSettingsServiceClient', + 'AutofeedSettingsServiceAsyncClient', + 'AutomaticImprovementsServiceClient', + 'AutomaticImprovementsServiceAsyncClient', + 'BusinessIdentityServiceClient', + 'BusinessIdentityServiceAsyncClient', + 'BusinessInfoServiceClient', + 'BusinessInfoServiceAsyncClient', + 'CheckoutSettingsServiceClient', + 'CheckoutSettingsServiceAsyncClient', + 'EmailPreferencesServiceClient', + 'EmailPreferencesServiceAsyncClient', + 'GbpAccountsServiceClient', + 'GbpAccountsServiceAsyncClient', + 'HomepageServiceClient', + 'HomepageServiceAsyncClient', + 'LfpProvidersServiceClient', + 'LfpProvidersServiceAsyncClient', + 'OmnichannelSettingsServiceClient', + 'OmnichannelSettingsServiceAsyncClient', + 'OnlineReturnPolicyServiceClient', + 'OnlineReturnPolicyServiceAsyncClient', + 'ProgramsServiceClient', + 'ProgramsServiceAsyncClient', + 'RegionsServiceClient', + 'RegionsServiceAsyncClient', + 'ShippingSettingsServiceClient', + 'ShippingSettingsServiceAsyncClient', + 'TermsOfServiceAgreementStateServiceClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', + 'TermsOfServiceServiceClient', + 'TermsOfServiceServiceAsyncClient', + 'UserServiceClient', + 'UserServiceAsyncClient', + 'AccessRight', + 'AccountTax', + 'GetAccountTaxRequest', + 'ListAccountTaxRequest', + 'ListAccountTaxResponse', + 'UpdateAccountTaxRequest', + 'AccountIssue', + 'ListAccountIssuesRequest', + 'ListAccountIssuesResponse', + 'Account', + 'CreateAndConfigureAccountRequest', + 'DeleteAccountRequest', + 'GetAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListSubAccountsRequest', + 'ListSubAccountsResponse', + 'UpdateAccountRequest', + 'AccountAggregation', + 'AutofeedSettings', + 'GetAutofeedSettingsRequest', + 'UpdateAutofeedSettingsRequest', + 'AutomaticImageImprovements', + 'AutomaticImprovements', + 'AutomaticItemUpdates', + 'AutomaticShippingImprovements', + 'GetAutomaticImprovementsRequest', + 'UpdateAutomaticImprovementsRequest', + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + 'CheckoutSettings', + 'CreateCheckoutSettingsRequest', + 'DeleteCheckoutSettingsRequest', + 'GetCheckoutSettingsRequest', + 'UpdateCheckoutSettingsRequest', + 'UriSettings', + 'CustomerService', + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + 'GbpAccount', + 'LinkGbpAccountRequest', + 'LinkGbpAccountResponse', + 'ListGbpAccountsRequest', + 'ListGbpAccountsResponse', + 'ClaimHomepageRequest', + 'GetHomepageRequest', + 'Homepage', + 'UnclaimHomepageRequest', + 'UpdateHomepageRequest', + 'FindLfpProvidersRequest', + 'FindLfpProvidersResponse', + 'LfpProvider', + 'LinkLfpProviderRequest', + 'LinkLfpProviderResponse', + 'About', + 'CreateOmnichannelSettingRequest', + 'GetOmnichannelSettingRequest', + 'InStock', + 'InventoryVerification', + 'LfpLink', + 'ListOmnichannelSettingsRequest', + 'ListOmnichannelSettingsResponse', + 'OmnichannelSetting', + 'OnDisplayToOrder', + 'Pickup', + 'RequestInventoryVerificationRequest', + 'RequestInventoryVerificationResponse', + 'ReviewState', + 'UpdateOmnichannelSettingRequest', + 'CreateOnlineReturnPolicyRequest', + 'DeleteOnlineReturnPolicyRequest', + 'GetOnlineReturnPolicyRequest', + 'ListOnlineReturnPoliciesRequest', + 'ListOnlineReturnPoliciesResponse', + 'OnlineReturnPolicy', + 'UpdateOnlineReturnPolicyRequest', + 'PhoneVerificationState', + 'DisableProgramRequest', + 'EnableProgramRequest', + 'GetProgramRequest', + 'ListProgramsRequest', + 'ListProgramsResponse', + 'Program', + 'CreateRegionRequest', + 'DeleteRegionRequest', + 'GetRegionRequest', + 'ListRegionsRequest', + 'ListRegionsResponse', + 'Region', + 'UpdateRegionRequest', + 'Address', + 'BusinessDayConfig', + 'CarrierRate', + 'CutoffTime', + 'DeliveryTime', + 'Distance', + 'GetShippingSettingsRequest', + 'Headers', + 'InsertShippingSettingsRequest', + 'LocationIdSet', + 'MinimumOrderValueTable', + 'RateGroup', + 'Row', + 'Service', + 'ShippingSettings', + 'Table', + 'TransitTable', + 'Value', + 'Warehouse', + 'WarehouseBasedDeliveryTime', + 'WarehouseCutoffTime', + 'TaxRule', + 'AcceptTermsOfServiceRequest', + 'GetTermsOfServiceRequest', + 'RetrieveLatestTermsOfServiceRequest', + 'TermsOfService', + 'Accepted', + 'GetTermsOfServiceAgreementStateRequest', + 'Required', + 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + 'TermsOfServiceAgreementState', + 'TermsOfServiceKind', + 'CreateUserRequest', + 'DeleteUserRequest', + 'GetUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + 'UpdateUserRequest', + 'User', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/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-accounts/v1beta/google/shopping/merchant_accounts/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/py.typed new file mode 100644 index 000000000000..19aa2588b0f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py new file mode 100644 index 000000000000..845ae3aa592c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py @@ -0,0 +1,372 @@ +# -*- 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_accounts_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.account_issue_service import AccountIssueServiceClient +from .services.account_issue_service import AccountIssueServiceAsyncClient +from .services.accounts_service import AccountsServiceClient +from .services.accounts_service import AccountsServiceAsyncClient +from .services.account_tax_service import AccountTaxServiceClient +from .services.account_tax_service import AccountTaxServiceAsyncClient +from .services.autofeed_settings_service import AutofeedSettingsServiceClient +from .services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient +from .services.automatic_improvements_service import AutomaticImprovementsServiceClient +from .services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient +from .services.business_identity_service import BusinessIdentityServiceClient +from .services.business_identity_service import BusinessIdentityServiceAsyncClient +from .services.business_info_service import BusinessInfoServiceClient +from .services.business_info_service import BusinessInfoServiceAsyncClient +from .services.checkout_settings_service import CheckoutSettingsServiceClient +from .services.checkout_settings_service import CheckoutSettingsServiceAsyncClient +from .services.email_preferences_service import EmailPreferencesServiceClient +from .services.email_preferences_service import EmailPreferencesServiceAsyncClient +from .services.gbp_accounts_service import GbpAccountsServiceClient +from .services.gbp_accounts_service import GbpAccountsServiceAsyncClient +from .services.homepage_service import HomepageServiceClient +from .services.homepage_service import HomepageServiceAsyncClient +from .services.lfp_providers_service import LfpProvidersServiceClient +from .services.lfp_providers_service import LfpProvidersServiceAsyncClient +from .services.omnichannel_settings_service import OmnichannelSettingsServiceClient +from .services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient +from .services.online_return_policy_service import OnlineReturnPolicyServiceClient +from .services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient +from .services.programs_service import ProgramsServiceClient +from .services.programs_service import ProgramsServiceAsyncClient +from .services.regions_service import RegionsServiceClient +from .services.regions_service import RegionsServiceAsyncClient +from .services.shipping_settings_service import ShippingSettingsServiceClient +from .services.shipping_settings_service import ShippingSettingsServiceAsyncClient +from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient +from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient +from .services.terms_of_service_service import TermsOfServiceServiceClient +from .services.terms_of_service_service import TermsOfServiceServiceAsyncClient +from .services.user_service import UserServiceClient +from .services.user_service import UserServiceAsyncClient + +from .types.accessright import AccessRight +from .types.account_tax import AccountTax +from .types.account_tax import GetAccountTaxRequest +from .types.account_tax import ListAccountTaxRequest +from .types.account_tax import ListAccountTaxResponse +from .types.account_tax import UpdateAccountTaxRequest +from .types.accountissue import AccountIssue +from .types.accountissue import ListAccountIssuesRequest +from .types.accountissue import ListAccountIssuesResponse +from .types.accounts import Account +from .types.accounts import CreateAndConfigureAccountRequest +from .types.accounts import DeleteAccountRequest +from .types.accounts import GetAccountRequest +from .types.accounts import ListAccountsRequest +from .types.accounts import ListAccountsResponse +from .types.accounts import ListSubAccountsRequest +from .types.accounts import ListSubAccountsResponse +from .types.accounts import UpdateAccountRequest +from .types.accountservices import AccountAggregation +from .types.autofeedsettings import AutofeedSettings +from .types.autofeedsettings import GetAutofeedSettingsRequest +from .types.autofeedsettings import UpdateAutofeedSettingsRequest +from .types.automaticimprovements import AutomaticImageImprovements +from .types.automaticimprovements import AutomaticImprovements +from .types.automaticimprovements import AutomaticItemUpdates +from .types.automaticimprovements import AutomaticShippingImprovements +from .types.automaticimprovements import GetAutomaticImprovementsRequest +from .types.automaticimprovements import UpdateAutomaticImprovementsRequest +from .types.businessidentity import BusinessIdentity +from .types.businessidentity import GetBusinessIdentityRequest +from .types.businessidentity import UpdateBusinessIdentityRequest +from .types.businessinfo import BusinessInfo +from .types.businessinfo import GetBusinessInfoRequest +from .types.businessinfo import UpdateBusinessInfoRequest +from .types.checkoutsettings import CheckoutSettings +from .types.checkoutsettings import CreateCheckoutSettingsRequest +from .types.checkoutsettings import DeleteCheckoutSettingsRequest +from .types.checkoutsettings import GetCheckoutSettingsRequest +from .types.checkoutsettings import UpdateCheckoutSettingsRequest +from .types.checkoutsettings import UriSettings +from .types.customerservice import CustomerService +from .types.emailpreferences import EmailPreferences +from .types.emailpreferences import GetEmailPreferencesRequest +from .types.emailpreferences import UpdateEmailPreferencesRequest +from .types.gbpaccounts import GbpAccount +from .types.gbpaccounts import LinkGbpAccountRequest +from .types.gbpaccounts import LinkGbpAccountResponse +from .types.gbpaccounts import ListGbpAccountsRequest +from .types.gbpaccounts import ListGbpAccountsResponse +from .types.homepage import ClaimHomepageRequest +from .types.homepage import GetHomepageRequest +from .types.homepage import Homepage +from .types.homepage import UnclaimHomepageRequest +from .types.homepage import UpdateHomepageRequest +from .types.lfpproviders import FindLfpProvidersRequest +from .types.lfpproviders import FindLfpProvidersResponse +from .types.lfpproviders import LfpProvider +from .types.lfpproviders import LinkLfpProviderRequest +from .types.lfpproviders import LinkLfpProviderResponse +from .types.omnichannelsettings import About +from .types.omnichannelsettings import CreateOmnichannelSettingRequest +from .types.omnichannelsettings import GetOmnichannelSettingRequest +from .types.omnichannelsettings import InStock +from .types.omnichannelsettings import InventoryVerification +from .types.omnichannelsettings import LfpLink +from .types.omnichannelsettings import ListOmnichannelSettingsRequest +from .types.omnichannelsettings import ListOmnichannelSettingsResponse +from .types.omnichannelsettings import OmnichannelSetting +from .types.omnichannelsettings import OnDisplayToOrder +from .types.omnichannelsettings import Pickup +from .types.omnichannelsettings import RequestInventoryVerificationRequest +from .types.omnichannelsettings import RequestInventoryVerificationResponse +from .types.omnichannelsettings import ReviewState +from .types.omnichannelsettings import UpdateOmnichannelSettingRequest +from .types.online_return_policy import CreateOnlineReturnPolicyRequest +from .types.online_return_policy import DeleteOnlineReturnPolicyRequest +from .types.online_return_policy import GetOnlineReturnPolicyRequest +from .types.online_return_policy import ListOnlineReturnPoliciesRequest +from .types.online_return_policy import ListOnlineReturnPoliciesResponse +from .types.online_return_policy import OnlineReturnPolicy +from .types.online_return_policy import UpdateOnlineReturnPolicyRequest +from .types.phoneverificationstate import PhoneVerificationState +from .types.programs import DisableProgramRequest +from .types.programs import EnableProgramRequest +from .types.programs import GetProgramRequest +from .types.programs import ListProgramsRequest +from .types.programs import ListProgramsResponse +from .types.programs import Program +from .types.regions import CreateRegionRequest +from .types.regions import DeleteRegionRequest +from .types.regions import GetRegionRequest +from .types.regions import ListRegionsRequest +from .types.regions import ListRegionsResponse +from .types.regions import Region +from .types.regions import UpdateRegionRequest +from .types.shippingsettings import Address +from .types.shippingsettings import BusinessDayConfig +from .types.shippingsettings import CarrierRate +from .types.shippingsettings import CutoffTime +from .types.shippingsettings import DeliveryTime +from .types.shippingsettings import Distance +from .types.shippingsettings import GetShippingSettingsRequest +from .types.shippingsettings import Headers +from .types.shippingsettings import InsertShippingSettingsRequest +from .types.shippingsettings import LocationIdSet +from .types.shippingsettings import MinimumOrderValueTable +from .types.shippingsettings import RateGroup +from .types.shippingsettings import Row +from .types.shippingsettings import Service +from .types.shippingsettings import ShippingSettings +from .types.shippingsettings import Table +from .types.shippingsettings import TransitTable +from .types.shippingsettings import Value +from .types.shippingsettings import Warehouse +from .types.shippingsettings import WarehouseBasedDeliveryTime +from .types.shippingsettings import WarehouseCutoffTime +from .types.tax_rule import TaxRule +from .types.termsofservice import AcceptTermsOfServiceRequest +from .types.termsofservice import GetTermsOfServiceRequest +from .types.termsofservice import RetrieveLatestTermsOfServiceRequest +from .types.termsofservice import TermsOfService +from .types.termsofserviceagreementstate import Accepted +from .types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest +from .types.termsofserviceagreementstate import Required +from .types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest +from .types.termsofserviceagreementstate import TermsOfServiceAgreementState +from .types.termsofservicekind import TermsOfServiceKind +from .types.user import CreateUserRequest +from .types.user import DeleteUserRequest +from .types.user import GetUserRequest +from .types.user import ListUsersRequest +from .types.user import ListUsersResponse +from .types.user import UpdateUserRequest +from .types.user import User + +__all__ = ( + 'AccountIssueServiceAsyncClient', + 'AccountTaxServiceAsyncClient', + 'AccountsServiceAsyncClient', + 'AutofeedSettingsServiceAsyncClient', + 'AutomaticImprovementsServiceAsyncClient', + 'BusinessIdentityServiceAsyncClient', + 'BusinessInfoServiceAsyncClient', + 'CheckoutSettingsServiceAsyncClient', + 'EmailPreferencesServiceAsyncClient', + 'GbpAccountsServiceAsyncClient', + 'HomepageServiceAsyncClient', + 'LfpProvidersServiceAsyncClient', + 'OmnichannelSettingsServiceAsyncClient', + 'OnlineReturnPolicyServiceAsyncClient', + 'ProgramsServiceAsyncClient', + 'RegionsServiceAsyncClient', + 'ShippingSettingsServiceAsyncClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', + 'TermsOfServiceServiceAsyncClient', + 'UserServiceAsyncClient', +'About', +'AcceptTermsOfServiceRequest', +'Accepted', +'AccessRight', +'Account', +'AccountAggregation', +'AccountIssue', +'AccountIssueServiceClient', +'AccountTax', +'AccountTaxServiceClient', +'AccountsServiceClient', +'Address', +'AutofeedSettings', +'AutofeedSettingsServiceClient', +'AutomaticImageImprovements', +'AutomaticImprovements', +'AutomaticImprovementsServiceClient', +'AutomaticItemUpdates', +'AutomaticShippingImprovements', +'BusinessDayConfig', +'BusinessIdentity', +'BusinessIdentityServiceClient', +'BusinessInfo', +'BusinessInfoServiceClient', +'CarrierRate', +'CheckoutSettings', +'CheckoutSettingsServiceClient', +'ClaimHomepageRequest', +'CreateAndConfigureAccountRequest', +'CreateCheckoutSettingsRequest', +'CreateOmnichannelSettingRequest', +'CreateOnlineReturnPolicyRequest', +'CreateRegionRequest', +'CreateUserRequest', +'CustomerService', +'CutoffTime', +'DeleteAccountRequest', +'DeleteCheckoutSettingsRequest', +'DeleteOnlineReturnPolicyRequest', +'DeleteRegionRequest', +'DeleteUserRequest', +'DeliveryTime', +'DisableProgramRequest', +'Distance', +'EmailPreferences', +'EmailPreferencesServiceClient', +'EnableProgramRequest', +'FindLfpProvidersRequest', +'FindLfpProvidersResponse', +'GbpAccount', +'GbpAccountsServiceClient', +'GetAccountRequest', +'GetAccountTaxRequest', +'GetAutofeedSettingsRequest', +'GetAutomaticImprovementsRequest', +'GetBusinessIdentityRequest', +'GetBusinessInfoRequest', +'GetCheckoutSettingsRequest', +'GetEmailPreferencesRequest', +'GetHomepageRequest', +'GetOmnichannelSettingRequest', +'GetOnlineReturnPolicyRequest', +'GetProgramRequest', +'GetRegionRequest', +'GetShippingSettingsRequest', +'GetTermsOfServiceAgreementStateRequest', +'GetTermsOfServiceRequest', +'GetUserRequest', +'Headers', +'Homepage', +'HomepageServiceClient', +'InStock', +'InsertShippingSettingsRequest', +'InventoryVerification', +'LfpLink', +'LfpProvider', +'LfpProvidersServiceClient', +'LinkGbpAccountRequest', +'LinkGbpAccountResponse', +'LinkLfpProviderRequest', +'LinkLfpProviderResponse', +'ListAccountIssuesRequest', +'ListAccountIssuesResponse', +'ListAccountTaxRequest', +'ListAccountTaxResponse', +'ListAccountsRequest', +'ListAccountsResponse', +'ListGbpAccountsRequest', +'ListGbpAccountsResponse', +'ListOmnichannelSettingsRequest', +'ListOmnichannelSettingsResponse', +'ListOnlineReturnPoliciesRequest', +'ListOnlineReturnPoliciesResponse', +'ListProgramsRequest', +'ListProgramsResponse', +'ListRegionsRequest', +'ListRegionsResponse', +'ListSubAccountsRequest', +'ListSubAccountsResponse', +'ListUsersRequest', +'ListUsersResponse', +'LocationIdSet', +'MinimumOrderValueTable', +'OmnichannelSetting', +'OmnichannelSettingsServiceClient', +'OnDisplayToOrder', +'OnlineReturnPolicy', +'OnlineReturnPolicyServiceClient', +'PhoneVerificationState', +'Pickup', +'Program', +'ProgramsServiceClient', +'RateGroup', +'Region', +'RegionsServiceClient', +'RequestInventoryVerificationRequest', +'RequestInventoryVerificationResponse', +'Required', +'RetrieveForApplicationTermsOfServiceAgreementStateRequest', +'RetrieveLatestTermsOfServiceRequest', +'ReviewState', +'Row', +'Service', +'ShippingSettings', +'ShippingSettingsServiceClient', +'Table', +'TaxRule', +'TermsOfService', +'TermsOfServiceAgreementState', +'TermsOfServiceAgreementStateServiceClient', +'TermsOfServiceKind', +'TermsOfServiceServiceClient', +'TransitTable', +'UnclaimHomepageRequest', +'UpdateAccountRequest', +'UpdateAccountTaxRequest', +'UpdateAutofeedSettingsRequest', +'UpdateAutomaticImprovementsRequest', +'UpdateBusinessIdentityRequest', +'UpdateBusinessInfoRequest', +'UpdateCheckoutSettingsRequest', +'UpdateEmailPreferencesRequest', +'UpdateHomepageRequest', +'UpdateOmnichannelSettingRequest', +'UpdateOnlineReturnPolicyRequest', +'UpdateRegionRequest', +'UpdateUserRequest', +'UriSettings', +'User', +'UserServiceClient', +'Value', +'Warehouse', +'WarehouseBasedDeliveryTime', +'WarehouseCutoffTime', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..306403adf83a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json @@ -0,0 +1,1334 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.shopping.merchant_accounts_v1beta", + "protoPackage": "google.shopping.merchant.accounts.v1beta", + "schema": "1.0", + "services": { + "AccountIssueService": { + "clients": { + "grpc": { + "libraryClient": "AccountIssueServiceClient", + "rpcs": { + "ListAccountIssues": { + "methods": [ + "list_account_issues" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountIssueServiceAsyncClient", + "rpcs": { + "ListAccountIssues": { + "methods": [ + "list_account_issues" + ] + } + } + }, + "rest": { + "libraryClient": "AccountIssueServiceClient", + "rpcs": { + "ListAccountIssues": { + "methods": [ + "list_account_issues" + ] + } + } + } + } + }, + "AccountTaxService": { + "clients": { + "grpc": { + "libraryClient": "AccountTaxServiceClient", + "rpcs": { + "GetAccountTax": { + "methods": [ + "get_account_tax" + ] + }, + "ListAccountTax": { + "methods": [ + "list_account_tax" + ] + }, + "UpdateAccountTax": { + "methods": [ + "update_account_tax" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountTaxServiceAsyncClient", + "rpcs": { + "GetAccountTax": { + "methods": [ + "get_account_tax" + ] + }, + "ListAccountTax": { + "methods": [ + "list_account_tax" + ] + }, + "UpdateAccountTax": { + "methods": [ + "update_account_tax" + ] + } + } + }, + "rest": { + "libraryClient": "AccountTaxServiceClient", + "rpcs": { + "GetAccountTax": { + "methods": [ + "get_account_tax" + ] + }, + "ListAccountTax": { + "methods": [ + "list_account_tax" + ] + }, + "UpdateAccountTax": { + "methods": [ + "update_account_tax" + ] + } + } + } + } + }, + "AccountsService": { + "clients": { + "grpc": { + "libraryClient": "AccountsServiceClient", + "rpcs": { + "CreateAndConfigureAccount": { + "methods": [ + "create_and_configure_account" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListSubAccounts": { + "methods": [ + "list_sub_accounts" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AccountsServiceAsyncClient", + "rpcs": { + "CreateAndConfigureAccount": { + "methods": [ + "create_and_configure_account" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListSubAccounts": { + "methods": [ + "list_sub_accounts" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + } + } + }, + "rest": { + "libraryClient": "AccountsServiceClient", + "rpcs": { + "CreateAndConfigureAccount": { + "methods": [ + "create_and_configure_account" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListSubAccounts": { + "methods": [ + "list_sub_accounts" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + } + } + } + } + }, + "AutofeedSettingsService": { + "clients": { + "grpc": { + "libraryClient": "AutofeedSettingsServiceClient", + "rpcs": { + "GetAutofeedSettings": { + "methods": [ + "get_autofeed_settings" + ] + }, + "UpdateAutofeedSettings": { + "methods": [ + "update_autofeed_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutofeedSettingsServiceAsyncClient", + "rpcs": { + "GetAutofeedSettings": { + "methods": [ + "get_autofeed_settings" + ] + }, + "UpdateAutofeedSettings": { + "methods": [ + "update_autofeed_settings" + ] + } + } + }, + "rest": { + "libraryClient": "AutofeedSettingsServiceClient", + "rpcs": { + "GetAutofeedSettings": { + "methods": [ + "get_autofeed_settings" + ] + }, + "UpdateAutofeedSettings": { + "methods": [ + "update_autofeed_settings" + ] + } + } + } + } + }, + "AutomaticImprovementsService": { + "clients": { + "grpc": { + "libraryClient": "AutomaticImprovementsServiceClient", + "rpcs": { + "GetAutomaticImprovements": { + "methods": [ + "get_automatic_improvements" + ] + }, + "UpdateAutomaticImprovements": { + "methods": [ + "update_automatic_improvements" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutomaticImprovementsServiceAsyncClient", + "rpcs": { + "GetAutomaticImprovements": { + "methods": [ + "get_automatic_improvements" + ] + }, + "UpdateAutomaticImprovements": { + "methods": [ + "update_automatic_improvements" + ] + } + } + }, + "rest": { + "libraryClient": "AutomaticImprovementsServiceClient", + "rpcs": { + "GetAutomaticImprovements": { + "methods": [ + "get_automatic_improvements" + ] + }, + "UpdateAutomaticImprovements": { + "methods": [ + "update_automatic_improvements" + ] + } + } + } + } + }, + "BusinessIdentityService": { + "clients": { + "grpc": { + "libraryClient": "BusinessIdentityServiceClient", + "rpcs": { + "GetBusinessIdentity": { + "methods": [ + "get_business_identity" + ] + }, + "UpdateBusinessIdentity": { + "methods": [ + "update_business_identity" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BusinessIdentityServiceAsyncClient", + "rpcs": { + "GetBusinessIdentity": { + "methods": [ + "get_business_identity" + ] + }, + "UpdateBusinessIdentity": { + "methods": [ + "update_business_identity" + ] + } + } + }, + "rest": { + "libraryClient": "BusinessIdentityServiceClient", + "rpcs": { + "GetBusinessIdentity": { + "methods": [ + "get_business_identity" + ] + }, + "UpdateBusinessIdentity": { + "methods": [ + "update_business_identity" + ] + } + } + } + } + }, + "BusinessInfoService": { + "clients": { + "grpc": { + "libraryClient": "BusinessInfoServiceClient", + "rpcs": { + "GetBusinessInfo": { + "methods": [ + "get_business_info" + ] + }, + "UpdateBusinessInfo": { + "methods": [ + "update_business_info" + ] + } + } + }, + "grpc-async": { + "libraryClient": "BusinessInfoServiceAsyncClient", + "rpcs": { + "GetBusinessInfo": { + "methods": [ + "get_business_info" + ] + }, + "UpdateBusinessInfo": { + "methods": [ + "update_business_info" + ] + } + } + }, + "rest": { + "libraryClient": "BusinessInfoServiceClient", + "rpcs": { + "GetBusinessInfo": { + "methods": [ + "get_business_info" + ] + }, + "UpdateBusinessInfo": { + "methods": [ + "update_business_info" + ] + } + } + } + } + }, + "CheckoutSettingsService": { + "clients": { + "grpc": { + "libraryClient": "CheckoutSettingsServiceClient", + "rpcs": { + "CreateCheckoutSettings": { + "methods": [ + "create_checkout_settings" + ] + }, + "DeleteCheckoutSettings": { + "methods": [ + "delete_checkout_settings" + ] + }, + "GetCheckoutSettings": { + "methods": [ + "get_checkout_settings" + ] + }, + "UpdateCheckoutSettings": { + "methods": [ + "update_checkout_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CheckoutSettingsServiceAsyncClient", + "rpcs": { + "CreateCheckoutSettings": { + "methods": [ + "create_checkout_settings" + ] + }, + "DeleteCheckoutSettings": { + "methods": [ + "delete_checkout_settings" + ] + }, + "GetCheckoutSettings": { + "methods": [ + "get_checkout_settings" + ] + }, + "UpdateCheckoutSettings": { + "methods": [ + "update_checkout_settings" + ] + } + } + }, + "rest": { + "libraryClient": "CheckoutSettingsServiceClient", + "rpcs": { + "CreateCheckoutSettings": { + "methods": [ + "create_checkout_settings" + ] + }, + "DeleteCheckoutSettings": { + "methods": [ + "delete_checkout_settings" + ] + }, + "GetCheckoutSettings": { + "methods": [ + "get_checkout_settings" + ] + }, + "UpdateCheckoutSettings": { + "methods": [ + "update_checkout_settings" + ] + } + } + } + } + }, + "EmailPreferencesService": { + "clients": { + "grpc": { + "libraryClient": "EmailPreferencesServiceClient", + "rpcs": { + "GetEmailPreferences": { + "methods": [ + "get_email_preferences" + ] + }, + "UpdateEmailPreferences": { + "methods": [ + "update_email_preferences" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EmailPreferencesServiceAsyncClient", + "rpcs": { + "GetEmailPreferences": { + "methods": [ + "get_email_preferences" + ] + }, + "UpdateEmailPreferences": { + "methods": [ + "update_email_preferences" + ] + } + } + }, + "rest": { + "libraryClient": "EmailPreferencesServiceClient", + "rpcs": { + "GetEmailPreferences": { + "methods": [ + "get_email_preferences" + ] + }, + "UpdateEmailPreferences": { + "methods": [ + "update_email_preferences" + ] + } + } + } + } + }, + "GbpAccountsService": { + "clients": { + "grpc": { + "libraryClient": "GbpAccountsServiceClient", + "rpcs": { + "LinkGbpAccount": { + "methods": [ + "link_gbp_account" + ] + }, + "ListGbpAccounts": { + "methods": [ + "list_gbp_accounts" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GbpAccountsServiceAsyncClient", + "rpcs": { + "LinkGbpAccount": { + "methods": [ + "link_gbp_account" + ] + }, + "ListGbpAccounts": { + "methods": [ + "list_gbp_accounts" + ] + } + } + }, + "rest": { + "libraryClient": "GbpAccountsServiceClient", + "rpcs": { + "LinkGbpAccount": { + "methods": [ + "link_gbp_account" + ] + }, + "ListGbpAccounts": { + "methods": [ + "list_gbp_accounts" + ] + } + } + } + } + }, + "HomepageService": { + "clients": { + "grpc": { + "libraryClient": "HomepageServiceClient", + "rpcs": { + "ClaimHomepage": { + "methods": [ + "claim_homepage" + ] + }, + "GetHomepage": { + "methods": [ + "get_homepage" + ] + }, + "UnclaimHomepage": { + "methods": [ + "unclaim_homepage" + ] + }, + "UpdateHomepage": { + "methods": [ + "update_homepage" + ] + } + } + }, + "grpc-async": { + "libraryClient": "HomepageServiceAsyncClient", + "rpcs": { + "ClaimHomepage": { + "methods": [ + "claim_homepage" + ] + }, + "GetHomepage": { + "methods": [ + "get_homepage" + ] + }, + "UnclaimHomepage": { + "methods": [ + "unclaim_homepage" + ] + }, + "UpdateHomepage": { + "methods": [ + "update_homepage" + ] + } + } + }, + "rest": { + "libraryClient": "HomepageServiceClient", + "rpcs": { + "ClaimHomepage": { + "methods": [ + "claim_homepage" + ] + }, + "GetHomepage": { + "methods": [ + "get_homepage" + ] + }, + "UnclaimHomepage": { + "methods": [ + "unclaim_homepage" + ] + }, + "UpdateHomepage": { + "methods": [ + "update_homepage" + ] + } + } + } + } + }, + "LfpProvidersService": { + "clients": { + "grpc": { + "libraryClient": "LfpProvidersServiceClient", + "rpcs": { + "FindLfpProviders": { + "methods": [ + "find_lfp_providers" + ] + }, + "LinkLfpProvider": { + "methods": [ + "link_lfp_provider" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LfpProvidersServiceAsyncClient", + "rpcs": { + "FindLfpProviders": { + "methods": [ + "find_lfp_providers" + ] + }, + "LinkLfpProvider": { + "methods": [ + "link_lfp_provider" + ] + } + } + }, + "rest": { + "libraryClient": "LfpProvidersServiceClient", + "rpcs": { + "FindLfpProviders": { + "methods": [ + "find_lfp_providers" + ] + }, + "LinkLfpProvider": { + "methods": [ + "link_lfp_provider" + ] + } + } + } + } + }, + "OmnichannelSettingsService": { + "clients": { + "grpc": { + "libraryClient": "OmnichannelSettingsServiceClient", + "rpcs": { + "CreateOmnichannelSetting": { + "methods": [ + "create_omnichannel_setting" + ] + }, + "GetOmnichannelSetting": { + "methods": [ + "get_omnichannel_setting" + ] + }, + "ListOmnichannelSettings": { + "methods": [ + "list_omnichannel_settings" + ] + }, + "RequestInventoryVerification": { + "methods": [ + "request_inventory_verification" + ] + }, + "UpdateOmnichannelSetting": { + "methods": [ + "update_omnichannel_setting" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OmnichannelSettingsServiceAsyncClient", + "rpcs": { + "CreateOmnichannelSetting": { + "methods": [ + "create_omnichannel_setting" + ] + }, + "GetOmnichannelSetting": { + "methods": [ + "get_omnichannel_setting" + ] + }, + "ListOmnichannelSettings": { + "methods": [ + "list_omnichannel_settings" + ] + }, + "RequestInventoryVerification": { + "methods": [ + "request_inventory_verification" + ] + }, + "UpdateOmnichannelSetting": { + "methods": [ + "update_omnichannel_setting" + ] + } + } + }, + "rest": { + "libraryClient": "OmnichannelSettingsServiceClient", + "rpcs": { + "CreateOmnichannelSetting": { + "methods": [ + "create_omnichannel_setting" + ] + }, + "GetOmnichannelSetting": { + "methods": [ + "get_omnichannel_setting" + ] + }, + "ListOmnichannelSettings": { + "methods": [ + "list_omnichannel_settings" + ] + }, + "RequestInventoryVerification": { + "methods": [ + "request_inventory_verification" + ] + }, + "UpdateOmnichannelSetting": { + "methods": [ + "update_omnichannel_setting" + ] + } + } + } + } + }, + "OnlineReturnPolicyService": { + "clients": { + "grpc": { + "libraryClient": "OnlineReturnPolicyServiceClient", + "rpcs": { + "CreateOnlineReturnPolicy": { + "methods": [ + "create_online_return_policy" + ] + }, + "DeleteOnlineReturnPolicy": { + "methods": [ + "delete_online_return_policy" + ] + }, + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + }, + "UpdateOnlineReturnPolicy": { + "methods": [ + "update_online_return_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "OnlineReturnPolicyServiceAsyncClient", + "rpcs": { + "CreateOnlineReturnPolicy": { + "methods": [ + "create_online_return_policy" + ] + }, + "DeleteOnlineReturnPolicy": { + "methods": [ + "delete_online_return_policy" + ] + }, + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + }, + "UpdateOnlineReturnPolicy": { + "methods": [ + "update_online_return_policy" + ] + } + } + }, + "rest": { + "libraryClient": "OnlineReturnPolicyServiceClient", + "rpcs": { + "CreateOnlineReturnPolicy": { + "methods": [ + "create_online_return_policy" + ] + }, + "DeleteOnlineReturnPolicy": { + "methods": [ + "delete_online_return_policy" + ] + }, + "GetOnlineReturnPolicy": { + "methods": [ + "get_online_return_policy" + ] + }, + "ListOnlineReturnPolicies": { + "methods": [ + "list_online_return_policies" + ] + }, + "UpdateOnlineReturnPolicy": { + "methods": [ + "update_online_return_policy" + ] + } + } + } + } + }, + "ProgramsService": { + "clients": { + "grpc": { + "libraryClient": "ProgramsServiceClient", + "rpcs": { + "DisableProgram": { + "methods": [ + "disable_program" + ] + }, + "EnableProgram": { + "methods": [ + "enable_program" + ] + }, + "GetProgram": { + "methods": [ + "get_program" + ] + }, + "ListPrograms": { + "methods": [ + "list_programs" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProgramsServiceAsyncClient", + "rpcs": { + "DisableProgram": { + "methods": [ + "disable_program" + ] + }, + "EnableProgram": { + "methods": [ + "enable_program" + ] + }, + "GetProgram": { + "methods": [ + "get_program" + ] + }, + "ListPrograms": { + "methods": [ + "list_programs" + ] + } + } + }, + "rest": { + "libraryClient": "ProgramsServiceClient", + "rpcs": { + "DisableProgram": { + "methods": [ + "disable_program" + ] + }, + "EnableProgram": { + "methods": [ + "enable_program" + ] + }, + "GetProgram": { + "methods": [ + "get_program" + ] + }, + "ListPrograms": { + "methods": [ + "list_programs" + ] + } + } + } + } + }, + "RegionsService": { + "clients": { + "grpc": { + "libraryClient": "RegionsServiceClient", + "rpcs": { + "CreateRegion": { + "methods": [ + "create_region" + ] + }, + "DeleteRegion": { + "methods": [ + "delete_region" + ] + }, + "GetRegion": { + "methods": [ + "get_region" + ] + }, + "ListRegions": { + "methods": [ + "list_regions" + ] + }, + "UpdateRegion": { + "methods": [ + "update_region" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegionsServiceAsyncClient", + "rpcs": { + "CreateRegion": { + "methods": [ + "create_region" + ] + }, + "DeleteRegion": { + "methods": [ + "delete_region" + ] + }, + "GetRegion": { + "methods": [ + "get_region" + ] + }, + "ListRegions": { + "methods": [ + "list_regions" + ] + }, + "UpdateRegion": { + "methods": [ + "update_region" + ] + } + } + }, + "rest": { + "libraryClient": "RegionsServiceClient", + "rpcs": { + "CreateRegion": { + "methods": [ + "create_region" + ] + }, + "DeleteRegion": { + "methods": [ + "delete_region" + ] + }, + "GetRegion": { + "methods": [ + "get_region" + ] + }, + "ListRegions": { + "methods": [ + "list_regions" + ] + }, + "UpdateRegion": { + "methods": [ + "update_region" + ] + } + } + } + } + }, + "ShippingSettingsService": { + "clients": { + "grpc": { + "libraryClient": "ShippingSettingsServiceClient", + "rpcs": { + "GetShippingSettings": { + "methods": [ + "get_shipping_settings" + ] + }, + "InsertShippingSettings": { + "methods": [ + "insert_shipping_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ShippingSettingsServiceAsyncClient", + "rpcs": { + "GetShippingSettings": { + "methods": [ + "get_shipping_settings" + ] + }, + "InsertShippingSettings": { + "methods": [ + "insert_shipping_settings" + ] + } + } + }, + "rest": { + "libraryClient": "ShippingSettingsServiceClient", + "rpcs": { + "GetShippingSettings": { + "methods": [ + "get_shipping_settings" + ] + }, + "InsertShippingSettings": { + "methods": [ + "insert_shipping_settings" + ] + } + } + } + } + }, + "TermsOfServiceAgreementStateService": { + "clients": { + "grpc": { + "libraryClient": "TermsOfServiceAgreementStateServiceClient", + "rpcs": { + "GetTermsOfServiceAgreementState": { + "methods": [ + "get_terms_of_service_agreement_state" + ] + }, + "RetrieveForApplicationTermsOfServiceAgreementState": { + "methods": [ + "retrieve_for_application_terms_of_service_agreement_state" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TermsOfServiceAgreementStateServiceAsyncClient", + "rpcs": { + "GetTermsOfServiceAgreementState": { + "methods": [ + "get_terms_of_service_agreement_state" + ] + }, + "RetrieveForApplicationTermsOfServiceAgreementState": { + "methods": [ + "retrieve_for_application_terms_of_service_agreement_state" + ] + } + } + }, + "rest": { + "libraryClient": "TermsOfServiceAgreementStateServiceClient", + "rpcs": { + "GetTermsOfServiceAgreementState": { + "methods": [ + "get_terms_of_service_agreement_state" + ] + }, + "RetrieveForApplicationTermsOfServiceAgreementState": { + "methods": [ + "retrieve_for_application_terms_of_service_agreement_state" + ] + } + } + } + } + }, + "TermsOfServiceService": { + "clients": { + "grpc": { + "libraryClient": "TermsOfServiceServiceClient", + "rpcs": { + "AcceptTermsOfService": { + "methods": [ + "accept_terms_of_service" + ] + }, + "GetTermsOfService": { + "methods": [ + "get_terms_of_service" + ] + }, + "RetrieveLatestTermsOfService": { + "methods": [ + "retrieve_latest_terms_of_service" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TermsOfServiceServiceAsyncClient", + "rpcs": { + "AcceptTermsOfService": { + "methods": [ + "accept_terms_of_service" + ] + }, + "GetTermsOfService": { + "methods": [ + "get_terms_of_service" + ] + }, + "RetrieveLatestTermsOfService": { + "methods": [ + "retrieve_latest_terms_of_service" + ] + } + } + }, + "rest": { + "libraryClient": "TermsOfServiceServiceClient", + "rpcs": { + "AcceptTermsOfService": { + "methods": [ + "accept_terms_of_service" + ] + }, + "GetTermsOfService": { + "methods": [ + "get_terms_of_service" + ] + }, + "RetrieveLatestTermsOfService": { + "methods": [ + "retrieve_latest_terms_of_service" + ] + } + } + } + } + }, + "UserService": { + "clients": { + "grpc": { + "libraryClient": "UserServiceClient", + "rpcs": { + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserServiceAsyncClient", + "rpcs": { + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + }, + "rest": { + "libraryClient": "UserServiceClient", + "rpcs": { + "CreateUser": { + "methods": [ + "create_user" + ] + }, + "DeleteUser": { + "methods": [ + "delete_user" + ] + }, + "GetUser": { + "methods": [ + "get_user" + ] + }, + "ListUsers": { + "methods": [ + "list_users" + ] + }, + "UpdateUser": { + "methods": [ + "update_user" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed new file mode 100644 index 000000000000..19aa2588b0f7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/__init__.py new file mode 100644 index 000000000000..1c1c6dd19914 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_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 AccountIssueServiceClient +from .async_client import AccountIssueServiceAsyncClient + +__all__ = ( + 'AccountIssueServiceClient', + 'AccountIssueServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py new file mode 100644 index 000000000000..9863fcd0a6c7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py @@ -0,0 +1,386 @@ +# -*- 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_accounts_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_accounts_v1beta.services.account_issue_service import pagers +from google.shopping.merchant_accounts_v1beta.types import accountissue +from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport +from .client import AccountIssueServiceClient + +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 AccountIssueServiceAsyncClient: + """Service to support ``AccountIssueService`` API.""" + + _client: AccountIssueServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountIssueServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountIssueServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AccountIssueServiceClient.account_path) + parse_account_path = staticmethod(AccountIssueServiceClient.parse_account_path) + account_issue_path = staticmethod(AccountIssueServiceClient.account_issue_path) + parse_account_issue_path = staticmethod(AccountIssueServiceClient.parse_account_issue_path) + common_billing_account_path = staticmethod(AccountIssueServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountIssueServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountIssueServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountIssueServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountIssueServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountIssueServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountIssueServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountIssueServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountIssueServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountIssueServiceClient.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: + AccountIssueServiceAsyncClient: The constructed client. + """ + return AccountIssueServiceClient.from_service_account_info.__func__(AccountIssueServiceAsyncClient, 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: + AccountIssueServiceAsyncClient: The constructed client. + """ + return AccountIssueServiceClient.from_service_account_file.__func__(AccountIssueServiceAsyncClient, 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 AccountIssueServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountIssueServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountIssueServiceTransport: 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 = AccountIssueServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account issue 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,AccountIssueServiceTransport,Callable[..., AccountIssueServiceTransport]]]): + 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 AccountIssueServiceTransport 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 = AccountIssueServiceClient( + 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.accounts_v1beta.AccountIssueServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", + "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.accounts.v1beta.AccountIssueService", + "credentialsType": None, + } + ) + + async def list_account_issues(self, + request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesAsyncPager: + r"""Lists all account issues of a Merchant Center + 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_accounts_v1beta + + async def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1beta.AccountIssueServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest, dict]]): + The request object. Request message for the ``ListAccountIssues`` method. + parent (:class:`str`): + Required. The parent, which owns this collection of + issues. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesAsyncPager: + Response message for the ListAccountIssues 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, accountissue.ListAccountIssuesRequest): + request = accountissue.ListAccountIssuesRequest(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_account_issues] + + # 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.ListAccountIssuesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AccountIssueServiceAsyncClient": + 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__ = ( + "AccountIssueServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py new file mode 100644 index 000000000000..c5f0d50a63ef --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py @@ -0,0 +1,755 @@ +# -*- 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_accounts_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_accounts_v1beta.services.account_issue_service import pagers +from google.shopping.merchant_accounts_v1beta.types import accountissue +from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountIssueServiceGrpcTransport +from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport +from .transports.rest import AccountIssueServiceRestTransport + + +class AccountIssueServiceClientMeta(type): + """Metaclass for the AccountIssueService 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[AccountIssueServiceTransport]] + _transport_registry["grpc"] = AccountIssueServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountIssueServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountIssueServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountIssueServiceTransport]: + """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 AccountIssueServiceClient(metaclass=AccountIssueServiceClientMeta): + """Service to support ``AccountIssueService`` API.""" + + @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: + AccountIssueServiceClient: 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: + AccountIssueServiceClient: 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) -> AccountIssueServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountIssueServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_issue_path(account: str,issue: str,) -> str: + """Returns a fully-qualified account_issue string.""" + return "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) + + @staticmethod + def parse_account_issue_path(path: str) -> Dict[str,str]: + """Parses a account_issue path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/issues/(?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 = AccountIssueServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountIssueServiceClient._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 = AccountIssueServiceClient._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, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account issue 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,AccountIssueServiceTransport,Callable[..., AccountIssueServiceTransport]]]): + 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 AccountIssueServiceTransport 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 = AccountIssueServiceClient._read_environment_variables() + self._client_cert_source = AccountIssueServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountIssueServiceClient._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, AccountIssueServiceTransport) + if transport_provided: + # transport is a AccountIssueServiceTransport 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(AccountIssueServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountIssueServiceClient._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[AccountIssueServiceTransport], Callable[..., AccountIssueServiceTransport]] = ( + AccountIssueServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountIssueServiceTransport], 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.accounts_v1beta.AccountIssueServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", + "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.accounts.v1beta.AccountIssueService", + "credentialsType": None, + } + ) + + def list_account_issues(self, + request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesPager: + r"""Lists all account issues of a Merchant Center + 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_accounts_v1beta + + def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1beta.AccountIssueServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest, dict]): + The request object. Request message for the ``ListAccountIssues`` method. + parent (str): + Required. The parent, which owns this collection of + issues. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesPager: + Response message for the ListAccountIssues 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, accountissue.ListAccountIssuesRequest): + request = accountissue.ListAccountIssuesRequest(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_account_issues] + + # 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.ListAccountIssuesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AccountIssueServiceClient": + 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__ = ( + "AccountIssueServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py new file mode 100644 index 000000000000..25d6740a69a2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_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_accounts_v1beta.types import accountissue + + +class ListAccountIssuesPager: + """A pager for iterating through ``list_account_issues`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_issues`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountIssues`` requests and continue to iterate + through the ``account_issues`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` + 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[..., accountissue.ListAccountIssuesResponse], + request: accountissue.ListAccountIssuesRequest, + response: accountissue.ListAccountIssuesResponse, + *, + 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_accounts_v1beta.types.ListAccountIssuesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse): + 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 = accountissue.ListAccountIssuesRequest(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[accountissue.ListAccountIssuesResponse]: + 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[accountissue.AccountIssue]: + for page in self.pages: + yield from page.account_issues + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountIssuesAsyncPager: + """A pager for iterating through ``list_account_issues`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_issues`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountIssues`` requests and continue to iterate + through the ``account_issues`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` + 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[accountissue.ListAccountIssuesResponse]], + request: accountissue.ListAccountIssuesRequest, + response: accountissue.ListAccountIssuesResponse, + *, + 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_accounts_v1beta.types.ListAccountIssuesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse): + 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 = accountissue.ListAccountIssuesRequest(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[accountissue.ListAccountIssuesResponse]: + 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[accountissue.AccountIssue]: + async def async_generator(): + async for page in self.pages: + for response in page.account_issues: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst new file mode 100644 index 000000000000..c03ba991127e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountIssueServiceTransport` is the ABC for all transports. +- public child `AccountIssueServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountIssueServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountIssueServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountIssueServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/__init__.py new file mode 100644 index 000000000000..7a24cf1c8dd1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_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 AccountIssueServiceTransport +from .grpc import AccountIssueServiceGrpcTransport +from .grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport +from .rest import AccountIssueServiceRestTransport +from .rest import AccountIssueServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountIssueServiceTransport]] +_transport_registry['grpc'] = AccountIssueServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountIssueServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountIssueServiceRestTransport + +__all__ = ( + 'AccountIssueServiceTransport', + 'AccountIssueServiceGrpcTransport', + 'AccountIssueServiceGrpcAsyncIOTransport', + 'AccountIssueServiceRestTransport', + 'AccountIssueServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py new file mode 100644 index 000000000000..8f5c255142fb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py @@ -0,0 +1,159 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import accountissue + +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 AccountIssueServiceTransport(abc.ABC): + """Abstract transport class for AccountIssueService.""" + + 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_account_issues: gapic_v1.method.wrap_method( + self.list_account_issues, + 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_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + Union[ + accountissue.ListAccountIssuesResponse, + Awaitable[accountissue.ListAccountIssuesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountIssueServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py new file mode 100644 index 000000000000..99311a702952 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py @@ -0,0 +1,347 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import accountissue +from .base import AccountIssueServiceTransport, 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.accounts.v1beta.AccountIssueService", + "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.accounts.v1beta.AccountIssueService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountIssueServiceGrpcTransport(AccountIssueServiceTransport): + """gRPC backend transport for AccountIssueService. + + Service to support ``AccountIssueService`` API. + + 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_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + accountissue.ListAccountIssuesResponse]: + r"""Return a callable for the list account issues method over gRPC. + + Lists all account issues of a Merchant Center + account. + + Returns: + Callable[[~.ListAccountIssuesRequest], + ~.ListAccountIssuesResponse]: + 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_account_issues' not in self._stubs: + self._stubs['list_account_issues'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountIssueService/ListAccountIssues', + request_serializer=accountissue.ListAccountIssuesRequest.serialize, + response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, + ) + return self._stubs['list_account_issues'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountIssueServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..04f578690beb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py @@ -0,0 +1,368 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import accountissue +from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountIssueServiceGrpcTransport + +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.accounts.v1beta.AccountIssueService", + "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.accounts.v1beta.AccountIssueService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountIssueServiceGrpcAsyncIOTransport(AccountIssueServiceTransport): + """gRPC AsyncIO backend transport for AccountIssueService. + + Service to support ``AccountIssueService`` API. + + 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_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + Awaitable[accountissue.ListAccountIssuesResponse]]: + r"""Return a callable for the list account issues method over gRPC. + + Lists all account issues of a Merchant Center + account. + + Returns: + Callable[[~.ListAccountIssuesRequest], + Awaitable[~.ListAccountIssuesResponse]]: + 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_account_issues' not in self._stubs: + self._stubs['list_account_issues'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountIssueService/ListAccountIssues', + request_serializer=accountissue.ListAccountIssuesRequest.serialize, + response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, + ) + return self._stubs['list_account_issues'] + + 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_account_issues: self._wrap_method( + self.list_account_issues, + 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__ = ( + 'AccountIssueServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py new file mode 100644 index 000000000000..1c0497024937 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py @@ -0,0 +1,351 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import accountissue + + +from .rest_base import _BaseAccountIssueServiceRestTransport +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 AccountIssueServiceRestInterceptor: + """Interceptor for AccountIssueService. + + 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 AccountIssueServiceRestTransport. + + .. code-block:: python + class MyCustomAccountIssueServiceInterceptor(AccountIssueServiceRestInterceptor): + def pre_list_account_issues(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_issues(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AccountIssueServiceRestTransport(interceptor=MyCustomAccountIssueServiceInterceptor()) + client = AccountIssueServiceClient(transport=transport) + + + """ + def pre_list_account_issues(self, request: accountissue.ListAccountIssuesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_account_issues + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountIssueService server. + """ + return request, metadata + + def post_list_account_issues(self, response: accountissue.ListAccountIssuesResponse) -> accountissue.ListAccountIssuesResponse: + """Post-rpc interceptor for list_account_issues + + DEPRECATED. Please use the `post_list_account_issues_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountIssueService server but before + it is returned to user code. This `post_list_account_issues` interceptor runs + before the `post_list_account_issues_with_metadata` interceptor. + """ + return response + + def post_list_account_issues_with_metadata(self, response: accountissue.ListAccountIssuesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_account_issues + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountIssueService server but before it is returned to user code. + + We recommend only using this `post_list_account_issues_with_metadata` + interceptor in new development instead of the `post_list_account_issues` interceptor. + When both interceptors are used, this `post_list_account_issues_with_metadata` interceptor runs after the + `post_list_account_issues` interceptor. The (possibly modified) response returned by + `post_list_account_issues` will be passed to + `post_list_account_issues_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AccountIssueServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountIssueServiceRestInterceptor + + +class AccountIssueServiceRestTransport(_BaseAccountIssueServiceRestTransport): + """REST backend synchronous transport for AccountIssueService. + + Service to support ``AccountIssueService`` API. + + 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[AccountIssueServiceRestInterceptor] = 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 AccountIssueServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListAccountIssues(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues, AccountIssueServiceRestStub): + def __hash__(self): + return hash("AccountIssueServiceRestTransport.ListAccountIssues") + + @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: accountissue.ListAccountIssuesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accountissue.ListAccountIssuesResponse: + r"""Call the list account issues method over HTTP. + + Args: + request (~.accountissue.ListAccountIssuesRequest): + The request object. Request message for the ``ListAccountIssues`` 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: + ~.accountissue.ListAccountIssuesResponse: + Response message for the ``ListAccountIssues`` method. + """ + + http_options = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_http_options() + + request, metadata = self._interceptor.pre_list_account_issues(request, metadata) + transcoded_request = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountIssueServiceClient.ListAccountIssues", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", + "rpcName": "ListAccountIssues", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountIssueServiceRestTransport._ListAccountIssues._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 = accountissue.ListAccountIssuesResponse() + pb_resp = accountissue.ListAccountIssuesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_account_issues(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_account_issues_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accountissue.ListAccountIssuesResponse.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.accounts_v1beta.AccountIssueServiceClient.list_account_issues", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", + "rpcName": "ListAccountIssues", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def list_account_issues(self) -> Callable[ + [accountissue.ListAccountIssuesRequest], + accountissue.ListAccountIssuesResponse]: + # 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._ListAccountIssues(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountIssueServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py new file mode 100644 index 000000000000..495938966b5a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py @@ -0,0 +1,128 @@ +# -*- 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 AccountIssueServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import accountissue + + +class _BaseAccountIssueServiceRestTransport(AccountIssueServiceTransport): + """Base REST backend transport for AccountIssueService. + + 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 _BaseListAccountIssues: + 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': '/accounts/v1beta/{parent=accounts/*}/issues', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accountissue.ListAccountIssuesRequest.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(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountIssueServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/__init__.py new file mode 100644 index 000000000000..440c9e63750e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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 AccountTaxServiceClient +from .async_client import AccountTaxServiceAsyncClient + +__all__ = ( + 'AccountTaxServiceClient', + 'AccountTaxServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py new file mode 100644 index 000000000000..c339300cded2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py @@ -0,0 +1,623 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.account_tax_service import pagers +from google.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax +from google.shopping.merchant_accounts_v1beta.types import tax_rule +from .transports.base import AccountTaxServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport +from .client import AccountTaxServiceClient + +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 AccountTaxServiceAsyncClient: + """Manages account level tax setting data. + + This API defines the following resource model: + + - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] + """ + + _client: AccountTaxServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountTaxServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountTaxServiceClient._DEFAULT_UNIVERSE + + account_tax_path = staticmethod(AccountTaxServiceClient.account_tax_path) + parse_account_tax_path = staticmethod(AccountTaxServiceClient.parse_account_tax_path) + common_billing_account_path = staticmethod(AccountTaxServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountTaxServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountTaxServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountTaxServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountTaxServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountTaxServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountTaxServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountTaxServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountTaxServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountTaxServiceClient.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: + AccountTaxServiceAsyncClient: The constructed client. + """ + return AccountTaxServiceClient.from_service_account_info.__func__(AccountTaxServiceAsyncClient, 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: + AccountTaxServiceAsyncClient: The constructed client. + """ + return AccountTaxServiceClient.from_service_account_file.__func__(AccountTaxServiceAsyncClient, 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 AccountTaxServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountTaxServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountTaxServiceTransport: 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 = AccountTaxServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountTaxServiceTransport, Callable[..., AccountTaxServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account tax 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,AccountTaxServiceTransport,Callable[..., AccountTaxServiceTransport]]]): + 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 AccountTaxServiceTransport 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 = AccountTaxServiceClient( + 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.accounts_v1beta.AccountTaxServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "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.accounts.v1beta.AccountTaxService", + "credentialsType": None, + } + ) + + async def get_account_tax(self, + request: Optional[Union[account_tax.GetAccountTaxRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> account_tax.AccountTax: + r"""Returns the tax rules that match the conditions of + GetAccountTaxRequest + + .. 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_accounts_v1beta + + async def sample_get_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountTaxRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account_tax(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest, dict]]): + The request object. Request to get tax settings + name (:class:`str`): + Required. The name from which tax + settings will be retrieved + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.AccountTax: + The tax settings of a merchant + account. All methods require the admin + role. + + """ + # 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, account_tax.GetAccountTaxRequest): + request = account_tax.GetAccountTaxRequest(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.get_account_tax] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_account_tax(self, + request: Optional[Union[account_tax.ListAccountTaxRequest, 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.ListAccountTaxAsyncPager: + r"""Lists the tax settings of the sub-accounts only in + your Merchant Center account. + This method can only be called on a multi-client + account, otherwise it'll return an error. + + .. 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_accounts_v1beta + + async def sample_list_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountTaxRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_tax(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest, dict]]): + The request object. Request to list all sub-account tax + settings only for the requesting + merchant This method can only be called + on a multi-client account, otherwise + it'll return an error. + parent (:class:`str`): + Required. The parent, which owns this + collection of account tax. Format: + accounts/{account} + + 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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxAsyncPager: + Response to account tax list request + This method can only be called on a + multi-client account, otherwise it'll + return an error. + + 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, account_tax.ListAccountTaxRequest): + request = account_tax.ListAccountTaxRequest(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_account_tax] + + # 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.ListAccountTaxAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_account_tax(self, + request: Optional[Union[gsma_account_tax.UpdateAccountTaxRequest, dict]] = None, + *, + account_tax: Optional[gsma_account_tax.AccountTax] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_account_tax.AccountTax: + r"""Updates the tax settings of the 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_accounts_v1beta + + async def sample_update_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAccountTaxRequest( + ) + + # Make the request + response = await client.update_account_tax(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest, dict]]): + The request object. Request to update the tax settings + account_tax (:class:`google.shopping.merchant_accounts_v1beta.types.AccountTax`): + Required. The tax setting that will + be updated + + This corresponds to the ``account_tax`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AccountTax: + The tax settings of a merchant + account. All methods require the admin + role. + + """ + # 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 = [account_tax, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_account_tax.UpdateAccountTaxRequest): + request = gsma_account_tax.UpdateAccountTaxRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account_tax is not None: + request.account_tax = account_tax + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_account_tax] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account_tax.name", request.account_tax.name), + )), + ) + + # 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 __aenter__(self) -> "AccountTaxServiceAsyncClient": + 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__ = ( + "AccountTaxServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py new file mode 100644 index 000000000000..0f3cd5d31304 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py @@ -0,0 +1,981 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.account_tax_service import pagers +from google.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax +from google.shopping.merchant_accounts_v1beta.types import tax_rule +from .transports.base import AccountTaxServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountTaxServiceGrpcTransport +from .transports.grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport +from .transports.rest import AccountTaxServiceRestTransport + + +class AccountTaxServiceClientMeta(type): + """Metaclass for the AccountTaxService 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[AccountTaxServiceTransport]] + _transport_registry["grpc"] = AccountTaxServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountTaxServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountTaxServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountTaxServiceTransport]: + """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 AccountTaxServiceClient(metaclass=AccountTaxServiceClientMeta): + """Manages account level tax setting data. + + This API defines the following resource model: + + - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] + """ + + @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: + AccountTaxServiceClient: 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: + AccountTaxServiceClient: 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) -> AccountTaxServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountTaxServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_tax_path(account: str,tax: str,) -> str: + """Returns a fully-qualified account_tax string.""" + return "accounts/{account}/accounttax/{tax}".format(account=account, tax=tax, ) + + @staticmethod + def parse_account_tax_path(path: str) -> Dict[str,str]: + """Parses a account_tax path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/accounttax/(?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 = AccountTaxServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountTaxServiceClient._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 = AccountTaxServiceClient._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, AccountTaxServiceTransport, Callable[..., AccountTaxServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the account tax 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,AccountTaxServiceTransport,Callable[..., AccountTaxServiceTransport]]]): + 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 AccountTaxServiceTransport 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 = AccountTaxServiceClient._read_environment_variables() + self._client_cert_source = AccountTaxServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountTaxServiceClient._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, AccountTaxServiceTransport) + if transport_provided: + # transport is a AccountTaxServiceTransport 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(AccountTaxServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountTaxServiceClient._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[AccountTaxServiceTransport], Callable[..., AccountTaxServiceTransport]] = ( + AccountTaxServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountTaxServiceTransport], 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.accounts_v1beta.AccountTaxServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "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.accounts.v1beta.AccountTaxService", + "credentialsType": None, + } + ) + + def get_account_tax(self, + request: Optional[Union[account_tax.GetAccountTaxRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> account_tax.AccountTax: + r"""Returns the tax rules that match the conditions of + GetAccountTaxRequest + + .. 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_accounts_v1beta + + def sample_get_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountTaxRequest( + name="name_value", + ) + + # Make the request + response = client.get_account_tax(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest, dict]): + The request object. Request to get tax settings + name (str): + Required. The name from which tax + settings will be retrieved + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.AccountTax: + The tax settings of a merchant + account. All methods require the admin + role. + + """ + # 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, account_tax.GetAccountTaxRequest): + request = account_tax.GetAccountTaxRequest(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.get_account_tax] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_account_tax(self, + request: Optional[Union[account_tax.ListAccountTaxRequest, 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.ListAccountTaxPager: + r"""Lists the tax settings of the sub-accounts only in + your Merchant Center account. + This method can only be called on a multi-client + account, otherwise it'll return an error. + + .. 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_accounts_v1beta + + def sample_list_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountTaxRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_tax(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest, dict]): + The request object. Request to list all sub-account tax + settings only for the requesting + merchant This method can only be called + on a multi-client account, otherwise + it'll return an error. + parent (str): + Required. The parent, which owns this + collection of account tax. Format: + accounts/{account} + + 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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxPager: + Response to account tax list request + This method can only be called on a + multi-client account, otherwise it'll + return an error. + + 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, account_tax.ListAccountTaxRequest): + request = account_tax.ListAccountTaxRequest(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_account_tax] + + # 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.ListAccountTaxPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_account_tax(self, + request: Optional[Union[gsma_account_tax.UpdateAccountTaxRequest, dict]] = None, + *, + account_tax: Optional[gsma_account_tax.AccountTax] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_account_tax.AccountTax: + r"""Updates the tax settings of the 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_accounts_v1beta + + def sample_update_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAccountTaxRequest( + ) + + # Make the request + response = client.update_account_tax(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest, dict]): + The request object. Request to update the tax settings + account_tax (google.shopping.merchant_accounts_v1beta.types.AccountTax): + Required. The tax setting that will + be updated + + This corresponds to the ``account_tax`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AccountTax: + The tax settings of a merchant + account. All methods require the admin + role. + + """ + # 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 = [account_tax, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_account_tax.UpdateAccountTaxRequest): + request = gsma_account_tax.UpdateAccountTaxRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account_tax is not None: + request.account_tax = account_tax + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_account_tax] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account_tax.name", request.account_tax.name), + )), + ) + + # 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 __enter__(self) -> "AccountTaxServiceClient": + 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__ = ( + "AccountTaxServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py new file mode 100644 index 000000000000..d0e42a3afa12 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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_accounts_v1beta.types import account_tax + + +class ListAccountTaxPager: + """A pager for iterating through ``list_account_tax`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_taxes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountTax`` requests and continue to iterate + through the ``account_taxes`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` + 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[..., account_tax.ListAccountTaxResponse], + request: account_tax.ListAccountTaxRequest, + response: account_tax.ListAccountTaxResponse, + *, + 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_accounts_v1beta.types.ListAccountTaxRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse): + 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 = account_tax.ListAccountTaxRequest(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[account_tax.ListAccountTaxResponse]: + 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[account_tax.AccountTax]: + for page in self.pages: + yield from page.account_taxes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountTaxAsyncPager: + """A pager for iterating through ``list_account_tax`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_taxes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountTax`` requests and continue to iterate + through the ``account_taxes`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` + 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[account_tax.ListAccountTaxResponse]], + request: account_tax.ListAccountTaxRequest, + response: account_tax.ListAccountTaxResponse, + *, + 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_accounts_v1beta.types.ListAccountTaxRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse): + 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 = account_tax.ListAccountTaxRequest(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[account_tax.ListAccountTaxResponse]: + 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[account_tax.AccountTax]: + async def async_generator(): + async for page in self.pages: + for response in page.account_taxes: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst new file mode 100644 index 000000000000..2af3997395a2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountTaxServiceTransport` is the ABC for all transports. +- public child `AccountTaxServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountTaxServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountTaxServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountTaxServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/__init__.py new file mode 100644 index 000000000000..711e8a17de35 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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 AccountTaxServiceTransport +from .grpc import AccountTaxServiceGrpcTransport +from .grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport +from .rest import AccountTaxServiceRestTransport +from .rest import AccountTaxServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountTaxServiceTransport]] +_transport_registry['grpc'] = AccountTaxServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountTaxServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountTaxServiceRestTransport + +__all__ = ( + 'AccountTaxServiceTransport', + 'AccountTaxServiceGrpcTransport', + 'AccountTaxServiceGrpcAsyncIOTransport', + 'AccountTaxServiceRestTransport', + 'AccountTaxServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/base.py new file mode 100644 index 000000000000..931f0d82550c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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_accounts_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.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax + +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 AccountTaxServiceTransport(abc.ABC): + """Abstract transport class for AccountTaxService.""" + + 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.get_account_tax: gapic_v1.method.wrap_method( + self.get_account_tax, + default_timeout=None, + client_info=client_info, + ), + self.list_account_tax: gapic_v1.method.wrap_method( + self.list_account_tax, + default_timeout=None, + client_info=client_info, + ), + self.update_account_tax: gapic_v1.method.wrap_method( + self.update_account_tax, + 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 get_account_tax(self) -> Callable[ + [account_tax.GetAccountTaxRequest], + Union[ + account_tax.AccountTax, + Awaitable[account_tax.AccountTax] + ]]: + raise NotImplementedError() + + @property + def list_account_tax(self) -> Callable[ + [account_tax.ListAccountTaxRequest], + Union[ + account_tax.ListAccountTaxResponse, + Awaitable[account_tax.ListAccountTaxResponse] + ]]: + raise NotImplementedError() + + @property + def update_account_tax(self) -> Callable[ + [gsma_account_tax.UpdateAccountTaxRequest], + Union[ + gsma_account_tax.AccountTax, + Awaitable[gsma_account_tax.AccountTax] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountTaxServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py new file mode 100644 index 000000000000..376fe4e410da --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py @@ -0,0 +1,407 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax +from .base import AccountTaxServiceTransport, 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.accounts.v1beta.AccountTaxService", + "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.accounts.v1beta.AccountTaxService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountTaxServiceGrpcTransport(AccountTaxServiceTransport): + """gRPC backend transport for AccountTaxService. + + Manages account level tax setting data. + + This API defines the following resource model: + + - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] + + 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 get_account_tax(self) -> Callable[ + [account_tax.GetAccountTaxRequest], + account_tax.AccountTax]: + r"""Return a callable for the get account tax method over gRPC. + + Returns the tax rules that match the conditions of + GetAccountTaxRequest + + Returns: + Callable[[~.GetAccountTaxRequest], + ~.AccountTax]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account_tax' not in self._stubs: + self._stubs['get_account_tax'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountTaxService/GetAccountTax', + request_serializer=account_tax.GetAccountTaxRequest.serialize, + response_deserializer=account_tax.AccountTax.deserialize, + ) + return self._stubs['get_account_tax'] + + @property + def list_account_tax(self) -> Callable[ + [account_tax.ListAccountTaxRequest], + account_tax.ListAccountTaxResponse]: + r"""Return a callable for the list account tax method over gRPC. + + Lists the tax settings of the sub-accounts only in + your Merchant Center account. + This method can only be called on a multi-client + account, otherwise it'll return an error. + + Returns: + Callable[[~.ListAccountTaxRequest], + ~.ListAccountTaxResponse]: + 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_account_tax' not in self._stubs: + self._stubs['list_account_tax'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountTaxService/ListAccountTax', + request_serializer=account_tax.ListAccountTaxRequest.serialize, + response_deserializer=account_tax.ListAccountTaxResponse.deserialize, + ) + return self._stubs['list_account_tax'] + + @property + def update_account_tax(self) -> Callable[ + [gsma_account_tax.UpdateAccountTaxRequest], + gsma_account_tax.AccountTax]: + r"""Return a callable for the update account tax method over gRPC. + + Updates the tax settings of the account. + + Returns: + Callable[[~.UpdateAccountTaxRequest], + ~.AccountTax]: + 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 'update_account_tax' not in self._stubs: + self._stubs['update_account_tax'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountTaxService/UpdateAccountTax', + request_serializer=gsma_account_tax.UpdateAccountTaxRequest.serialize, + response_deserializer=gsma_account_tax.AccountTax.deserialize, + ) + return self._stubs['update_account_tax'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountTaxServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c88371254b2e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py @@ -0,0 +1,438 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax +from .base import AccountTaxServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountTaxServiceGrpcTransport + +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.accounts.v1beta.AccountTaxService", + "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.accounts.v1beta.AccountTaxService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountTaxServiceGrpcAsyncIOTransport(AccountTaxServiceTransport): + """gRPC AsyncIO backend transport for AccountTaxService. + + Manages account level tax setting data. + + This API defines the following resource model: + + - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] + + 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 get_account_tax(self) -> Callable[ + [account_tax.GetAccountTaxRequest], + Awaitable[account_tax.AccountTax]]: + r"""Return a callable for the get account tax method over gRPC. + + Returns the tax rules that match the conditions of + GetAccountTaxRequest + + Returns: + Callable[[~.GetAccountTaxRequest], + Awaitable[~.AccountTax]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account_tax' not in self._stubs: + self._stubs['get_account_tax'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountTaxService/GetAccountTax', + request_serializer=account_tax.GetAccountTaxRequest.serialize, + response_deserializer=account_tax.AccountTax.deserialize, + ) + return self._stubs['get_account_tax'] + + @property + def list_account_tax(self) -> Callable[ + [account_tax.ListAccountTaxRequest], + Awaitable[account_tax.ListAccountTaxResponse]]: + r"""Return a callable for the list account tax method over gRPC. + + Lists the tax settings of the sub-accounts only in + your Merchant Center account. + This method can only be called on a multi-client + account, otherwise it'll return an error. + + Returns: + Callable[[~.ListAccountTaxRequest], + Awaitable[~.ListAccountTaxResponse]]: + 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_account_tax' not in self._stubs: + self._stubs['list_account_tax'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountTaxService/ListAccountTax', + request_serializer=account_tax.ListAccountTaxRequest.serialize, + response_deserializer=account_tax.ListAccountTaxResponse.deserialize, + ) + return self._stubs['list_account_tax'] + + @property + def update_account_tax(self) -> Callable[ + [gsma_account_tax.UpdateAccountTaxRequest], + Awaitable[gsma_account_tax.AccountTax]]: + r"""Return a callable for the update account tax method over gRPC. + + Updates the tax settings of the account. + + Returns: + Callable[[~.UpdateAccountTaxRequest], + Awaitable[~.AccountTax]]: + 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 'update_account_tax' not in self._stubs: + self._stubs['update_account_tax'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountTaxService/UpdateAccountTax', + request_serializer=gsma_account_tax.UpdateAccountTaxRequest.serialize, + response_deserializer=gsma_account_tax.AccountTax.deserialize, + ) + return self._stubs['update_account_tax'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account_tax: self._wrap_method( + self.get_account_tax, + default_timeout=None, + client_info=client_info, + ), + self.list_account_tax: self._wrap_method( + self.list_account_tax, + default_timeout=None, + client_info=client_info, + ), + self.update_account_tax: self._wrap_method( + self.update_account_tax, + 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__ = ( + 'AccountTaxServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py new file mode 100644 index 000000000000..509d7cfbd17c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py @@ -0,0 +1,715 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax + + +from .rest_base import _BaseAccountTaxServiceRestTransport +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 AccountTaxServiceRestInterceptor: + """Interceptor for AccountTaxService. + + 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 AccountTaxServiceRestTransport. + + .. code-block:: python + class MyCustomAccountTaxServiceInterceptor(AccountTaxServiceRestInterceptor): + def pre_get_account_tax(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account_tax(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_account_tax(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_tax(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_account_tax(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_account_tax(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AccountTaxServiceRestTransport(interceptor=MyCustomAccountTaxServiceInterceptor()) + client = AccountTaxServiceClient(transport=transport) + + + """ + def pre_get_account_tax(self, request: account_tax.GetAccountTaxRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.GetAccountTaxRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_account_tax + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountTaxService server. + """ + return request, metadata + + def post_get_account_tax(self, response: account_tax.AccountTax) -> account_tax.AccountTax: + """Post-rpc interceptor for get_account_tax + + DEPRECATED. Please use the `post_get_account_tax_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountTaxService server but before + it is returned to user code. This `post_get_account_tax` interceptor runs + before the `post_get_account_tax_with_metadata` interceptor. + """ + return response + + def post_get_account_tax_with_metadata(self, response: account_tax.AccountTax, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.AccountTax, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_account_tax + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountTaxService server but before it is returned to user code. + + We recommend only using this `post_get_account_tax_with_metadata` + interceptor in new development instead of the `post_get_account_tax` interceptor. + When both interceptors are used, this `post_get_account_tax_with_metadata` interceptor runs after the + `post_get_account_tax` interceptor. The (possibly modified) response returned by + `post_get_account_tax` will be passed to + `post_get_account_tax_with_metadata`. + """ + return response, metadata + + def pre_list_account_tax(self, request: account_tax.ListAccountTaxRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.ListAccountTaxRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_account_tax + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountTaxService server. + """ + return request, metadata + + def post_list_account_tax(self, response: account_tax.ListAccountTaxResponse) -> account_tax.ListAccountTaxResponse: + """Post-rpc interceptor for list_account_tax + + DEPRECATED. Please use the `post_list_account_tax_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountTaxService server but before + it is returned to user code. This `post_list_account_tax` interceptor runs + before the `post_list_account_tax_with_metadata` interceptor. + """ + return response + + def post_list_account_tax_with_metadata(self, response: account_tax.ListAccountTaxResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.ListAccountTaxResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_account_tax + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountTaxService server but before it is returned to user code. + + We recommend only using this `post_list_account_tax_with_metadata` + interceptor in new development instead of the `post_list_account_tax` interceptor. + When both interceptors are used, this `post_list_account_tax_with_metadata` interceptor runs after the + `post_list_account_tax` interceptor. The (possibly modified) response returned by + `post_list_account_tax` will be passed to + `post_list_account_tax_with_metadata`. + """ + return response, metadata + + def pre_update_account_tax(self, request: gsma_account_tax.UpdateAccountTaxRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_account_tax.UpdateAccountTaxRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_account_tax + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountTaxService server. + """ + return request, metadata + + def post_update_account_tax(self, response: gsma_account_tax.AccountTax) -> gsma_account_tax.AccountTax: + """Post-rpc interceptor for update_account_tax + + DEPRECATED. Please use the `post_update_account_tax_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountTaxService server but before + it is returned to user code. This `post_update_account_tax` interceptor runs + before the `post_update_account_tax_with_metadata` interceptor. + """ + return response + + def post_update_account_tax_with_metadata(self, response: gsma_account_tax.AccountTax, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_account_tax.AccountTax, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_account_tax + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountTaxService server but before it is returned to user code. + + We recommend only using this `post_update_account_tax_with_metadata` + interceptor in new development instead of the `post_update_account_tax` interceptor. + When both interceptors are used, this `post_update_account_tax_with_metadata` interceptor runs after the + `post_update_account_tax` interceptor. The (possibly modified) response returned by + `post_update_account_tax` will be passed to + `post_update_account_tax_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AccountTaxServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountTaxServiceRestInterceptor + + +class AccountTaxServiceRestTransport(_BaseAccountTaxServiceRestTransport): + """REST backend synchronous transport for AccountTaxService. + + Manages account level tax setting data. + + This API defines the following resource model: + + - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] + + 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[AccountTaxServiceRestInterceptor] = 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 AccountTaxServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAccountTax(_BaseAccountTaxServiceRestTransport._BaseGetAccountTax, AccountTaxServiceRestStub): + def __hash__(self): + return hash("AccountTaxServiceRestTransport.GetAccountTax") + + @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: account_tax.GetAccountTaxRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> account_tax.AccountTax: + r"""Call the get account tax method over HTTP. + + Args: + request (~.account_tax.GetAccountTaxRequest): + The request object. Request to get tax settings + 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: + ~.account_tax.AccountTax: + The tax settings of a merchant + account. All methods require the admin + role. + + """ + + http_options = _BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_http_options() + + request, metadata = self._interceptor.pre_get_account_tax(request, metadata) + transcoded_request = _BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountTaxServiceClient.GetAccountTax", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "rpcName": "GetAccountTax", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountTaxServiceRestTransport._GetAccountTax._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 = account_tax.AccountTax() + pb_resp = account_tax.AccountTax.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_account_tax(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_account_tax_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = account_tax.AccountTax.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.accounts_v1beta.AccountTaxServiceClient.get_account_tax", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "rpcName": "GetAccountTax", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAccountTax(_BaseAccountTaxServiceRestTransport._BaseListAccountTax, AccountTaxServiceRestStub): + def __hash__(self): + return hash("AccountTaxServiceRestTransport.ListAccountTax") + + @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: account_tax.ListAccountTaxRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> account_tax.ListAccountTaxResponse: + r"""Call the list account tax method over HTTP. + + Args: + request (~.account_tax.ListAccountTaxRequest): + The request object. Request to list all sub-account tax + settings only for the requesting + merchant This method can only be called + on a multi-client account, otherwise + it'll return an error. + 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: + ~.account_tax.ListAccountTaxResponse: + Response to account tax list request + This method can only be called on a + multi-client account, otherwise it'll + return an error. + + """ + + http_options = _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_http_options() + + request, metadata = self._interceptor.pre_list_account_tax(request, metadata) + transcoded_request = _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountTaxServiceClient.ListAccountTax", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "rpcName": "ListAccountTax", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountTaxServiceRestTransport._ListAccountTax._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 = account_tax.ListAccountTaxResponse() + pb_resp = account_tax.ListAccountTaxResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_account_tax(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_account_tax_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = account_tax.ListAccountTaxResponse.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.accounts_v1beta.AccountTaxServiceClient.list_account_tax", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "rpcName": "ListAccountTax", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAccountTax(_BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax, AccountTaxServiceRestStub): + def __hash__(self): + return hash("AccountTaxServiceRestTransport.UpdateAccountTax") + + @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: gsma_account_tax.UpdateAccountTaxRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_account_tax.AccountTax: + r"""Call the update account tax method over HTTP. + + Args: + request (~.gsma_account_tax.UpdateAccountTaxRequest): + The request object. Request to update the tax settings + 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: + ~.gsma_account_tax.AccountTax: + The tax settings of a merchant + account. All methods require the admin + role. + + """ + + http_options = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_http_options() + + request, metadata = self._interceptor.pre_update_account_tax(request, metadata) + transcoded_request = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_transcoded_request(http_options, request) + + body = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountTaxServiceClient.UpdateAccountTax", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "rpcName": "UpdateAccountTax", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountTaxServiceRestTransport._UpdateAccountTax._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 = gsma_account_tax.AccountTax() + pb_resp = gsma_account_tax.AccountTax.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_account_tax(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_account_tax_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_account_tax.AccountTax.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.accounts_v1beta.AccountTaxServiceClient.update_account_tax", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "rpcName": "UpdateAccountTax", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_account_tax(self) -> Callable[ + [account_tax.GetAccountTaxRequest], + account_tax.AccountTax]: + # 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._GetAccountTax(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_account_tax(self) -> Callable[ + [account_tax.ListAccountTaxRequest], + account_tax.ListAccountTaxResponse]: + # 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._ListAccountTax(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_account_tax(self) -> Callable[ + [gsma_account_tax.UpdateAccountTaxRequest], + gsma_account_tax.AccountTax]: + # 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._UpdateAccountTax(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountTaxServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest_base.py new file mode 100644 index 000000000000..a893ddd9af6c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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 AccountTaxServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax + + +class _BaseAccountTaxServiceRestTransport(AccountTaxServiceTransport): + """Base REST backend transport for AccountTaxService. + + 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 _BaseGetAccountTax: + 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': '/accounts/v1beta/{name=accounts/*/accounttax/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = account_tax.GetAccountTaxRequest.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(_BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAccountTax: + 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': '/accounts/v1beta/{parent=accounts/*}/accounttax', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = account_tax.ListAccountTaxRequest.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(_BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAccountTax: + 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': 'patch', + 'uri': '/accounts/v1beta/{account_tax.name=accounts/*/accounttax/*}', + 'body': 'account_tax', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_account_tax.UpdateAccountTaxRequest.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(_BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountTaxServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py new file mode 100644 index 000000000000..5115ab24752a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_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 AccountsServiceClient +from .async_client import AccountsServiceAsyncClient + +__all__ = ( + 'AccountsServiceClient', + 'AccountsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py new file mode 100644 index 000000000000..1b0e8912aa4c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py @@ -0,0 +1,894 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.accounts_service import pagers +from google.shopping.merchant_accounts_v1beta.types import accounts +from google.type import datetime_pb2 # type: ignore +from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport +from .client import AccountsServiceClient + +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 AccountsServiceAsyncClient: + """Service to support Accounts API.""" + + _client: AccountsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AccountsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AccountsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AccountsServiceClient.account_path) + parse_account_path = staticmethod(AccountsServiceClient.parse_account_path) + terms_of_service_path = staticmethod(AccountsServiceClient.terms_of_service_path) + parse_terms_of_service_path = staticmethod(AccountsServiceClient.parse_terms_of_service_path) + user_path = staticmethod(AccountsServiceClient.user_path) + parse_user_path = staticmethod(AccountsServiceClient.parse_user_path) + common_billing_account_path = staticmethod(AccountsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AccountsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AccountsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AccountsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AccountsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AccountsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AccountsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AccountsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AccountsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AccountsServiceClient.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: + AccountsServiceAsyncClient: The constructed client. + """ + return AccountsServiceClient.from_service_account_info.__func__(AccountsServiceAsyncClient, 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: + AccountsServiceAsyncClient: The constructed client. + """ + return AccountsServiceClient.from_service_account_file.__func__(AccountsServiceAsyncClient, 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 AccountsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountsServiceTransport: 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 = AccountsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the accounts 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,AccountsServiceTransport,Callable[..., AccountsServiceTransport]]]): + 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 AccountsServiceTransport 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 = AccountsServiceClient( + 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.accounts_v1beta.AccountsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "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.accounts.v1beta.AccountsService", + "credentialsType": None, + } + ) + + async def get_account(self, + request: Optional[Union[accounts.GetAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + .. 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_accounts_v1beta + + async def sample_get_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAccountRequest, dict]]): + The request object. Request message for the ``GetAccount`` method. + name (:class:`str`): + Required. The name of the account to retrieve. Format: + ``accounts/{account}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Account: + An account. + """ + # 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, accounts.GetAccountRequest): + request = accounts.GetAccountRequest(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.get_account] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_and_configure_account(self, + request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Creates a standalone Merchant Center account with + additional configuration. Adds the user that makes the + request as an admin for the new 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_accounts_v1beta + + async def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = await client.create_and_configure_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest, dict]]): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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_accounts_v1beta.types.Account: + An account. + """ + # 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, accounts.CreateAndConfigureAccountRequest): + request = accounts.CreateAndConfigureAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_and_configure_account] + + # 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_account(self, + request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, + *, + name: 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 account regardless of its type: + standalone, MCA or sub-account. Deleting an MCA leads to the + deletion of all of its sub-accounts. Executing this method + requires admin access. The deletion succeeds only if the account + does not provide services to any other account and has no + processed offers. You can use the ``force`` parameter to + override this. + + .. 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_accounts_v1beta + + async def sample_delete_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_account(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest, dict]]): + The request object. Request message for the ``DeleteAccount`` method. + name (:class:`str`): + Required. The name of the account to delete. Format: + ``accounts/{account}`` + + 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, accounts.DeleteAccountRequest): + request = accounts.DeleteAccountRequest(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_account] + + # 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 update_account(self, + request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, + *, + account: Optional[accounts.Account] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Updates an account regardless of its type: + standalone, MCA or sub-account. Executing this method + requires admin access. + + .. 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_accounts_v1beta + + async def sample_update_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = await client.update_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest, dict]]): + The request object. Request message for the ``UpdateAccount`` method. + account (:class:`google.shopping.merchant_accounts_v1beta.types.Account`): + Required. The new version of the + account. + + This corresponds to the ``account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Account: + An account. + """ + # 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 = [account, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.UpdateAccountRequest): + request = accounts.UpdateAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.name), + )), + ) + + # 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 list_accounts(self, + request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAccountsAsyncPager: + r"""Lists accounts accessible to the calling user and + matching the constraints of the request such as page + size or filters. This is not just listing the + sub-accounts of an MCA, but all accounts the calling + user has access to including other MCAs, linked + accounts, standalone accounts and so on. If no filter is + provided, then it returns accounts the user is directly + added to. + + .. 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_accounts_v1beta + + async def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest, dict]]): + The request object. Request message for the ``ListAccounts`` 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_accounts_v1beta.services.accounts_service.pagers.ListAccountsAsyncPager: + Response message for the ListAccounts method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, accounts.ListAccountsRequest): + request = accounts.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_accounts] + + # 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.ListAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sub_accounts(self, + request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, + *, + provider: 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.ListSubAccountsAsyncPager: + r"""List all sub-accounts for a given multi client account. This is + a convenience wrapper for the more powerful ``ListAccounts`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + .. 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_accounts_v1beta + + async def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest, dict]]): + The request object. Request message for the ``ListSubAccounts`` method. + provider (:class:`str`): + Required. The parent account. Format: + ``accounts/{account}`` + + This corresponds to the ``provider`` 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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsAsyncPager: + Response message for the ListSubAccounts 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 = [provider] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.ListSubAccountsRequest): + request = accounts.ListSubAccountsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if provider is not None: + request.provider = provider + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_sub_accounts] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("provider", request.provider), + )), + ) + + # 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.ListSubAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AccountsServiceAsyncClient": + 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__ = ( + "AccountsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py new file mode 100644 index 000000000000..a2c5064fc494 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py @@ -0,0 +1,1269 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.accounts_service import pagers +from google.shopping.merchant_accounts_v1beta.types import accounts +from google.type import datetime_pb2 # type: ignore +from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AccountsServiceGrpcTransport +from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport +from .transports.rest import AccountsServiceRestTransport + + +class AccountsServiceClientMeta(type): + """Metaclass for the AccountsService 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[AccountsServiceTransport]] + _transport_registry["grpc"] = AccountsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AccountsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AccountsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AccountsServiceTransport]: + """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 AccountsServiceClient(metaclass=AccountsServiceClientMeta): + """Service to support Accounts API.""" + + @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: + AccountsServiceClient: 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: + AccountsServiceClient: 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) -> AccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AccountsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_path(version: str,) -> str: + """Returns a fully-qualified terms_of_service string.""" + return "termsOfService/{version}".format(version=version, ) + + @staticmethod + def parse_terms_of_service_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service path into its component segments.""" + m = re.match(r"^termsOfService/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(account: str,email: str,) -> str: + """Returns a fully-qualified user string.""" + return "accounts/{account}/users/{email}".format(account=account, email=email, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/users/(?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 = AccountsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AccountsServiceClient._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 = AccountsServiceClient._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, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the accounts 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,AccountsServiceTransport,Callable[..., AccountsServiceTransport]]]): + 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 AccountsServiceTransport 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 = AccountsServiceClient._read_environment_variables() + self._client_cert_source = AccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AccountsServiceClient._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, AccountsServiceTransport) + if transport_provided: + # transport is a AccountsServiceTransport 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(AccountsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AccountsServiceClient._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[AccountsServiceTransport], Callable[..., AccountsServiceTransport]] = ( + AccountsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AccountsServiceTransport], 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.accounts_v1beta.AccountsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "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.accounts.v1beta.AccountsService", + "credentialsType": None, + } + ) + + def get_account(self, + request: Optional[Union[accounts.GetAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + .. 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_accounts_v1beta + + def sample_get_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetAccountRequest, dict]): + The request object. Request message for the ``GetAccount`` method. + name (str): + Required. The name of the account to retrieve. Format: + ``accounts/{account}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Account: + An account. + """ + # 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, accounts.GetAccountRequest): + request = accounts.GetAccountRequest(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.get_account] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_and_configure_account(self, + request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Creates a standalone Merchant Center account with + additional configuration. Adds the user that makes the + request as an admin for the new 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_accounts_v1beta + + def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = client.create_and_configure_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest, dict]): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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_accounts_v1beta.types.Account: + An account. + """ + # 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, accounts.CreateAndConfigureAccountRequest): + request = accounts.CreateAndConfigureAccountRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_and_configure_account] + + # 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_account(self, + request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, + *, + name: 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 account regardless of its type: + standalone, MCA or sub-account. Deleting an MCA leads to the + deletion of all of its sub-accounts. Executing this method + requires admin access. The deletion succeeds only if the account + does not provide services to any other account and has no + processed offers. You can use the ``force`` parameter to + override this. + + .. 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_accounts_v1beta + + def sample_delete_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_account(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest, dict]): + The request object. Request message for the ``DeleteAccount`` method. + name (str): + Required. The name of the account to delete. Format: + ``accounts/{account}`` + + 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, accounts.DeleteAccountRequest): + request = accounts.DeleteAccountRequest(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_account] + + # 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 update_account(self, + request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, + *, + account: Optional[accounts.Account] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: + r"""Updates an account regardless of its type: + standalone, MCA or sub-account. Executing this method + requires admin access. + + .. 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_accounts_v1beta + + def sample_update_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = client.update_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest, dict]): + The request object. Request message for the ``UpdateAccount`` method. + account (google.shopping.merchant_accounts_v1beta.types.Account): + Required. The new version of the + account. + + This corresponds to the ``account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Account: + An account. + """ + # 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 = [account, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.UpdateAccountRequest): + request = accounts.UpdateAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.name), + )), + ) + + # 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 list_accounts(self, + request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAccountsPager: + r"""Lists accounts accessible to the calling user and + matching the constraints of the request such as page + size or filters. This is not just listing the + sub-accounts of an MCA, but all accounts the calling + user has access to including other MCAs, linked + accounts, standalone accounts and so on. If no filter is + provided, then it returns accounts the user is directly + added to. + + .. 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_accounts_v1beta + + def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest, dict]): + The request object. Request message for the ``ListAccounts`` 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_accounts_v1beta.services.accounts_service.pagers.ListAccountsPager: + Response message for the ListAccounts method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, accounts.ListAccountsRequest): + request = accounts.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_accounts] + + # 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.ListAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sub_accounts(self, + request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, + *, + provider: 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.ListSubAccountsPager: + r"""List all sub-accounts for a given multi client account. This is + a convenience wrapper for the more powerful ``ListAccounts`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + .. 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_accounts_v1beta + + def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest, dict]): + The request object. Request message for the ``ListSubAccounts`` method. + provider (str): + Required. The parent account. Format: + ``accounts/{account}`` + + This corresponds to the ``provider`` 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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsPager: + Response message for the ListSubAccounts 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 = [provider] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, accounts.ListSubAccountsRequest): + request = accounts.ListSubAccountsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if provider is not None: + request.provider = provider + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_sub_accounts] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("provider", request.provider), + )), + ) + + # 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.ListSubAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AccountsServiceClient": + 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__ = ( + "AccountsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py new file mode 100644 index 000000000000..de54451b9ec5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py @@ -0,0 +1,305 @@ +# -*- 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_accounts_v1beta.types import accounts + + +class ListAccountsPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` + 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[..., accounts.ListAccountsResponse], + request: accounts.ListAccountsRequest, + response: accounts.ListAccountsResponse, + *, + 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_accounts_v1beta.types.ListAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse): + 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 = accounts.ListAccountsRequest(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[accounts.ListAccountsResponse]: + 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[accounts.Account]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountsAsyncPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` + 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[accounts.ListAccountsResponse]], + request: accounts.ListAccountsRequest, + response: accounts.ListAccountsResponse, + *, + 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_accounts_v1beta.types.ListAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse): + 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 = accounts.ListAccountsRequest(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[accounts.ListAccountsResponse]: + 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[accounts.Account]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubAccountsPager: + """A pager for iterating through ``list_sub_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSubAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` + 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[..., accounts.ListSubAccountsResponse], + request: accounts.ListSubAccountsRequest, + response: accounts.ListSubAccountsResponse, + *, + 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_accounts_v1beta.types.ListSubAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse): + 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 = accounts.ListSubAccountsRequest(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[accounts.ListSubAccountsResponse]: + 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[accounts.Account]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubAccountsAsyncPager: + """A pager for iterating through ``list_sub_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSubAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` + 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[accounts.ListSubAccountsResponse]], + request: accounts.ListSubAccountsRequest, + response: accounts.ListSubAccountsResponse, + *, + 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_accounts_v1beta.types.ListSubAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse): + 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 = accounts.ListSubAccountsRequest(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[accounts.ListSubAccountsResponse]: + 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[accounts.Account]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst new file mode 100644 index 000000000000..feb9cc900a04 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AccountsServiceTransport` is the ABC for all transports. +- public child `AccountsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AccountsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAccountsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AccountsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py new file mode 100644 index 000000000000..36cbcd559b5e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_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 AccountsServiceTransport +from .grpc import AccountsServiceGrpcTransport +from .grpc_asyncio import AccountsServiceGrpcAsyncIOTransport +from .rest import AccountsServiceRestTransport +from .rest import AccountsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AccountsServiceTransport]] +_transport_registry['grpc'] = AccountsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AccountsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AccountsServiceRestTransport + +__all__ = ( + 'AccountsServiceTransport', + 'AccountsServiceGrpcTransport', + 'AccountsServiceGrpcAsyncIOTransport', + 'AccountsServiceRestTransport', + 'AccountsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py new file mode 100644 index 000000000000..7b7b63ee46fa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py @@ -0,0 +1,230 @@ +# -*- 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_accounts_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_accounts_v1beta.types import accounts + +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 AccountsServiceTransport(abc.ABC): + """Abstract transport class for AccountsService.""" + + 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.get_account: gapic_v1.method.wrap_method( + self.get_account, + default_timeout=None, + client_info=client_info, + ), + self.create_and_configure_account: gapic_v1.method.wrap_method( + self.create_and_configure_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_account: gapic_v1.method.wrap_method( + self.delete_account, + default_timeout=None, + client_info=client_info, + ), + self.update_account: gapic_v1.method.wrap_method( + self.update_account, + default_timeout=None, + client_info=client_info, + ), + self.list_accounts: gapic_v1.method.wrap_method( + self.list_accounts, + default_timeout=None, + client_info=client_info, + ), + self.list_sub_accounts: gapic_v1.method.wrap_method( + self.list_sub_accounts, + 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 get_account(self) -> Callable[ + [accounts.GetAccountRequest], + Union[ + accounts.Account, + Awaitable[accounts.Account] + ]]: + raise NotImplementedError() + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + Union[ + accounts.Account, + Awaitable[accounts.Account] + ]]: + raise NotImplementedError() + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + Union[ + accounts.Account, + Awaitable[accounts.Account] + ]]: + raise NotImplementedError() + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + Union[ + accounts.ListAccountsResponse, + Awaitable[accounts.ListAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + Union[ + accounts.ListSubAccountsResponse, + Awaitable[accounts.ListSubAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AccountsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py new file mode 100644 index 000000000000..de3e2f9ab401 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py @@ -0,0 +1,501 @@ +# -*- 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_accounts_v1beta.types import accounts +from .base import AccountsServiceTransport, 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.accounts.v1beta.AccountsService", + "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.accounts.v1beta.AccountsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountsServiceGrpcTransport(AccountsServiceTransport): + """gRPC backend transport for AccountsService. + + Service to support Accounts API. + + 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 get_account(self) -> Callable[ + [accounts.GetAccountRequest], + accounts.Account]: + r"""Return a callable for the get account method over gRPC. + + Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + Returns: + Callable[[~.GetAccountRequest], + ~.Account]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account' not in self._stubs: + self._stubs['get_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/GetAccount', + request_serializer=accounts.GetAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + accounts.Account]: + r"""Return a callable for the create and configure account method over gRPC. + + Creates a standalone Merchant Center account with + additional configuration. Adds the user that makes the + request as an admin for the new account. + + Returns: + Callable[[~.CreateAndConfigureAccountRequest], + ~.Account]: + 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 'create_and_configure_account' not in self._stubs: + self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/CreateAndConfigureAccount', + request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['create_and_configure_account'] + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete account method over gRPC. + + Deletes the specified account regardless of its type: + standalone, MCA or sub-account. Deleting an MCA leads to the + deletion of all of its sub-accounts. Executing this method + requires admin access. The deletion succeeds only if the account + does not provide services to any other account and has no + processed offers. You can use the ``force`` parameter to + override this. + + Returns: + Callable[[~.DeleteAccountRequest], + ~.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_account' not in self._stubs: + self._stubs['delete_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/DeleteAccount', + request_serializer=accounts.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + accounts.Account]: + r"""Return a callable for the update account method over gRPC. + + Updates an account regardless of its type: + standalone, MCA or sub-account. Executing this method + requires admin access. + + Returns: + Callable[[~.UpdateAccountRequest], + ~.Account]: + 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 'update_account' not in self._stubs: + self._stubs['update_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/UpdateAccount', + request_serializer=accounts.UpdateAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + accounts.ListAccountsResponse]: + r"""Return a callable for the list accounts method over gRPC. + + Lists accounts accessible to the calling user and + matching the constraints of the request such as page + size or filters. This is not just listing the + sub-accounts of an MCA, but all accounts the calling + user has access to including other MCAs, linked + accounts, standalone accounts and so on. If no filter is + provided, then it returns accounts the user is directly + added to. + + Returns: + Callable[[~.ListAccountsRequest], + ~.ListAccountsResponse]: + 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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/ListAccounts', + request_serializer=accounts.ListAccountsRequest.serialize, + response_deserializer=accounts.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + accounts.ListSubAccountsResponse]: + r"""Return a callable for the list sub accounts method over gRPC. + + List all sub-accounts for a given multi client account. This is + a convenience wrapper for the more powerful ``ListAccounts`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + Returns: + Callable[[~.ListSubAccountsRequest], + ~.ListSubAccountsResponse]: + 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_sub_accounts' not in self._stubs: + self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/ListSubAccounts', + request_serializer=accounts.ListSubAccountsRequest.serialize, + response_deserializer=accounts.ListSubAccountsResponse.deserialize, + ) + return self._stubs['list_sub_accounts'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AccountsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..6cf2cf6fff4d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py @@ -0,0 +1,547 @@ +# -*- 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_accounts_v1beta.types import accounts +from .base import AccountsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AccountsServiceGrpcTransport + +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.accounts.v1beta.AccountsService", + "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.accounts.v1beta.AccountsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AccountsServiceGrpcAsyncIOTransport(AccountsServiceTransport): + """gRPC AsyncIO backend transport for AccountsService. + + Service to support Accounts API. + + 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 get_account(self) -> Callable[ + [accounts.GetAccountRequest], + Awaitable[accounts.Account]]: + r"""Return a callable for the get account method over gRPC. + + Retrieves an account from your Merchant Center + account. After inserting, updating, or deleting an + account, it may take several minutes before changes take + effect. + + Returns: + Callable[[~.GetAccountRequest], + Awaitable[~.Account]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_account' not in self._stubs: + self._stubs['get_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/GetAccount', + request_serializer=accounts.GetAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + Awaitable[accounts.Account]]: + r"""Return a callable for the create and configure account method over gRPC. + + Creates a standalone Merchant Center account with + additional configuration. Adds the user that makes the + request as an admin for the new account. + + Returns: + Callable[[~.CreateAndConfigureAccountRequest], + Awaitable[~.Account]]: + 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 'create_and_configure_account' not in self._stubs: + self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/CreateAndConfigureAccount', + request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['create_and_configure_account'] + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete account method over gRPC. + + Deletes the specified account regardless of its type: + standalone, MCA or sub-account. Deleting an MCA leads to the + deletion of all of its sub-accounts. Executing this method + requires admin access. The deletion succeeds only if the account + does not provide services to any other account and has no + processed offers. You can use the ``force`` parameter to + override this. + + Returns: + Callable[[~.DeleteAccountRequest], + 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_account' not in self._stubs: + self._stubs['delete_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/DeleteAccount', + request_serializer=accounts.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + Awaitable[accounts.Account]]: + r"""Return a callable for the update account method over gRPC. + + Updates an account regardless of its type: + standalone, MCA or sub-account. Executing this method + requires admin access. + + Returns: + Callable[[~.UpdateAccountRequest], + Awaitable[~.Account]]: + 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 'update_account' not in self._stubs: + self._stubs['update_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/UpdateAccount', + request_serializer=accounts.UpdateAccountRequest.serialize, + response_deserializer=accounts.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + Awaitable[accounts.ListAccountsResponse]]: + r"""Return a callable for the list accounts method over gRPC. + + Lists accounts accessible to the calling user and + matching the constraints of the request such as page + size or filters. This is not just listing the + sub-accounts of an MCA, but all accounts the calling + user has access to including other MCAs, linked + accounts, standalone accounts and so on. If no filter is + provided, then it returns accounts the user is directly + added to. + + Returns: + Callable[[~.ListAccountsRequest], + Awaitable[~.ListAccountsResponse]]: + 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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/ListAccounts', + request_serializer=accounts.ListAccountsRequest.serialize, + response_deserializer=accounts.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + Awaitable[accounts.ListSubAccountsResponse]]: + r"""Return a callable for the list sub accounts method over gRPC. + + List all sub-accounts for a given multi client account. This is + a convenience wrapper for the more powerful ``ListAccounts`` + method. This method will produce the same results as calling + ``ListsAccounts`` with the following filter: + ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` + + Returns: + Callable[[~.ListSubAccountsRequest], + Awaitable[~.ListSubAccountsResponse]]: + 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_sub_accounts' not in self._stubs: + self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AccountsService/ListSubAccounts', + request_serializer=accounts.ListSubAccountsRequest.serialize, + response_deserializer=accounts.ListSubAccountsResponse.deserialize, + ) + return self._stubs['list_sub_accounts'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account: self._wrap_method( + self.get_account, + default_timeout=None, + client_info=client_info, + ), + self.create_and_configure_account: self._wrap_method( + self.create_and_configure_account, + default_timeout=None, + client_info=client_info, + ), + self.delete_account: self._wrap_method( + self.delete_account, + default_timeout=None, + client_info=client_info, + ), + self.update_account: self._wrap_method( + self.update_account, + default_timeout=None, + client_info=client_info, + ), + self.list_accounts: self._wrap_method( + self.list_accounts, + default_timeout=None, + client_info=client_info, + ), + self.list_sub_accounts: self._wrap_method( + self.list_sub_accounts, + 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__ = ( + 'AccountsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py new file mode 100644 index 000000000000..6f0c86176ba0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py @@ -0,0 +1,1149 @@ +# -*- 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_accounts_v1beta.types import accounts + + +from .rest_base import _BaseAccountsServiceRestTransport +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 AccountsServiceRestInterceptor: + """Interceptor for AccountsService. + + 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 AccountsServiceRestTransport. + + .. code-block:: python + class MyCustomAccountsServiceInterceptor(AccountsServiceRestInterceptor): + def pre_create_and_configure_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_and_configure_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sub_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sub_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_account(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AccountsServiceRestTransport(interceptor=MyCustomAccountsServiceInterceptor()) + client = AccountsServiceClient(transport=transport) + + + """ + def pre_create_and_configure_account(self, request: accounts.CreateAndConfigureAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_and_configure_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_create_and_configure_account(self, response: accounts.Account) -> accounts.Account: + """Post-rpc interceptor for create_and_configure_account + + DEPRECATED. Please use the `post_create_and_configure_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_create_and_configure_account` interceptor runs + before the `post_create_and_configure_account_with_metadata` interceptor. + """ + return response + + def post_create_and_configure_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_and_configure_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_create_and_configure_account_with_metadata` + interceptor in new development instead of the `post_create_and_configure_account` interceptor. + When both interceptors are used, this `post_create_and_configure_account_with_metadata` interceptor runs after the + `post_create_and_configure_account` interceptor. The (possibly modified) response returned by + `post_create_and_configure_account` will be passed to + `post_create_and_configure_account_with_metadata`. + """ + return response, metadata + + def pre_delete_account(self, request: accounts.DeleteAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def pre_get_account(self, request: accounts.GetAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_get_account(self, response: accounts.Account) -> accounts.Account: + """Post-rpc interceptor for get_account + + DEPRECATED. Please use the `post_get_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_get_account` interceptor runs + before the `post_get_account_with_metadata` interceptor. + """ + return response + + def post_get_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_get_account_with_metadata` + interceptor in new development instead of the `post_get_account` interceptor. + When both interceptors are used, this `post_get_account_with_metadata` interceptor runs after the + `post_get_account` interceptor. The (possibly modified) response returned by + `post_get_account` will be passed to + `post_get_account_with_metadata`. + """ + return response, metadata + + def pre_list_accounts(self, request: accounts.ListAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_list_accounts(self, response: accounts.ListAccountsResponse) -> accounts.ListAccountsResponse: + """Post-rpc interceptor for list_accounts + + DEPRECATED. Please use the `post_list_accounts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_list_accounts` interceptor runs + before the `post_list_accounts_with_metadata` interceptor. + """ + return response + + def post_list_accounts_with_metadata(self, response: accounts.ListAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_accounts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_list_accounts_with_metadata` + interceptor in new development instead of the `post_list_accounts` interceptor. + When both interceptors are used, this `post_list_accounts_with_metadata` interceptor runs after the + `post_list_accounts` interceptor. The (possibly modified) response returned by + `post_list_accounts` will be passed to + `post_list_accounts_with_metadata`. + """ + return response, metadata + + def pre_list_sub_accounts(self, request: accounts.ListSubAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_sub_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_list_sub_accounts(self, response: accounts.ListSubAccountsResponse) -> accounts.ListSubAccountsResponse: + """Post-rpc interceptor for list_sub_accounts + + DEPRECATED. Please use the `post_list_sub_accounts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_list_sub_accounts` interceptor runs + before the `post_list_sub_accounts_with_metadata` interceptor. + """ + return response + + def post_list_sub_accounts_with_metadata(self, response: accounts.ListSubAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_sub_accounts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_list_sub_accounts_with_metadata` + interceptor in new development instead of the `post_list_sub_accounts` interceptor. + When both interceptors are used, this `post_list_sub_accounts_with_metadata` interceptor runs after the + `post_list_sub_accounts` interceptor. The (possibly modified) response returned by + `post_list_sub_accounts` will be passed to + `post_list_sub_accounts_with_metadata`. + """ + return response, metadata + + def pre_update_account(self, request: accounts.UpdateAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AccountsService server. + """ + return request, metadata + + def post_update_account(self, response: accounts.Account) -> accounts.Account: + """Post-rpc interceptor for update_account + + DEPRECATED. Please use the `post_update_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AccountsService server but before + it is returned to user code. This `post_update_account` interceptor runs + before the `post_update_account_with_metadata` interceptor. + """ + return response + + def post_update_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AccountsService server but before it is returned to user code. + + We recommend only using this `post_update_account_with_metadata` + interceptor in new development instead of the `post_update_account` interceptor. + When both interceptors are used, this `post_update_account_with_metadata` interceptor runs after the + `post_update_account` interceptor. The (possibly modified) response returned by + `post_update_account` will be passed to + `post_update_account_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AccountsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AccountsServiceRestInterceptor + + +class AccountsServiceRestTransport(_BaseAccountsServiceRestTransport): + """REST backend synchronous transport for AccountsService. + + Service to support Accounts API. + + 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[AccountsServiceRestInterceptor] = 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 AccountsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateAndConfigureAccount(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.CreateAndConfigureAccount") + + @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: accounts.CreateAndConfigureAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.Account: + r"""Call the create and configure + account method over HTTP. + + Args: + request (~.accounts.CreateAndConfigureAccountRequest): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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: + ~.accounts.Account: + An account. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_http_options() + + request, metadata = self._interceptor.pre_create_and_configure_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_transcoded_request(http_options, request) + + body = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.CreateAndConfigureAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "CreateAndConfigureAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._CreateAndConfigureAccount._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 = accounts.Account() + pb_resp = accounts.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_and_configure_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_and_configure_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.Account.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.accounts_v1beta.AccountsServiceClient.create_and_configure_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "CreateAndConfigureAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAccount(_BaseAccountsServiceRestTransport._BaseDeleteAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.DeleteAccount") + + @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: accounts.DeleteAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete account method over HTTP. + + Args: + request (~.accounts.DeleteAccountRequest): + The request object. Request message for the ``DeleteAccount`` 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 = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_http_options() + + request, metadata = self._interceptor.pre_delete_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.DeleteAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "DeleteAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._DeleteAccount._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 _GetAccount(_BaseAccountsServiceRestTransport._BaseGetAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.GetAccount") + + @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: accounts.GetAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.Account: + r"""Call the get account method over HTTP. + + Args: + request (~.accounts.GetAccountRequest): + The request object. Request message for the ``GetAccount`` 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: + ~.accounts.Account: + An account. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseGetAccount._get_http_options() + + request, metadata = self._interceptor.pre_get_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseGetAccount._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseGetAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.GetAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "GetAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._GetAccount._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 = accounts.Account() + pb_resp = accounts.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.Account.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.accounts_v1beta.AccountsServiceClient.get_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "GetAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAccounts(_BaseAccountsServiceRestTransport._BaseListAccounts, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.ListAccounts") + + @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: accounts.ListAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.ListAccountsResponse: + r"""Call the list accounts method over HTTP. + + Args: + request (~.accounts.ListAccountsRequest): + The request object. Request message for the ``ListAccounts`` 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: + ~.accounts.ListAccountsResponse: + Response message for the ``ListAccounts`` method. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseListAccounts._get_http_options() + + request, metadata = self._interceptor.pre_list_accounts(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseListAccounts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseListAccounts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.ListAccounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "ListAccounts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._ListAccounts._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 = accounts.ListAccountsResponse() + pb_resp = accounts.ListAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_accounts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_accounts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.ListAccountsResponse.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.accounts_v1beta.AccountsServiceClient.list_accounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "ListAccounts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSubAccounts(_BaseAccountsServiceRestTransport._BaseListSubAccounts, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.ListSubAccounts") + + @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: accounts.ListSubAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.ListSubAccountsResponse: + r"""Call the list sub accounts method over HTTP. + + Args: + request (~.accounts.ListSubAccountsRequest): + The request object. Request message for the ``ListSubAccounts`` 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: + ~.accounts.ListSubAccountsResponse: + Response message for the ``ListSubAccounts`` method. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_http_options() + + request, metadata = self._interceptor.pre_list_sub_accounts(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.ListSubAccounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "ListSubAccounts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._ListSubAccounts._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 = accounts.ListSubAccountsResponse() + pb_resp = accounts.ListSubAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sub_accounts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sub_accounts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.ListSubAccountsResponse.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.accounts_v1beta.AccountsServiceClient.list_sub_accounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "ListSubAccounts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAccount(_BaseAccountsServiceRestTransport._BaseUpdateAccount, AccountsServiceRestStub): + def __hash__(self): + return hash("AccountsServiceRestTransport.UpdateAccount") + + @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: accounts.UpdateAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> accounts.Account: + r"""Call the update account method over HTTP. + + Args: + request (~.accounts.UpdateAccountRequest): + The request object. Request message for the ``UpdateAccount`` 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: + ~.accounts.Account: + An account. + """ + + http_options = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_http_options() + + request, metadata = self._interceptor.pre_update_account(request, metadata) + transcoded_request = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_transcoded_request(http_options, request) + + body = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.UpdateAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "UpdateAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AccountsServiceRestTransport._UpdateAccount._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 = accounts.Account() + pb_resp = accounts.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = accounts.Account.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.accounts_v1beta.AccountsServiceClient.update_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "rpcName": "UpdateAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_and_configure_account(self) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + accounts.Account]: + # 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._CreateAndConfigureAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_account(self) -> Callable[ + [accounts.DeleteAccountRequest], + 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._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_account(self) -> Callable[ + [accounts.GetAccountRequest], + accounts.Account]: + # 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._GetAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_accounts(self) -> Callable[ + [accounts.ListAccountsRequest], + accounts.ListAccountsResponse]: + # 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._ListAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sub_accounts(self) -> Callable[ + [accounts.ListSubAccountsRequest], + accounts.ListSubAccountsResponse]: + # 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._ListSubAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_account(self) -> Callable[ + [accounts.UpdateAccountRequest], + accounts.Account]: + # 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._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py new file mode 100644 index 000000000000..2eb9ab5be202 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py @@ -0,0 +1,326 @@ +# -*- 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 AccountsServiceTransport, 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_accounts_v1beta.types import accounts + + +class _BaseAccountsServiceRestTransport(AccountsServiceTransport): + """Base REST backend transport for AccountsService. + + 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 _BaseCreateAndConfigureAccount: + 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': '/accounts/v1beta/accounts:createAndConfigure', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.CreateAndConfigureAccountRequest.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(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAccount: + 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': '/accounts/v1beta/{name=accounts/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.DeleteAccountRequest.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(_BaseAccountsServiceRestTransport._BaseDeleteAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAccount: + 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': '/accounts/v1beta/{name=accounts/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.GetAccountRequest.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(_BaseAccountsServiceRestTransport._BaseGetAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAccounts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/accounts/v1beta/accounts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.ListAccountsRequest.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["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSubAccounts: + 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': '/accounts/v1beta/{provider=accounts/*}:listSubaccounts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.ListSubAccountsRequest.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(_BaseAccountsServiceRestTransport._BaseListSubAccounts._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAccount: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{account.name=accounts/*}', + 'body': 'account', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = accounts.UpdateAccountRequest.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(_BaseAccountsServiceRestTransport._BaseUpdateAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py new file mode 100644 index 000000000000..9d2f0554ddd6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_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 AutofeedSettingsServiceClient +from .async_client import AutofeedSettingsServiceAsyncClient + +__all__ = ( + 'AutofeedSettingsServiceClient', + 'AutofeedSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py new file mode 100644 index 000000000000..538b6cfb295e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py @@ -0,0 +1,493 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import autofeedsettings +from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport +from .client import AutofeedSettingsServiceClient + +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 AutofeedSettingsServiceAsyncClient: + """Service to support + `autofeed `__ + setting. + """ + + _client: AutofeedSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + + autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.autofeed_settings_path) + parse_autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.parse_autofeed_settings_path) + common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AutofeedSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AutofeedSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AutofeedSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AutofeedSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AutofeedSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AutofeedSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AutofeedSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AutofeedSettingsServiceClient.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: + AutofeedSettingsServiceAsyncClient: The constructed client. + """ + return AutofeedSettingsServiceClient.from_service_account_info.__func__(AutofeedSettingsServiceAsyncClient, 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: + AutofeedSettingsServiceAsyncClient: The constructed client. + """ + return AutofeedSettingsServiceClient.from_service_account_file.__func__(AutofeedSettingsServiceAsyncClient, 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 AutofeedSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AutofeedSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutofeedSettingsServiceTransport: 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 = AutofeedSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autofeed settings 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,AutofeedSettingsServiceTransport,Callable[..., AutofeedSettingsServiceTransport]]]): + 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 AutofeedSettingsServiceTransport 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 = AutofeedSettingsServiceClient( + 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.accounts_v1beta.AutofeedSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "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.accounts.v1beta.AutofeedSettingsService", + "credentialsType": None, + } + ) + + async def get_autofeed_settings(self, + request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Retrieves the autofeed settings of an 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_accounts_v1beta + + async def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest, dict]]): + The request object. Request message for the ``GetAutofeedSettings`` method. + name (:class:`str`): + Required. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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, autofeedsettings.GetAutofeedSettingsRequest): + request = autofeedsettings.GetAutofeedSettingsRequest(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.get_autofeed_settings] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_autofeed_settings(self, + request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, + *, + autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Updates the autofeed settings of an 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_accounts_v1beta + + async def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = await client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest, dict]]): + The request object. Request message for the ``UpdateAutofeedSettings`` + method. + autofeed_settings (:class:`google.shopping.merchant_accounts_v1beta.types.AutofeedSettings`): + Required. The new version of the + autofeed setting. + + This corresponds to the ``autofeed_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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 = [autofeed_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, autofeedsettings.UpdateAutofeedSettingsRequest): + request = autofeedsettings.UpdateAutofeedSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if autofeed_settings is not None: + request.autofeed_settings = autofeed_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_autofeed_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("autofeed_settings.name", request.autofeed_settings.name), + )), + ) + + # 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 __aenter__(self) -> "AutofeedSettingsServiceAsyncClient": + 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__ = ( + "AutofeedSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py new file mode 100644 index 000000000000..b2e0f8881c87 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py @@ -0,0 +1,852 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import autofeedsettings +from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AutofeedSettingsServiceGrpcTransport +from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport +from .transports.rest import AutofeedSettingsServiceRestTransport + + +class AutofeedSettingsServiceClientMeta(type): + """Metaclass for the AutofeedSettingsService 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[AutofeedSettingsServiceTransport]] + _transport_registry["grpc"] = AutofeedSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AutofeedSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AutofeedSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AutofeedSettingsServiceTransport]: + """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 AutofeedSettingsServiceClient(metaclass=AutofeedSettingsServiceClientMeta): + """Service to support + `autofeed `__ + setting. + """ + + @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: + AutofeedSettingsServiceClient: 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: + AutofeedSettingsServiceClient: 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) -> AutofeedSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutofeedSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def autofeed_settings_path(account: str,) -> str: + """Returns a fully-qualified autofeed_settings string.""" + return "accounts/{account}/autofeedSettings".format(account=account, ) + + @staticmethod + def parse_autofeed_settings_path(path: str) -> Dict[str,str]: + """Parses a autofeed_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/autofeedSettings$", 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 = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient._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, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autofeed settings 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,AutofeedSettingsServiceTransport,Callable[..., AutofeedSettingsServiceTransport]]]): + 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 AutofeedSettingsServiceTransport 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 = AutofeedSettingsServiceClient._read_environment_variables() + self._client_cert_source = AutofeedSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AutofeedSettingsServiceClient._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, AutofeedSettingsServiceTransport) + if transport_provided: + # transport is a AutofeedSettingsServiceTransport 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(AutofeedSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AutofeedSettingsServiceClient._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[AutofeedSettingsServiceTransport], Callable[..., AutofeedSettingsServiceTransport]] = ( + AutofeedSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AutofeedSettingsServiceTransport], 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.accounts_v1beta.AutofeedSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "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.accounts.v1beta.AutofeedSettingsService", + "credentialsType": None, + } + ) + + def get_autofeed_settings(self, + request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Retrieves the autofeed settings of an 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_accounts_v1beta + + def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest, dict]): + The request object. Request message for the ``GetAutofeedSettings`` method. + name (str): + Required. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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, autofeedsettings.GetAutofeedSettingsRequest): + request = autofeedsettings.GetAutofeedSettingsRequest(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.get_autofeed_settings] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_autofeed_settings(self, + request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, + *, + autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: + r"""Updates the autofeed settings of an 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_accounts_v1beta + + def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest, dict]): + The request object. Request message for the ``UpdateAutofeedSettings`` + method. + autofeed_settings (google.shopping.merchant_accounts_v1beta.types.AutofeedSettings): + Required. The new version of the + autofeed setting. + + This corresponds to the ``autofeed_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutofeedSettings: + Collection of information related to the + [autofeed](https://support.google.com/merchants/answer/7538732) + settings. + + """ + # 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 = [autofeed_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, autofeedsettings.UpdateAutofeedSettingsRequest): + request = autofeedsettings.UpdateAutofeedSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if autofeed_settings is not None: + request.autofeed_settings = autofeed_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_autofeed_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("autofeed_settings.name", request.autofeed_settings.name), + )), + ) + + # 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 __enter__(self) -> "AutofeedSettingsServiceClient": + 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__ = ( + "AutofeedSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst new file mode 100644 index 000000000000..54f64d66d215 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AutofeedSettingsServiceTransport` is the ABC for all transports. +- public child `AutofeedSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AutofeedSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAutofeedSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AutofeedSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py new file mode 100644 index 000000000000..c2ddd49ce02d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_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 AutofeedSettingsServiceTransport +from .grpc import AutofeedSettingsServiceGrpcTransport +from .grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport +from .rest import AutofeedSettingsServiceRestTransport +from .rest import AutofeedSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AutofeedSettingsServiceTransport]] +_transport_registry['grpc'] = AutofeedSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AutofeedSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AutofeedSettingsServiceRestTransport + +__all__ = ( + 'AutofeedSettingsServiceTransport', + 'AutofeedSettingsServiceGrpcTransport', + 'AutofeedSettingsServiceGrpcAsyncIOTransport', + 'AutofeedSettingsServiceRestTransport', + 'AutofeedSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py new file mode 100644 index 000000000000..746744918723 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import autofeedsettings + +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 AutofeedSettingsServiceTransport(abc.ABC): + """Abstract transport class for AutofeedSettingsService.""" + + 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.get_autofeed_settings: gapic_v1.method.wrap_method( + self.get_autofeed_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_autofeed_settings: gapic_v1.method.wrap_method( + self.update_autofeed_settings, + 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 get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + Union[ + autofeedsettings.AutofeedSettings, + Awaitable[autofeedsettings.AutofeedSettings] + ]]: + raise NotImplementedError() + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + Union[ + autofeedsettings.AutofeedSettings, + Awaitable[autofeedsettings.AutofeedSettings] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AutofeedSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py new file mode 100644 index 000000000000..85dd101af839 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import autofeedsettings +from .base import AutofeedSettingsServiceTransport, 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.accounts.v1beta.AutofeedSettingsService", + "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.accounts.v1beta.AutofeedSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutofeedSettingsServiceGrpcTransport(AutofeedSettingsServiceTransport): + """gRPC backend transport for AutofeedSettingsService. + + Service to support + `autofeed `__ + setting. + + 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 get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + r"""Return a callable for the get autofeed settings method over gRPC. + + Retrieves the autofeed settings of an account. + + Returns: + Callable[[~.GetAutofeedSettingsRequest], + ~.AutofeedSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_autofeed_settings' not in self._stubs: + self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/GetAutofeedSettings', + request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['get_autofeed_settings'] + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + r"""Return a callable for the update autofeed settings method over gRPC. + + Updates the autofeed settings of an account. + + Returns: + Callable[[~.UpdateAutofeedSettingsRequest], + ~.AutofeedSettings]: + 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 'update_autofeed_settings' not in self._stubs: + self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/UpdateAutofeedSettings', + request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['update_autofeed_settings'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AutofeedSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c02a74167f25 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,400 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import autofeedsettings +from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AutofeedSettingsServiceGrpcTransport + +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.accounts.v1beta.AutofeedSettingsService", + "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.accounts.v1beta.AutofeedSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutofeedSettingsServiceGrpcAsyncIOTransport(AutofeedSettingsServiceTransport): + """gRPC AsyncIO backend transport for AutofeedSettingsService. + + Service to support + `autofeed `__ + setting. + + 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 get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + Awaitable[autofeedsettings.AutofeedSettings]]: + r"""Return a callable for the get autofeed settings method over gRPC. + + Retrieves the autofeed settings of an account. + + Returns: + Callable[[~.GetAutofeedSettingsRequest], + Awaitable[~.AutofeedSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_autofeed_settings' not in self._stubs: + self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/GetAutofeedSettings', + request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['get_autofeed_settings'] + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + Awaitable[autofeedsettings.AutofeedSettings]]: + r"""Return a callable for the update autofeed settings method over gRPC. + + Updates the autofeed settings of an account. + + Returns: + Callable[[~.UpdateAutofeedSettingsRequest], + Awaitable[~.AutofeedSettings]]: + 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 'update_autofeed_settings' not in self._stubs: + self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/UpdateAutofeedSettings', + request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, + response_deserializer=autofeedsettings.AutofeedSettings.deserialize, + ) + return self._stubs['update_autofeed_settings'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_autofeed_settings: self._wrap_method( + self.get_autofeed_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_autofeed_settings: self._wrap_method( + self.update_autofeed_settings, + 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__ = ( + 'AutofeedSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py new file mode 100644 index 000000000000..bc908e354b7e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py @@ -0,0 +1,534 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import autofeedsettings + + +from .rest_base import _BaseAutofeedSettingsServiceRestTransport +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 AutofeedSettingsServiceRestInterceptor: + """Interceptor for AutofeedSettingsService. + + 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 AutofeedSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomAutofeedSettingsServiceInterceptor(AutofeedSettingsServiceRestInterceptor): + def pre_get_autofeed_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_autofeed_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_autofeed_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_autofeed_settings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AutofeedSettingsServiceRestTransport(interceptor=MyCustomAutofeedSettingsServiceInterceptor()) + client = AutofeedSettingsServiceClient(transport=transport) + + + """ + def pre_get_autofeed_settings(self, request: autofeedsettings.GetAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_autofeed_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutofeedSettingsService server. + """ + return request, metadata + + def post_get_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: + """Post-rpc interceptor for get_autofeed_settings + + DEPRECATED. Please use the `post_get_autofeed_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutofeedSettingsService server but before + it is returned to user code. This `post_get_autofeed_settings` interceptor runs + before the `post_get_autofeed_settings_with_metadata` interceptor. + """ + return response + + def post_get_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_autofeed_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutofeedSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_autofeed_settings_with_metadata` + interceptor in new development instead of the `post_get_autofeed_settings` interceptor. + When both interceptors are used, this `post_get_autofeed_settings_with_metadata` interceptor runs after the + `post_get_autofeed_settings` interceptor. The (possibly modified) response returned by + `post_get_autofeed_settings` will be passed to + `post_get_autofeed_settings_with_metadata`. + """ + return response, metadata + + def pre_update_autofeed_settings(self, request: autofeedsettings.UpdateAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_autofeed_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutofeedSettingsService server. + """ + return request, metadata + + def post_update_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: + """Post-rpc interceptor for update_autofeed_settings + + DEPRECATED. Please use the `post_update_autofeed_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutofeedSettingsService server but before + it is returned to user code. This `post_update_autofeed_settings` interceptor runs + before the `post_update_autofeed_settings_with_metadata` interceptor. + """ + return response + + def post_update_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_autofeed_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutofeedSettingsService server but before it is returned to user code. + + We recommend only using this `post_update_autofeed_settings_with_metadata` + interceptor in new development instead of the `post_update_autofeed_settings` interceptor. + When both interceptors are used, this `post_update_autofeed_settings_with_metadata` interceptor runs after the + `post_update_autofeed_settings` interceptor. The (possibly modified) response returned by + `post_update_autofeed_settings` will be passed to + `post_update_autofeed_settings_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AutofeedSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutofeedSettingsServiceRestInterceptor + + +class AutofeedSettingsServiceRestTransport(_BaseAutofeedSettingsServiceRestTransport): + """REST backend synchronous transport for AutofeedSettingsService. + + Service to support + `autofeed `__ + setting. + + 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[AutofeedSettingsServiceRestInterceptor] = 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 AutofeedSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings, AutofeedSettingsServiceRestStub): + def __hash__(self): + return hash("AutofeedSettingsServiceRestTransport.GetAutofeedSettings") + + @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: autofeedsettings.GetAutofeedSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> autofeedsettings.AutofeedSettings: + r"""Call the get autofeed settings method over HTTP. + + Args: + request (~.autofeedsettings.GetAutofeedSettingsRequest): + The request object. Request message for the ``GetAutofeedSettings`` 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: + ~.autofeedsettings.AutofeedSettings: + Collection of information related to the + `autofeed `__ + settings. + + """ + + http_options = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_http_options() + + request, metadata = self._interceptor.pre_get_autofeed_settings(request, metadata) + transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutofeedSettingsServiceClient.GetAutofeedSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "rpcName": "GetAutofeedSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutofeedSettingsServiceRestTransport._GetAutofeedSettings._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 = autofeedsettings.AutofeedSettings() + pb_resp = autofeedsettings.AutofeedSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_autofeed_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_autofeed_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1beta.AutofeedSettingsServiceClient.get_autofeed_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "rpcName": "GetAutofeedSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings, AutofeedSettingsServiceRestStub): + def __hash__(self): + return hash("AutofeedSettingsServiceRestTransport.UpdateAutofeedSettings") + + @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: autofeedsettings.UpdateAutofeedSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> autofeedsettings.AutofeedSettings: + r"""Call the update autofeed settings method over HTTP. + + Args: + request (~.autofeedsettings.UpdateAutofeedSettingsRequest): + The request object. Request message for the ``UpdateAutofeedSettings`` + 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: + ~.autofeedsettings.AutofeedSettings: + Collection of information related to the + `autofeed `__ + settings. + + """ + + http_options = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_http_options() + + request, metadata = self._interceptor.pre_update_autofeed_settings(request, metadata) + transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_transcoded_request(http_options, request) + + body = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutofeedSettingsServiceClient.UpdateAutofeedSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "rpcName": "UpdateAutofeedSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutofeedSettingsServiceRestTransport._UpdateAutofeedSettings._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 = autofeedsettings.AutofeedSettings() + pb_resp = autofeedsettings.AutofeedSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_autofeed_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_autofeed_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1beta.AutofeedSettingsServiceClient.update_autofeed_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "rpcName": "UpdateAutofeedSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_autofeed_settings(self) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + # 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._GetAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_autofeed_settings(self) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings]: + # 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._UpdateAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AutofeedSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..c5c58aca9244 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import autofeedsettings + + +class _BaseAutofeedSettingsServiceRestTransport(AutofeedSettingsServiceTransport): + """Base REST backend transport for AutofeedSettingsService. + + 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 _BaseGetAutofeedSettings: + 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': '/accounts/v1beta/{name=accounts/*/autofeedSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autofeedsettings.GetAutofeedSettingsRequest.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(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAutofeedSettings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{autofeed_settings.name=accounts/*/autofeedSettings}', + 'body': 'autofeed_settings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autofeedsettings.UpdateAutofeedSettingsRequest.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(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAutofeedSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/__init__.py new file mode 100644 index 000000000000..7df59eeedb79 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_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 AutomaticImprovementsServiceClient +from .async_client import AutomaticImprovementsServiceAsyncClient + +__all__ = ( + 'AutomaticImprovementsServiceClient', + 'AutomaticImprovementsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py new file mode 100644 index 000000000000..60e41a5290e6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py @@ -0,0 +1,499 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import automaticimprovements +from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport +from .client import AutomaticImprovementsServiceClient + +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 AutomaticImprovementsServiceAsyncClient: + """Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + """ + + _client: AutomaticImprovementsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + + automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.automatic_improvements_path) + parse_automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.parse_automatic_improvements_path) + common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AutomaticImprovementsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AutomaticImprovementsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AutomaticImprovementsServiceClient.common_project_path) + parse_common_project_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_project_path) + common_location_path = staticmethod(AutomaticImprovementsServiceClient.common_location_path) + parse_common_location_path = staticmethod(AutomaticImprovementsServiceClient.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: + AutomaticImprovementsServiceAsyncClient: The constructed client. + """ + return AutomaticImprovementsServiceClient.from_service_account_info.__func__(AutomaticImprovementsServiceAsyncClient, 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: + AutomaticImprovementsServiceAsyncClient: The constructed client. + """ + return AutomaticImprovementsServiceClient.from_service_account_file.__func__(AutomaticImprovementsServiceAsyncClient, 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 AutomaticImprovementsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AutomaticImprovementsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutomaticImprovementsServiceTransport: 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 = AutomaticImprovementsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the automatic improvements 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,AutomaticImprovementsServiceTransport,Callable[..., AutomaticImprovementsServiceTransport]]]): + 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 AutomaticImprovementsServiceTransport 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 = AutomaticImprovementsServiceClient( + 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.accounts_v1beta.AutomaticImprovementsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "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.accounts.v1beta.AutomaticImprovementsService", + "credentialsType": None, + } + ) + + async def get_automatic_improvements(self, + request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Retrieves the automatic improvements of an 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_accounts_v1beta + + async def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest, dict]]): + The request object. Request message for the ``GetAutomaticImprovements`` + method. + name (:class:`str`): + Required. The resource name of the automatic + improvements. Format: + ``accounts/{account}/automaticImprovements`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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, automaticimprovements.GetAutomaticImprovementsRequest): + request = automaticimprovements.GetAutomaticImprovementsRequest(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.get_automatic_improvements] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_automatic_improvements(self, + request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, + *, + automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Updates the automatic improvements of an 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_accounts_v1beta + + async def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = await client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest, dict]]): + The request object. Request message for the ``UpdateAutomaticImprovements`` + method. + automatic_improvements (:class:`google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements`): + Required. The new version of the + automatic imrovements. + + This corresponds to the ``automatic_improvements`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``item_updates`` + - ``item_updates.account_level_settings`` + - ``image_improvements`` + - ``image_improvements.account_level_settings`` + - ``shipping_improvements`` + - ``shipping_improvements.allow_shipping_improvements`` + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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 = [automatic_improvements, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, automaticimprovements.UpdateAutomaticImprovementsRequest): + request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if automatic_improvements is not None: + request.automatic_improvements = automatic_improvements + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_automatic_improvements] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("automatic_improvements.name", request.automatic_improvements.name), + )), + ) + + # 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 __aenter__(self) -> "AutomaticImprovementsServiceAsyncClient": + 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__ = ( + "AutomaticImprovementsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py new file mode 100644 index 000000000000..ceb3df3a74cc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py @@ -0,0 +1,858 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import automaticimprovements +from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AutomaticImprovementsServiceGrpcTransport +from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport +from .transports.rest import AutomaticImprovementsServiceRestTransport + + +class AutomaticImprovementsServiceClientMeta(type): + """Metaclass for the AutomaticImprovementsService 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[AutomaticImprovementsServiceTransport]] + _transport_registry["grpc"] = AutomaticImprovementsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AutomaticImprovementsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AutomaticImprovementsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AutomaticImprovementsServiceTransport]: + """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 AutomaticImprovementsServiceClient(metaclass=AutomaticImprovementsServiceClientMeta): + """Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + """ + + @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: + AutomaticImprovementsServiceClient: 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: + AutomaticImprovementsServiceClient: 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) -> AutomaticImprovementsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AutomaticImprovementsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def automatic_improvements_path(account: str,) -> str: + """Returns a fully-qualified automatic_improvements string.""" + return "accounts/{account}/automaticImprovements".format(account=account, ) + + @staticmethod + def parse_automatic_improvements_path(path: str) -> Dict[str,str]: + """Parses a automatic_improvements path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/automaticImprovements$", 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 = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient._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, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the automatic improvements 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,AutomaticImprovementsServiceTransport,Callable[..., AutomaticImprovementsServiceTransport]]]): + 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 AutomaticImprovementsServiceTransport 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 = AutomaticImprovementsServiceClient._read_environment_variables() + self._client_cert_source = AutomaticImprovementsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AutomaticImprovementsServiceClient._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, AutomaticImprovementsServiceTransport) + if transport_provided: + # transport is a AutomaticImprovementsServiceTransport 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(AutomaticImprovementsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AutomaticImprovementsServiceClient._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[AutomaticImprovementsServiceTransport], Callable[..., AutomaticImprovementsServiceTransport]] = ( + AutomaticImprovementsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AutomaticImprovementsServiceTransport], 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.accounts_v1beta.AutomaticImprovementsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "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.accounts.v1beta.AutomaticImprovementsService", + "credentialsType": None, + } + ) + + def get_automatic_improvements(self, + request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Retrieves the automatic improvements of an 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_accounts_v1beta + + def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest, dict]): + The request object. Request message for the ``GetAutomaticImprovements`` + method. + name (str): + Required. The resource name of the automatic + improvements. Format: + ``accounts/{account}/automaticImprovements`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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, automaticimprovements.GetAutomaticImprovementsRequest): + request = automaticimprovements.GetAutomaticImprovementsRequest(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.get_automatic_improvements] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_automatic_improvements(self, + request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, + *, + automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: + r"""Updates the automatic improvements of an 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_accounts_v1beta + + def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest, dict]): + The request object. Request message for the ``UpdateAutomaticImprovements`` + method. + automatic_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements): + Required. The new version of the + automatic imrovements. + + This corresponds to the ``automatic_improvements`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``item_updates`` + - ``item_updates.account_level_settings`` + - ``image_improvements`` + - ``image_improvements.account_level_settings`` + - ``shipping_improvements`` + - ``shipping_improvements.allow_shipping_improvements`` + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutomaticImprovements: + Collection of information related to the [automatic + improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) + of an account. + + """ + # 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 = [automatic_improvements, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, automaticimprovements.UpdateAutomaticImprovementsRequest): + request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if automatic_improvements is not None: + request.automatic_improvements = automatic_improvements + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_automatic_improvements] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("automatic_improvements.name", request.automatic_improvements.name), + )), + ) + + # 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 __enter__(self) -> "AutomaticImprovementsServiceClient": + 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__ = ( + "AutomaticImprovementsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst new file mode 100644 index 000000000000..87e807806d8b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AutomaticImprovementsServiceTransport` is the ABC for all transports. +- public child `AutomaticImprovementsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AutomaticImprovementsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAutomaticImprovementsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AutomaticImprovementsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/__init__.py new file mode 100644 index 000000000000..815443dffafc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_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 AutomaticImprovementsServiceTransport +from .grpc import AutomaticImprovementsServiceGrpcTransport +from .grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport +from .rest import AutomaticImprovementsServiceRestTransport +from .rest import AutomaticImprovementsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] +_transport_registry['grpc'] = AutomaticImprovementsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AutomaticImprovementsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AutomaticImprovementsServiceRestTransport + +__all__ = ( + 'AutomaticImprovementsServiceTransport', + 'AutomaticImprovementsServiceGrpcTransport', + 'AutomaticImprovementsServiceGrpcAsyncIOTransport', + 'AutomaticImprovementsServiceRestTransport', + 'AutomaticImprovementsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py new file mode 100644 index 000000000000..2d15663db10e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import automaticimprovements + +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 AutomaticImprovementsServiceTransport(abc.ABC): + """Abstract transport class for AutomaticImprovementsService.""" + + 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.get_automatic_improvements: gapic_v1.method.wrap_method( + self.get_automatic_improvements, + default_timeout=None, + client_info=client_info, + ), + self.update_automatic_improvements: gapic_v1.method.wrap_method( + self.update_automatic_improvements, + 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 get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + Union[ + automaticimprovements.AutomaticImprovements, + Awaitable[automaticimprovements.AutomaticImprovements] + ]]: + raise NotImplementedError() + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + Union[ + automaticimprovements.AutomaticImprovements, + Awaitable[automaticimprovements.AutomaticImprovements] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AutomaticImprovementsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py new file mode 100644 index 000000000000..7b84dd140ddc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py @@ -0,0 +1,374 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import automaticimprovements +from .base import AutomaticImprovementsServiceTransport, 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.accounts.v1beta.AutomaticImprovementsService", + "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.accounts.v1beta.AutomaticImprovementsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutomaticImprovementsServiceGrpcTransport(AutomaticImprovementsServiceTransport): + """gRPC backend transport for AutomaticImprovementsService. + + Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + + 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 get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + r"""Return a callable for the get automatic improvements method over gRPC. + + Retrieves the automatic improvements of an account. + + Returns: + Callable[[~.GetAutomaticImprovementsRequest], + ~.AutomaticImprovements]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_automatic_improvements' not in self._stubs: + self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/GetAutomaticImprovements', + request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['get_automatic_improvements'] + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + r"""Return a callable for the update automatic improvements method over gRPC. + + Updates the automatic improvements of an account. + + Returns: + Callable[[~.UpdateAutomaticImprovementsRequest], + ~.AutomaticImprovements]: + 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 'update_automatic_improvements' not in self._stubs: + self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/UpdateAutomaticImprovements', + request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['update_automatic_improvements'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AutomaticImprovementsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..73e3540640d7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py @@ -0,0 +1,400 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import automaticimprovements +from .base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AutomaticImprovementsServiceGrpcTransport + +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.accounts.v1beta.AutomaticImprovementsService", + "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.accounts.v1beta.AutomaticImprovementsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AutomaticImprovementsServiceGrpcAsyncIOTransport(AutomaticImprovementsServiceTransport): + """gRPC AsyncIO backend transport for AutomaticImprovementsService. + + Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + + 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 get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + Awaitable[automaticimprovements.AutomaticImprovements]]: + r"""Return a callable for the get automatic improvements method over gRPC. + + Retrieves the automatic improvements of an account. + + Returns: + Callable[[~.GetAutomaticImprovementsRequest], + Awaitable[~.AutomaticImprovements]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_automatic_improvements' not in self._stubs: + self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/GetAutomaticImprovements', + request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['get_automatic_improvements'] + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + Awaitable[automaticimprovements.AutomaticImprovements]]: + r"""Return a callable for the update automatic improvements method over gRPC. + + Updates the automatic improvements of an account. + + Returns: + Callable[[~.UpdateAutomaticImprovementsRequest], + Awaitable[~.AutomaticImprovements]]: + 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 'update_automatic_improvements' not in self._stubs: + self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/UpdateAutomaticImprovements', + request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, + response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, + ) + return self._stubs['update_automatic_improvements'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_automatic_improvements: self._wrap_method( + self.get_automatic_improvements, + default_timeout=None, + client_info=client_info, + ), + self.update_automatic_improvements: self._wrap_method( + self.update_automatic_improvements, + 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__ = ( + 'AutomaticImprovementsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py new file mode 100644 index 000000000000..bb8df4b21ee0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py @@ -0,0 +1,537 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import automaticimprovements + + +from .rest_base import _BaseAutomaticImprovementsServiceRestTransport +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 AutomaticImprovementsServiceRestInterceptor: + """Interceptor for AutomaticImprovementsService. + + 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 AutomaticImprovementsServiceRestTransport. + + .. code-block:: python + class MyCustomAutomaticImprovementsServiceInterceptor(AutomaticImprovementsServiceRestInterceptor): + def pre_get_automatic_improvements(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_automatic_improvements(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_automatic_improvements(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_automatic_improvements(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AutomaticImprovementsServiceRestTransport(interceptor=MyCustomAutomaticImprovementsServiceInterceptor()) + client = AutomaticImprovementsServiceClient(transport=transport) + + + """ + def pre_get_automatic_improvements(self, request: automaticimprovements.GetAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.GetAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_automatic_improvements + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutomaticImprovementsService server. + """ + return request, metadata + + def post_get_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: + """Post-rpc interceptor for get_automatic_improvements + + DEPRECATED. Please use the `post_get_automatic_improvements_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutomaticImprovementsService server but before + it is returned to user code. This `post_get_automatic_improvements` interceptor runs + before the `post_get_automatic_improvements_with_metadata` interceptor. + """ + return response + + def post_get_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_automatic_improvements + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutomaticImprovementsService server but before it is returned to user code. + + We recommend only using this `post_get_automatic_improvements_with_metadata` + interceptor in new development instead of the `post_get_automatic_improvements` interceptor. + When both interceptors are used, this `post_get_automatic_improvements_with_metadata` interceptor runs after the + `post_get_automatic_improvements` interceptor. The (possibly modified) response returned by + `post_get_automatic_improvements` will be passed to + `post_get_automatic_improvements_with_metadata`. + """ + return response, metadata + + def pre_update_automatic_improvements(self, request: automaticimprovements.UpdateAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.UpdateAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_automatic_improvements + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutomaticImprovementsService server. + """ + return request, metadata + + def post_update_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: + """Post-rpc interceptor for update_automatic_improvements + + DEPRECATED. Please use the `post_update_automatic_improvements_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AutomaticImprovementsService server but before + it is returned to user code. This `post_update_automatic_improvements` interceptor runs + before the `post_update_automatic_improvements_with_metadata` interceptor. + """ + return response + + def post_update_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_automatic_improvements + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AutomaticImprovementsService server but before it is returned to user code. + + We recommend only using this `post_update_automatic_improvements_with_metadata` + interceptor in new development instead of the `post_update_automatic_improvements` interceptor. + When both interceptors are used, this `post_update_automatic_improvements_with_metadata` interceptor runs after the + `post_update_automatic_improvements` interceptor. The (possibly modified) response returned by + `post_update_automatic_improvements` will be passed to + `post_update_automatic_improvements_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class AutomaticImprovementsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutomaticImprovementsServiceRestInterceptor + + +class AutomaticImprovementsServiceRestTransport(_BaseAutomaticImprovementsServiceRestTransport): + """REST backend synchronous transport for AutomaticImprovementsService. + + Service to manage the automatic improvements of an account. + The automatic improvements of the account can be used to + automatically update products, improve images and shipping. + + 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[AutomaticImprovementsServiceRestInterceptor] = 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 AutomaticImprovementsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements, AutomaticImprovementsServiceRestStub): + def __hash__(self): + return hash("AutomaticImprovementsServiceRestTransport.GetAutomaticImprovements") + + @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: automaticimprovements.GetAutomaticImprovementsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> automaticimprovements.AutomaticImprovements: + r"""Call the get automatic + improvements method over HTTP. + + Args: + request (~.automaticimprovements.GetAutomaticImprovementsRequest): + The request object. Request message for the ``GetAutomaticImprovements`` + 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: + ~.automaticimprovements.AutomaticImprovements: + Collection of information related to the `automatic + improvements `__ + of an account. + + """ + + http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_http_options() + + request, metadata = self._interceptor.pre_get_automatic_improvements(request, metadata) + transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutomaticImprovementsServiceClient.GetAutomaticImprovements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "rpcName": "GetAutomaticImprovements", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutomaticImprovementsServiceRestTransport._GetAutomaticImprovements._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 = automaticimprovements.AutomaticImprovements() + pb_resp = automaticimprovements.AutomaticImprovements.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_automatic_improvements(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_automatic_improvements_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = automaticimprovements.AutomaticImprovements.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.accounts_v1beta.AutomaticImprovementsServiceClient.get_automatic_improvements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "rpcName": "GetAutomaticImprovements", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements, AutomaticImprovementsServiceRestStub): + def __hash__(self): + return hash("AutomaticImprovementsServiceRestTransport.UpdateAutomaticImprovements") + + @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: automaticimprovements.UpdateAutomaticImprovementsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> automaticimprovements.AutomaticImprovements: + r"""Call the update automatic + improvements method over HTTP. + + Args: + request (~.automaticimprovements.UpdateAutomaticImprovementsRequest): + The request object. Request message for the ``UpdateAutomaticImprovements`` + 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: + ~.automaticimprovements.AutomaticImprovements: + Collection of information related to the `automatic + improvements `__ + of an account. + + """ + + http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_http_options() + + request, metadata = self._interceptor.pre_update_automatic_improvements(request, metadata) + transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_transcoded_request(http_options, request) + + body = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutomaticImprovementsServiceClient.UpdateAutomaticImprovements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "rpcName": "UpdateAutomaticImprovements", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AutomaticImprovementsServiceRestTransport._UpdateAutomaticImprovements._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 = automaticimprovements.AutomaticImprovements() + pb_resp = automaticimprovements.AutomaticImprovements.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_automatic_improvements(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_automatic_improvements_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = automaticimprovements.AutomaticImprovements.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.accounts_v1beta.AutomaticImprovementsServiceClient.update_automatic_improvements", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "rpcName": "UpdateAutomaticImprovements", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_automatic_improvements(self) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + # 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._GetAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_automatic_improvements(self) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements]: + # 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._UpdateAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AutomaticImprovementsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py new file mode 100644 index 000000000000..f2a1be12bb5c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import automaticimprovements + + +class _BaseAutomaticImprovementsServiceRestTransport(AutomaticImprovementsServiceTransport): + """Base REST backend transport for AutomaticImprovementsService. + + 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 _BaseGetAutomaticImprovements: + 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': '/accounts/v1beta/{name=accounts/*/automaticImprovements}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = automaticimprovements.GetAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAutomaticImprovements: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{automatic_improvements.name=accounts/*/automaticImprovements}', + 'body': 'automatic_improvements', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = automaticimprovements.UpdateAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseAutomaticImprovementsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/__init__.py new file mode 100644 index 000000000000..f97b26e0a25c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_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 BusinessIdentityServiceClient +from .async_client import BusinessIdentityServiceAsyncClient + +__all__ = ( + 'BusinessIdentityServiceClient', + 'BusinessIdentityServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py new file mode 100644 index 000000000000..a46b3103fdfc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py @@ -0,0 +1,488 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import businessidentity +from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport +from .client import BusinessIdentityServiceClient + +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 BusinessIdentityServiceAsyncClient: + """Service to support `business + identity `__ + API. + """ + + _client: BusinessIdentityServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + + business_identity_path = staticmethod(BusinessIdentityServiceClient.business_identity_path) + parse_business_identity_path = staticmethod(BusinessIdentityServiceClient.parse_business_identity_path) + common_billing_account_path = staticmethod(BusinessIdentityServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(BusinessIdentityServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(BusinessIdentityServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(BusinessIdentityServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(BusinessIdentityServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(BusinessIdentityServiceClient.parse_common_organization_path) + common_project_path = staticmethod(BusinessIdentityServiceClient.common_project_path) + parse_common_project_path = staticmethod(BusinessIdentityServiceClient.parse_common_project_path) + common_location_path = staticmethod(BusinessIdentityServiceClient.common_location_path) + parse_common_location_path = staticmethod(BusinessIdentityServiceClient.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: + BusinessIdentityServiceAsyncClient: The constructed client. + """ + return BusinessIdentityServiceClient.from_service_account_info.__func__(BusinessIdentityServiceAsyncClient, 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: + BusinessIdentityServiceAsyncClient: The constructed client. + """ + return BusinessIdentityServiceClient.from_service_account_file.__func__(BusinessIdentityServiceAsyncClient, 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 BusinessIdentityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> BusinessIdentityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessIdentityServiceTransport: 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 = BusinessIdentityServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business identity 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,BusinessIdentityServiceTransport,Callable[..., BusinessIdentityServiceTransport]]]): + 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 BusinessIdentityServiceTransport 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 = BusinessIdentityServiceClient( + 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.accounts_v1beta.BusinessIdentityServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "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.accounts.v1beta.BusinessIdentityService", + "credentialsType": None, + } + ) + + async def get_business_identity(self, + request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Retrieves the business identity of an 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_accounts_v1beta + + async def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest, dict]]): + The request object. Request message for the ``GetBusinessIdentity`` method. + name (:class:`str`): + Required. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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, businessidentity.GetBusinessIdentityRequest): + request = businessidentity.GetBusinessIdentityRequest(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.get_business_identity] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_business_identity(self, + request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, + *, + business_identity: Optional[businessidentity.BusinessIdentity] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Updates the business identity of an account. + Executing this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( + ) + + # Make the request + response = await client.update_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest, dict]]): + The request object. Request message for the ``UpdateBusinessIdentity`` + method. + business_identity (:class:`google.shopping.merchant_accounts_v1beta.types.BusinessIdentity`): + Required. The new version of the + business identity. + + This corresponds to the ``business_identity`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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 = [business_identity, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessidentity.UpdateBusinessIdentityRequest): + request = businessidentity.UpdateBusinessIdentityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_identity is not None: + request.business_identity = business_identity + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_identity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_identity.name", request.business_identity.name), + )), + ) + + # 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 __aenter__(self) -> "BusinessIdentityServiceAsyncClient": + 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__ = ( + "BusinessIdentityServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py new file mode 100644 index 000000000000..6b84a83a61a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py @@ -0,0 +1,847 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import businessidentity +from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import BusinessIdentityServiceGrpcTransport +from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport +from .transports.rest import BusinessIdentityServiceRestTransport + + +class BusinessIdentityServiceClientMeta(type): + """Metaclass for the BusinessIdentityService 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[BusinessIdentityServiceTransport]] + _transport_registry["grpc"] = BusinessIdentityServiceGrpcTransport + _transport_registry["grpc_asyncio"] = BusinessIdentityServiceGrpcAsyncIOTransport + _transport_registry["rest"] = BusinessIdentityServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[BusinessIdentityServiceTransport]: + """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 BusinessIdentityServiceClient(metaclass=BusinessIdentityServiceClientMeta): + """Service to support `business + identity `__ + API. + """ + + @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: + BusinessIdentityServiceClient: 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: + BusinessIdentityServiceClient: 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) -> BusinessIdentityServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessIdentityServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def business_identity_path(account: str,) -> str: + """Returns a fully-qualified business_identity string.""" + return "accounts/{account}/businessIdentity".format(account=account, ) + + @staticmethod + def parse_business_identity_path(path: str) -> Dict[str,str]: + """Parses a business_identity path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/businessIdentity$", 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 = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient._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, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business identity 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,BusinessIdentityServiceTransport,Callable[..., BusinessIdentityServiceTransport]]]): + 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 BusinessIdentityServiceTransport 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 = BusinessIdentityServiceClient._read_environment_variables() + self._client_cert_source = BusinessIdentityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = BusinessIdentityServiceClient._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, BusinessIdentityServiceTransport) + if transport_provided: + # transport is a BusinessIdentityServiceTransport 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(BusinessIdentityServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + BusinessIdentityServiceClient._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[BusinessIdentityServiceTransport], Callable[..., BusinessIdentityServiceTransport]] = ( + BusinessIdentityServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., BusinessIdentityServiceTransport], 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.accounts_v1beta.BusinessIdentityServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "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.accounts.v1beta.BusinessIdentityService", + "credentialsType": None, + } + ) + + def get_business_identity(self, + request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Retrieves the business identity of an 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_accounts_v1beta + + def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest, dict]): + The request object. Request message for the ``GetBusinessIdentity`` method. + name (str): + Required. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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, businessidentity.GetBusinessIdentityRequest): + request = businessidentity.GetBusinessIdentityRequest(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.get_business_identity] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_business_identity(self, + request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, + *, + business_identity: Optional[businessidentity.BusinessIdentity] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: + r"""Updates the business identity of an account. + Executing this method requires admin access. + + .. 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_accounts_v1beta + + def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( + ) + + # Make the request + response = client.update_business_identity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest, dict]): + The request object. Request message for the ``UpdateBusinessIdentity`` + method. + business_identity (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity): + Required. The new version of the + business identity. + + This corresponds to the ``business_identity`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessIdentity: + Collection of information related to the [identity of a + business](\ https://support.google.com/merchants/answer/12564247). + + """ + # 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 = [business_identity, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessidentity.UpdateBusinessIdentityRequest): + request = businessidentity.UpdateBusinessIdentityRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_identity is not None: + request.business_identity = business_identity + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_business_identity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_identity.name", request.business_identity.name), + )), + ) + + # 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 __enter__(self) -> "BusinessIdentityServiceClient": + 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__ = ( + "BusinessIdentityServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst new file mode 100644 index 000000000000..55db4f093f62 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`BusinessIdentityServiceTransport` is the ABC for all transports. +- public child `BusinessIdentityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `BusinessIdentityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseBusinessIdentityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `BusinessIdentityServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/__init__.py new file mode 100644 index 000000000000..0f211578bee2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_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 BusinessIdentityServiceTransport +from .grpc import BusinessIdentityServiceGrpcTransport +from .grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport +from .rest import BusinessIdentityServiceRestTransport +from .rest import BusinessIdentityServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessIdentityServiceTransport]] +_transport_registry['grpc'] = BusinessIdentityServiceGrpcTransport +_transport_registry['grpc_asyncio'] = BusinessIdentityServiceGrpcAsyncIOTransport +_transport_registry['rest'] = BusinessIdentityServiceRestTransport + +__all__ = ( + 'BusinessIdentityServiceTransport', + 'BusinessIdentityServiceGrpcTransport', + 'BusinessIdentityServiceGrpcAsyncIOTransport', + 'BusinessIdentityServiceRestTransport', + 'BusinessIdentityServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py new file mode 100644 index 000000000000..d0f37244bc6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import businessidentity + +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 BusinessIdentityServiceTransport(abc.ABC): + """Abstract transport class for BusinessIdentityService.""" + + 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.get_business_identity: gapic_v1.method.wrap_method( + self.get_business_identity, + default_timeout=None, + client_info=client_info, + ), + self.update_business_identity: gapic_v1.method.wrap_method( + self.update_business_identity, + 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 get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + Union[ + businessidentity.BusinessIdentity, + Awaitable[businessidentity.BusinessIdentity] + ]]: + raise NotImplementedError() + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + Union[ + businessidentity.BusinessIdentity, + Awaitable[businessidentity.BusinessIdentity] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'BusinessIdentityServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py new file mode 100644 index 000000000000..8365cef3bc93 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py @@ -0,0 +1,375 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import businessidentity +from .base import BusinessIdentityServiceTransport, 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.accounts.v1beta.BusinessIdentityService", + "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.accounts.v1beta.BusinessIdentityService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessIdentityServiceGrpcTransport(BusinessIdentityServiceTransport): + """gRPC backend transport for BusinessIdentityService. + + Service to support `business + identity `__ + API. + + 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 get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + r"""Return a callable for the get business identity method over gRPC. + + Retrieves the business identity of an account. + + Returns: + Callable[[~.GetBusinessIdentityRequest], + ~.BusinessIdentity]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_identity' not in self._stubs: + self._stubs['get_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/GetBusinessIdentity', + request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['get_business_identity'] + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + r"""Return a callable for the update business identity method over gRPC. + + Updates the business identity of an account. + Executing this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessIdentityRequest], + ~.BusinessIdentity]: + 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 'update_business_identity' not in self._stubs: + self._stubs['update_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/UpdateBusinessIdentity', + request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['update_business_identity'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'BusinessIdentityServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..7346ea703c54 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py @@ -0,0 +1,401 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import businessidentity +from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import BusinessIdentityServiceGrpcTransport + +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.accounts.v1beta.BusinessIdentityService", + "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.accounts.v1beta.BusinessIdentityService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessIdentityServiceGrpcAsyncIOTransport(BusinessIdentityServiceTransport): + """gRPC AsyncIO backend transport for BusinessIdentityService. + + Service to support `business + identity `__ + API. + + 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 get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + Awaitable[businessidentity.BusinessIdentity]]: + r"""Return a callable for the get business identity method over gRPC. + + Retrieves the business identity of an account. + + Returns: + Callable[[~.GetBusinessIdentityRequest], + Awaitable[~.BusinessIdentity]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_identity' not in self._stubs: + self._stubs['get_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/GetBusinessIdentity', + request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['get_business_identity'] + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + Awaitable[businessidentity.BusinessIdentity]]: + r"""Return a callable for the update business identity method over gRPC. + + Updates the business identity of an account. + Executing this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessIdentityRequest], + Awaitable[~.BusinessIdentity]]: + 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 'update_business_identity' not in self._stubs: + self._stubs['update_business_identity'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/UpdateBusinessIdentity', + request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, + response_deserializer=businessidentity.BusinessIdentity.deserialize, + ) + return self._stubs['update_business_identity'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_business_identity: self._wrap_method( + self.get_business_identity, + default_timeout=None, + client_info=client_info, + ), + self.update_business_identity: self._wrap_method( + self.update_business_identity, + 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__ = ( + 'BusinessIdentityServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py new file mode 100644 index 000000000000..f1c66a816840 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py @@ -0,0 +1,532 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import businessidentity + + +from .rest_base import _BaseBusinessIdentityServiceRestTransport +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 BusinessIdentityServiceRestInterceptor: + """Interceptor for BusinessIdentityService. + + 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 BusinessIdentityServiceRestTransport. + + .. code-block:: python + class MyCustomBusinessIdentityServiceInterceptor(BusinessIdentityServiceRestInterceptor): + def pre_get_business_identity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_business_identity(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_business_identity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_business_identity(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BusinessIdentityServiceRestTransport(interceptor=MyCustomBusinessIdentityServiceInterceptor()) + client = BusinessIdentityServiceClient(transport=transport) + + + """ + def pre_get_business_identity(self, request: businessidentity.GetBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_business_identity + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessIdentityService server. + """ + return request, metadata + + def post_get_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: + """Post-rpc interceptor for get_business_identity + + DEPRECATED. Please use the `post_get_business_identity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessIdentityService server but before + it is returned to user code. This `post_get_business_identity` interceptor runs + before the `post_get_business_identity_with_metadata` interceptor. + """ + return response + + def post_get_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_business_identity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessIdentityService server but before it is returned to user code. + + We recommend only using this `post_get_business_identity_with_metadata` + interceptor in new development instead of the `post_get_business_identity` interceptor. + When both interceptors are used, this `post_get_business_identity_with_metadata` interceptor runs after the + `post_get_business_identity` interceptor. The (possibly modified) response returned by + `post_get_business_identity` will be passed to + `post_get_business_identity_with_metadata`. + """ + return response, metadata + + def pre_update_business_identity(self, request: businessidentity.UpdateBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_business_identity + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessIdentityService server. + """ + return request, metadata + + def post_update_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: + """Post-rpc interceptor for update_business_identity + + DEPRECATED. Please use the `post_update_business_identity_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessIdentityService server but before + it is returned to user code. This `post_update_business_identity` interceptor runs + before the `post_update_business_identity_with_metadata` interceptor. + """ + return response + + def post_update_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_business_identity + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessIdentityService server but before it is returned to user code. + + We recommend only using this `post_update_business_identity_with_metadata` + interceptor in new development instead of the `post_update_business_identity` interceptor. + When both interceptors are used, this `post_update_business_identity_with_metadata` interceptor runs after the + `post_update_business_identity` interceptor. The (possibly modified) response returned by + `post_update_business_identity` will be passed to + `post_update_business_identity_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class BusinessIdentityServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BusinessIdentityServiceRestInterceptor + + +class BusinessIdentityServiceRestTransport(_BaseBusinessIdentityServiceRestTransport): + """REST backend synchronous transport for BusinessIdentityService. + + Service to support `business + identity `__ + API. + + 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[BusinessIdentityServiceRestInterceptor] = 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 BusinessIdentityServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity, BusinessIdentityServiceRestStub): + def __hash__(self): + return hash("BusinessIdentityServiceRestTransport.GetBusinessIdentity") + + @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: businessidentity.GetBusinessIdentityRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessidentity.BusinessIdentity: + r"""Call the get business identity method over HTTP. + + Args: + request (~.businessidentity.GetBusinessIdentityRequest): + The request object. Request message for the ``GetBusinessIdentity`` 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: + ~.businessidentity.BusinessIdentity: + Collection of information related to the `identity of a + business `__. + + """ + + http_options = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_http_options() + + request, metadata = self._interceptor.pre_get_business_identity(request, metadata) + transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessIdentityServiceClient.GetBusinessIdentity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "rpcName": "GetBusinessIdentity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessIdentityServiceRestTransport._GetBusinessIdentity._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 = businessidentity.BusinessIdentity() + pb_resp = businessidentity.BusinessIdentity.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_business_identity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_business_identity_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessidentity.BusinessIdentity.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.accounts_v1beta.BusinessIdentityServiceClient.get_business_identity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "rpcName": "GetBusinessIdentity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity, BusinessIdentityServiceRestStub): + def __hash__(self): + return hash("BusinessIdentityServiceRestTransport.UpdateBusinessIdentity") + + @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: businessidentity.UpdateBusinessIdentityRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessidentity.BusinessIdentity: + r"""Call the update business identity method over HTTP. + + Args: + request (~.businessidentity.UpdateBusinessIdentityRequest): + The request object. Request message for the ``UpdateBusinessIdentity`` + 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: + ~.businessidentity.BusinessIdentity: + Collection of information related to the `identity of a + business `__. + + """ + + http_options = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_http_options() + + request, metadata = self._interceptor.pre_update_business_identity(request, metadata) + transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_transcoded_request(http_options, request) + + body = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessIdentityServiceClient.UpdateBusinessIdentity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "rpcName": "UpdateBusinessIdentity", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessIdentityServiceRestTransport._UpdateBusinessIdentity._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 = businessidentity.BusinessIdentity() + pb_resp = businessidentity.BusinessIdentity.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_business_identity(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_business_identity_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessidentity.BusinessIdentity.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.accounts_v1beta.BusinessIdentityServiceClient.update_business_identity", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "rpcName": "UpdateBusinessIdentity", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_business_identity(self) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + # 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._GetBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_business_identity(self) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + businessidentity.BusinessIdentity]: + # 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._UpdateBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'BusinessIdentityServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py new file mode 100644 index 000000000000..1294de519fd2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import businessidentity + + +class _BaseBusinessIdentityServiceRestTransport(BusinessIdentityServiceTransport): + """Base REST backend transport for BusinessIdentityService. + + 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 _BaseGetBusinessIdentity: + 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': '/accounts/v1beta/{name=accounts/*/businessIdentity}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessidentity.GetBusinessIdentityRequest.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(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateBusinessIdentity: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{business_identity.name=accounts/*/businessIdentity}', + 'body': 'business_identity', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessidentity.UpdateBusinessIdentityRequest.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(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseBusinessIdentityServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py new file mode 100644 index 000000000000..df547a28f156 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_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 BusinessInfoServiceClient +from .async_client import BusinessInfoServiceAsyncClient + +__all__ = ( + 'BusinessInfoServiceClient', + 'BusinessInfoServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py new file mode 100644 index 000000000000..e96e7e15208b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py @@ -0,0 +1,488 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import businessinfo +from google.shopping.merchant_accounts_v1beta.types import customerservice +from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore +from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport +from .client import BusinessInfoServiceClient + +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 BusinessInfoServiceAsyncClient: + """Service to support business info API.""" + + _client: BusinessInfoServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = BusinessInfoServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = BusinessInfoServiceClient._DEFAULT_UNIVERSE + + business_info_path = staticmethod(BusinessInfoServiceClient.business_info_path) + parse_business_info_path = staticmethod(BusinessInfoServiceClient.parse_business_info_path) + common_billing_account_path = staticmethod(BusinessInfoServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(BusinessInfoServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(BusinessInfoServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(BusinessInfoServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(BusinessInfoServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(BusinessInfoServiceClient.parse_common_organization_path) + common_project_path = staticmethod(BusinessInfoServiceClient.common_project_path) + parse_common_project_path = staticmethod(BusinessInfoServiceClient.parse_common_project_path) + common_location_path = staticmethod(BusinessInfoServiceClient.common_location_path) + parse_common_location_path = staticmethod(BusinessInfoServiceClient.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: + BusinessInfoServiceAsyncClient: The constructed client. + """ + return BusinessInfoServiceClient.from_service_account_info.__func__(BusinessInfoServiceAsyncClient, 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: + BusinessInfoServiceAsyncClient: The constructed client. + """ + return BusinessInfoServiceClient.from_service_account_file.__func__(BusinessInfoServiceAsyncClient, 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 BusinessInfoServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> BusinessInfoServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessInfoServiceTransport: 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 = BusinessInfoServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business info 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,BusinessInfoServiceTransport,Callable[..., BusinessInfoServiceTransport]]]): + 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 BusinessInfoServiceTransport 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 = BusinessInfoServiceClient( + 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.accounts_v1beta.BusinessInfoServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "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.accounts.v1beta.BusinessInfoService", + "credentialsType": None, + } + ) + + async def get_business_info(self, + request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Retrieves the business info of an 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_accounts_v1beta + + async def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest, dict]]): + The request object. Request message for the ``GetBusinessInfo`` method. + name (:class:`str`): + Required. The resource name of the business info. + Format: ``accounts/{account}/businessInfo`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.BusinessInfo: + Collection of information related to + a business. + + """ + # 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, businessinfo.GetBusinessInfoRequest): + request = businessinfo.GetBusinessInfoRequest(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.get_business_info] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_business_info(self, + request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, + *, + business_info: Optional[businessinfo.BusinessInfo] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Updates the business info of an account. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( + ) + + # Make the request + response = await client.update_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest, dict]]): + The request object. Request message for the ``UpdateBusinessInfo`` method. + business_info (:class:`google.shopping.merchant_accounts_v1beta.types.BusinessInfo`): + Required. The new version of the + business info. + + This corresponds to the ``business_info`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessInfo: + Collection of information related to + a business. + + """ + # 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 = [business_info, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessinfo.UpdateBusinessInfoRequest): + request = businessinfo.UpdateBusinessInfoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_info is not None: + request.business_info = business_info + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_info] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_info.name", request.business_info.name), + )), + ) + + # 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 __aenter__(self) -> "BusinessInfoServiceAsyncClient": + 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__ = ( + "BusinessInfoServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py new file mode 100644 index 000000000000..bb89b973829c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py @@ -0,0 +1,847 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import businessinfo +from google.shopping.merchant_accounts_v1beta.types import customerservice +from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore +from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import BusinessInfoServiceGrpcTransport +from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport +from .transports.rest import BusinessInfoServiceRestTransport + + +class BusinessInfoServiceClientMeta(type): + """Metaclass for the BusinessInfoService 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[BusinessInfoServiceTransport]] + _transport_registry["grpc"] = BusinessInfoServiceGrpcTransport + _transport_registry["grpc_asyncio"] = BusinessInfoServiceGrpcAsyncIOTransport + _transport_registry["rest"] = BusinessInfoServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[BusinessInfoServiceTransport]: + """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 BusinessInfoServiceClient(metaclass=BusinessInfoServiceClientMeta): + """Service to support business info API.""" + + @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: + BusinessInfoServiceClient: 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: + BusinessInfoServiceClient: 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) -> BusinessInfoServiceTransport: + """Returns the transport used by the client instance. + + Returns: + BusinessInfoServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def business_info_path(account: str,) -> str: + """Returns a fully-qualified business_info string.""" + return "accounts/{account}/businessInfo".format(account=account, ) + + @staticmethod + def parse_business_info_path(path: str) -> Dict[str,str]: + """Parses a business_info path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/businessInfo$", 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 = BusinessInfoServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = BusinessInfoServiceClient._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 = BusinessInfoServiceClient._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, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the business info 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,BusinessInfoServiceTransport,Callable[..., BusinessInfoServiceTransport]]]): + 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 BusinessInfoServiceTransport 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 = BusinessInfoServiceClient._read_environment_variables() + self._client_cert_source = BusinessInfoServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = BusinessInfoServiceClient._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, BusinessInfoServiceTransport) + if transport_provided: + # transport is a BusinessInfoServiceTransport 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(BusinessInfoServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + BusinessInfoServiceClient._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[BusinessInfoServiceTransport], Callable[..., BusinessInfoServiceTransport]] = ( + BusinessInfoServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., BusinessInfoServiceTransport], 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.accounts_v1beta.BusinessInfoServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "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.accounts.v1beta.BusinessInfoService", + "credentialsType": None, + } + ) + + def get_business_info(self, + request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Retrieves the business info of an 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_accounts_v1beta + + def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest, dict]): + The request object. Request message for the ``GetBusinessInfo`` method. + name (str): + Required. The resource name of the business info. + Format: ``accounts/{account}/businessInfo`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.BusinessInfo: + Collection of information related to + a business. + + """ + # 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, businessinfo.GetBusinessInfoRequest): + request = businessinfo.GetBusinessInfoRequest(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.get_business_info] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_business_info(self, + request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, + *, + business_info: Optional[businessinfo.BusinessInfo] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: + r"""Updates the business info of an account. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( + ) + + # Make the request + response = client.update_business_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest, dict]): + The request object. Request message for the ``UpdateBusinessInfo`` method. + business_info (google.shopping.merchant_accounts_v1beta.types.BusinessInfo): + Required. The new version of the + business info. + + This corresponds to the ``business_info`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessInfo: + Collection of information related to + a business. + + """ + # 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 = [business_info, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, businessinfo.UpdateBusinessInfoRequest): + request = businessinfo.UpdateBusinessInfoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if business_info is not None: + request.business_info = business_info + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_business_info] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("business_info.name", request.business_info.name), + )), + ) + + # 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 __enter__(self) -> "BusinessInfoServiceClient": + 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__ = ( + "BusinessInfoServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst new file mode 100644 index 000000000000..1024050406f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`BusinessInfoServiceTransport` is the ABC for all transports. +- public child `BusinessInfoServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `BusinessInfoServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseBusinessInfoServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `BusinessInfoServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py new file mode 100644 index 000000000000..cd3235917a9f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_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 BusinessInfoServiceTransport +from .grpc import BusinessInfoServiceGrpcTransport +from .grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport +from .rest import BusinessInfoServiceRestTransport +from .rest import BusinessInfoServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessInfoServiceTransport]] +_transport_registry['grpc'] = BusinessInfoServiceGrpcTransport +_transport_registry['grpc_asyncio'] = BusinessInfoServiceGrpcAsyncIOTransport +_transport_registry['rest'] = BusinessInfoServiceRestTransport + +__all__ = ( + 'BusinessInfoServiceTransport', + 'BusinessInfoServiceGrpcTransport', + 'BusinessInfoServiceGrpcAsyncIOTransport', + 'BusinessInfoServiceRestTransport', + 'BusinessInfoServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py new file mode 100644 index 000000000000..fef070afb0f2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import businessinfo + +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 BusinessInfoServiceTransport(abc.ABC): + """Abstract transport class for BusinessInfoService.""" + + 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.get_business_info: gapic_v1.method.wrap_method( + self.get_business_info, + default_timeout=None, + client_info=client_info, + ), + self.update_business_info: gapic_v1.method.wrap_method( + self.update_business_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! + """ + raise NotImplementedError() + + @property + def get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + Union[ + businessinfo.BusinessInfo, + Awaitable[businessinfo.BusinessInfo] + ]]: + raise NotImplementedError() + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + Union[ + businessinfo.BusinessInfo, + Awaitable[businessinfo.BusinessInfo] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'BusinessInfoServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py new file mode 100644 index 000000000000..dc1e8c008e62 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py @@ -0,0 +1,373 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import businessinfo +from .base import BusinessInfoServiceTransport, 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.accounts.v1beta.BusinessInfoService", + "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.accounts.v1beta.BusinessInfoService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessInfoServiceGrpcTransport(BusinessInfoServiceTransport): + """gRPC backend transport for BusinessInfoService. + + Service to support business info API. + + 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 get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + businessinfo.BusinessInfo]: + r"""Return a callable for the get business info method over gRPC. + + Retrieves the business info of an account. + + Returns: + Callable[[~.GetBusinessInfoRequest], + ~.BusinessInfo]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_info' not in self._stubs: + self._stubs['get_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/GetBusinessInfo', + request_serializer=businessinfo.GetBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['get_business_info'] + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + businessinfo.BusinessInfo]: + r"""Return a callable for the update business info method over gRPC. + + Updates the business info of an account. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessInfoRequest], + ~.BusinessInfo]: + 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 'update_business_info' not in self._stubs: + self._stubs['update_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/UpdateBusinessInfo', + request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['update_business_info'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'BusinessInfoServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..d5f55c65110b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py @@ -0,0 +1,399 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import businessinfo +from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import BusinessInfoServiceGrpcTransport + +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.accounts.v1beta.BusinessInfoService", + "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.accounts.v1beta.BusinessInfoService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class BusinessInfoServiceGrpcAsyncIOTransport(BusinessInfoServiceTransport): + """gRPC AsyncIO backend transport for BusinessInfoService. + + Service to support business info API. + + 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 get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + Awaitable[businessinfo.BusinessInfo]]: + r"""Return a callable for the get business info method over gRPC. + + Retrieves the business info of an account. + + Returns: + Callable[[~.GetBusinessInfoRequest], + Awaitable[~.BusinessInfo]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_business_info' not in self._stubs: + self._stubs['get_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/GetBusinessInfo', + request_serializer=businessinfo.GetBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['get_business_info'] + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + Awaitable[businessinfo.BusinessInfo]]: + r"""Return a callable for the update business info method over gRPC. + + Updates the business info of an account. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateBusinessInfoRequest], + Awaitable[~.BusinessInfo]]: + 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 'update_business_info' not in self._stubs: + self._stubs['update_business_info'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/UpdateBusinessInfo', + request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, + response_deserializer=businessinfo.BusinessInfo.deserialize, + ) + return self._stubs['update_business_info'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_business_info: self._wrap_method( + self.get_business_info, + default_timeout=None, + client_info=client_info, + ), + self.update_business_info: self._wrap_method( + self.update_business_info, + 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__ = ( + 'BusinessInfoServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py new file mode 100644 index 000000000000..9e8ce6c7ea6c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py @@ -0,0 +1,529 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import businessinfo + + +from .rest_base import _BaseBusinessInfoServiceRestTransport +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 BusinessInfoServiceRestInterceptor: + """Interceptor for BusinessInfoService. + + 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 BusinessInfoServiceRestTransport. + + .. code-block:: python + class MyCustomBusinessInfoServiceInterceptor(BusinessInfoServiceRestInterceptor): + def pre_get_business_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_business_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_business_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_business_info(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BusinessInfoServiceRestTransport(interceptor=MyCustomBusinessInfoServiceInterceptor()) + client = BusinessInfoServiceClient(transport=transport) + + + """ + def pre_get_business_info(self, request: businessinfo.GetBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_business_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessInfoService server. + """ + return request, metadata + + def post_get_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: + """Post-rpc interceptor for get_business_info + + DEPRECATED. Please use the `post_get_business_info_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessInfoService server but before + it is returned to user code. This `post_get_business_info` interceptor runs + before the `post_get_business_info_with_metadata` interceptor. + """ + return response + + def post_get_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_business_info + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessInfoService server but before it is returned to user code. + + We recommend only using this `post_get_business_info_with_metadata` + interceptor in new development instead of the `post_get_business_info` interceptor. + When both interceptors are used, this `post_get_business_info_with_metadata` interceptor runs after the + `post_get_business_info` interceptor. The (possibly modified) response returned by + `post_get_business_info` will be passed to + `post_get_business_info_with_metadata`. + """ + return response, metadata + + def pre_update_business_info(self, request: businessinfo.UpdateBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_business_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the BusinessInfoService server. + """ + return request, metadata + + def post_update_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: + """Post-rpc interceptor for update_business_info + + DEPRECATED. Please use the `post_update_business_info_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BusinessInfoService server but before + it is returned to user code. This `post_update_business_info` interceptor runs + before the `post_update_business_info_with_metadata` interceptor. + """ + return response + + def post_update_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_business_info + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BusinessInfoService server but before it is returned to user code. + + We recommend only using this `post_update_business_info_with_metadata` + interceptor in new development instead of the `post_update_business_info` interceptor. + When both interceptors are used, this `post_update_business_info_with_metadata` interceptor runs after the + `post_update_business_info` interceptor. The (possibly modified) response returned by + `post_update_business_info` will be passed to + `post_update_business_info_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class BusinessInfoServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BusinessInfoServiceRestInterceptor + + +class BusinessInfoServiceRestTransport(_BaseBusinessInfoServiceRestTransport): + """REST backend synchronous transport for BusinessInfoService. + + Service to support business info API. + + 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[BusinessInfoServiceRestInterceptor] = 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 BusinessInfoServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo, BusinessInfoServiceRestStub): + def __hash__(self): + return hash("BusinessInfoServiceRestTransport.GetBusinessInfo") + + @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: businessinfo.GetBusinessInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessinfo.BusinessInfo: + r"""Call the get business info method over HTTP. + + Args: + request (~.businessinfo.GetBusinessInfoRequest): + The request object. Request message for the ``GetBusinessInfo`` 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: + ~.businessinfo.BusinessInfo: + Collection of information related to + a business. + + """ + + http_options = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_http_options() + + request, metadata = self._interceptor.pre_get_business_info(request, metadata) + transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessInfoServiceClient.GetBusinessInfo", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "rpcName": "GetBusinessInfo", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessInfoServiceRestTransport._GetBusinessInfo._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 = businessinfo.BusinessInfo() + pb_resp = businessinfo.BusinessInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_business_info(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_business_info_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessinfo.BusinessInfo.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.accounts_v1beta.BusinessInfoServiceClient.get_business_info", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "rpcName": "GetBusinessInfo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo, BusinessInfoServiceRestStub): + def __hash__(self): + return hash("BusinessInfoServiceRestTransport.UpdateBusinessInfo") + + @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: businessinfo.UpdateBusinessInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> businessinfo.BusinessInfo: + r"""Call the update business info method over HTTP. + + Args: + request (~.businessinfo.UpdateBusinessInfoRequest): + The request object. Request message for the ``UpdateBusinessInfo`` 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: + ~.businessinfo.BusinessInfo: + Collection of information related to + a business. + + """ + + http_options = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_http_options() + + request, metadata = self._interceptor.pre_update_business_info(request, metadata) + transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_transcoded_request(http_options, request) + + body = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessInfoServiceClient.UpdateBusinessInfo", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "rpcName": "UpdateBusinessInfo", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BusinessInfoServiceRestTransport._UpdateBusinessInfo._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 = businessinfo.BusinessInfo() + pb_resp = businessinfo.BusinessInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_business_info(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_business_info_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = businessinfo.BusinessInfo.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.accounts_v1beta.BusinessInfoServiceClient.update_business_info", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "rpcName": "UpdateBusinessInfo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_business_info(self) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + businessinfo.BusinessInfo]: + # 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._GetBusinessInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_business_info(self) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + businessinfo.BusinessInfo]: + # 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._UpdateBusinessInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'BusinessInfoServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py new file mode 100644 index 000000000000..769d8b6f81f0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import businessinfo + + +class _BaseBusinessInfoServiceRestTransport(BusinessInfoServiceTransport): + """Base REST backend transport for BusinessInfoService. + + 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 _BaseGetBusinessInfo: + 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': '/accounts/v1beta/{name=accounts/*/businessInfo}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessinfo.GetBusinessInfoRequest.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(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateBusinessInfo: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{business_info.name=accounts/*/businessInfo}', + 'body': 'business_info', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = businessinfo.UpdateBusinessInfoRequest.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(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseBusinessInfoServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/__init__.py new file mode 100644 index 000000000000..d3119c55bf22 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_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 CheckoutSettingsServiceClient +from .async_client import CheckoutSettingsServiceAsyncClient + +__all__ = ( + 'CheckoutSettingsServiceClient', + 'CheckoutSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py new file mode 100644 index 000000000000..818e9eeda5c6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py @@ -0,0 +1,706 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import checkoutsettings +from google.shopping.type.types import types +from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport +from .client import CheckoutSettingsServiceClient + +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 CheckoutSettingsServiceAsyncClient: + """Service for supporting `checkout + settings `__. + """ + + _client: CheckoutSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + + checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.checkout_settings_path) + parse_checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.parse_checkout_settings_path) + common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CheckoutSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CheckoutSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CheckoutSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CheckoutSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CheckoutSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(CheckoutSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(CheckoutSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(CheckoutSettingsServiceClient.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: + CheckoutSettingsServiceAsyncClient: The constructed client. + """ + return CheckoutSettingsServiceClient.from_service_account_info.__func__(CheckoutSettingsServiceAsyncClient, 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: + CheckoutSettingsServiceAsyncClient: The constructed client. + """ + return CheckoutSettingsServiceClient.from_service_account_file.__func__(CheckoutSettingsServiceAsyncClient, 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 CheckoutSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CheckoutSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CheckoutSettingsServiceTransport: 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 = CheckoutSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the checkout settings 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,CheckoutSettingsServiceTransport,Callable[..., CheckoutSettingsServiceTransport]]]): + 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 CheckoutSettingsServiceTransport 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 = CheckoutSettingsServiceClient( + 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.accounts_v1beta.CheckoutSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "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.accounts.v1beta.CheckoutSettingsService", + "credentialsType": None, + } + ) + + async def get_checkout_settings(self, + request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + .. 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_accounts_v1beta + + async def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest, dict]]): + The request object. Request message for ``GetCheckoutSettings`` method. + name (:class:`str`): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkoutsettings.GetCheckoutSettingsRequest): + request = checkoutsettings.GetCheckoutSettingsRequest(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.get_checkout_settings] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_checkout_settings(self, + request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Creates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1beta + + async def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest, dict]]): + The request object. Request message for the ``CreateCheckoutSettings`` + method. + parent (:class:`str`): + Required. The merchant account for which the + ``CheckoutSettings`` will be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + checkout_settings (:class:`google.shopping.merchant_accounts_v1beta.types.CheckoutSettings`): + Required. The ``CheckoutSettings`` object to create. + This corresponds to the ``checkout_settings`` 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_accounts_v1beta.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkout_settings] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.CreateCheckoutSettingsRequest): + request = checkoutsettings.CreateCheckoutSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if checkout_settings is not None: + request.checkout_settings = checkout_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_checkout_settings] + + # 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 update_checkout_settings(self, + request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, + *, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Updates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1beta + + async def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = await client.update_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest, dict]]): + The request object. Request message for the ``UpdateCheckoutSettings`` + method. + checkout_settings (:class:`google.shopping.merchant_accounts_v1beta.types.CheckoutSettings`): + Required. The updated version of the + ``CheckoutSettings``. The ``name`` field is used to + identify the ``CheckoutSettings``. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + This corresponds to the ``checkout_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``eligible_destinations`` + - ``uri_settings`` + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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 = [checkout_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.UpdateCheckoutSettingsRequest): + request = checkoutsettings.UpdateCheckoutSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if checkout_settings is not None: + request.checkout_settings = checkout_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_checkout_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("checkout_settings.name", request.checkout_settings.name), + )), + ) + + # 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_checkout_settings(self, + request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, + *, + name: 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 ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + .. 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_accounts_v1beta + + async def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + await client.delete_checkout_settings(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest, dict]]): + The request object. Request message for the ``DeleteCheckoutSettings`` + method. + name (:class:`str`): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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, checkoutsettings.DeleteCheckoutSettingsRequest): + request = checkoutsettings.DeleteCheckoutSettingsRequest(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_checkout_settings] + + # 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) -> "CheckoutSettingsServiceAsyncClient": + 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__ = ( + "CheckoutSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py new file mode 100644 index 000000000000..75bc7c0c2b6d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py @@ -0,0 +1,1063 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import checkoutsettings +from google.shopping.type.types import types +from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CheckoutSettingsServiceGrpcTransport +from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport +from .transports.rest import CheckoutSettingsServiceRestTransport + + +class CheckoutSettingsServiceClientMeta(type): + """Metaclass for the CheckoutSettingsService 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[CheckoutSettingsServiceTransport]] + _transport_registry["grpc"] = CheckoutSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CheckoutSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CheckoutSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CheckoutSettingsServiceTransport]: + """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 CheckoutSettingsServiceClient(metaclass=CheckoutSettingsServiceClientMeta): + """Service for supporting `checkout + settings `__. + """ + + @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: + CheckoutSettingsServiceClient: 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: + CheckoutSettingsServiceClient: 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) -> CheckoutSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CheckoutSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def checkout_settings_path(account: str,program: str,) -> str: + """Returns a fully-qualified checkout_settings string.""" + return "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) + + @staticmethod + def parse_checkout_settings_path(path: str) -> Dict[str,str]: + """Parses a checkout_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/programs/(?P.+?)/checkoutSettings$", 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 = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient._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, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the checkout settings 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,CheckoutSettingsServiceTransport,Callable[..., CheckoutSettingsServiceTransport]]]): + 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 CheckoutSettingsServiceTransport 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 = CheckoutSettingsServiceClient._read_environment_variables() + self._client_cert_source = CheckoutSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = CheckoutSettingsServiceClient._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, CheckoutSettingsServiceTransport) + if transport_provided: + # transport is a CheckoutSettingsServiceTransport 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(CheckoutSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + CheckoutSettingsServiceClient._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[CheckoutSettingsServiceTransport], Callable[..., CheckoutSettingsServiceTransport]] = ( + CheckoutSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., CheckoutSettingsServiceTransport], 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.accounts_v1beta.CheckoutSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "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.accounts.v1beta.CheckoutSettingsService", + "credentialsType": None, + } + ) + + def get_checkout_settings(self, + request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + .. 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_accounts_v1beta + + def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest, dict]): + The request object. Request message for ``GetCheckoutSettings`` method. + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkoutsettings.GetCheckoutSettingsRequest): + request = checkoutsettings.GetCheckoutSettingsRequest(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.get_checkout_settings] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_checkout_settings(self, + request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, + *, + parent: Optional[str] = None, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Creates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1beta + + def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest, dict]): + The request object. Request message for the ``CreateCheckoutSettings`` + method. + parent (str): + Required. The merchant account for which the + ``CheckoutSettings`` will be created. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): + Required. The ``CheckoutSettings`` object to create. + This corresponds to the ``checkout_settings`` 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_accounts_v1beta.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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, checkout_settings] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.CreateCheckoutSettingsRequest): + request = checkoutsettings.CreateCheckoutSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if checkout_settings is not None: + request.checkout_settings = checkout_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_checkout_settings] + + # 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 update_checkout_settings(self, + request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, + *, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: + r"""Updates ``CheckoutSettings`` for the given merchant. + + .. 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_accounts_v1beta + + def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = client.update_checkout_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest, dict]): + The request object. Request message for the ``UpdateCheckoutSettings`` + method. + checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): + Required. The updated version of the + ``CheckoutSettings``. The ``name`` field is used to + identify the ``CheckoutSettings``. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + This corresponds to the ``checkout_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following + fields are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``eligible_destinations`` + - ``uri_settings`` + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.CheckoutSettings: + [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for + a specific merchant. + + """ + # 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 = [checkout_settings, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, checkoutsettings.UpdateCheckoutSettingsRequest): + request = checkoutsettings.UpdateCheckoutSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if checkout_settings is not None: + request.checkout_settings = checkout_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_checkout_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("checkout_settings.name", request.checkout_settings.name), + )), + ) + + # 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_checkout_settings(self, + request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, + *, + name: 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 ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + .. 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_accounts_v1beta + + def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + client.delete_checkout_settings(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest, dict]): + The request object. Request message for the ``DeleteCheckoutSettings`` + method. + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + + 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, checkoutsettings.DeleteCheckoutSettingsRequest): + request = checkoutsettings.DeleteCheckoutSettingsRequest(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_checkout_settings] + + # 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) -> "CheckoutSettingsServiceClient": + 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__ = ( + "CheckoutSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst new file mode 100644 index 000000000000..95c14e3fa6f8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`CheckoutSettingsServiceTransport` is the ABC for all transports. +- public child `CheckoutSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `CheckoutSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseCheckoutSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `CheckoutSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/__init__.py new file mode 100644 index 000000000000..e319afd3cf0a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_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 CheckoutSettingsServiceTransport +from .grpc import CheckoutSettingsServiceGrpcTransport +from .grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport +from .rest import CheckoutSettingsServiceRestTransport +from .rest import CheckoutSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CheckoutSettingsServiceTransport]] +_transport_registry['grpc'] = CheckoutSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CheckoutSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = CheckoutSettingsServiceRestTransport + +__all__ = ( + 'CheckoutSettingsServiceTransport', + 'CheckoutSettingsServiceGrpcTransport', + 'CheckoutSettingsServiceGrpcAsyncIOTransport', + 'CheckoutSettingsServiceRestTransport', + 'CheckoutSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py new file mode 100644 index 000000000000..55cf215ccd10 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py @@ -0,0 +1,202 @@ +# -*- 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_accounts_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_accounts_v1beta.types import checkoutsettings + +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 CheckoutSettingsServiceTransport(abc.ABC): + """Abstract transport class for CheckoutSettingsService.""" + + 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.get_checkout_settings: gapic_v1.method.wrap_method( + self.get_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_checkout_settings: gapic_v1.method.wrap_method( + self.create_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_checkout_settings: gapic_v1.method.wrap_method( + self.update_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_checkout_settings: gapic_v1.method.wrap_method( + self.delete_checkout_settings, + 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 get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings] + ]]: + raise NotImplementedError() + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings] + ]]: + raise NotImplementedError() + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings] + ]]: + raise NotImplementedError() + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CheckoutSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py new file mode 100644 index 000000000000..6a1defe9f5db --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py @@ -0,0 +1,429 @@ +# -*- 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_accounts_v1beta.types import checkoutsettings +from .base import CheckoutSettingsServiceTransport, 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.accounts.v1beta.CheckoutSettingsService", + "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.accounts.v1beta.CheckoutSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class CheckoutSettingsServiceGrpcTransport(CheckoutSettingsServiceTransport): + """gRPC backend transport for CheckoutSettingsService. + + Service for supporting `checkout + settings `__. + + 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 get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + r"""Return a callable for the get checkout settings method over gRPC. + + Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + Returns: + Callable[[~.GetCheckoutSettingsRequest], + ~.CheckoutSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_checkout_settings' not in self._stubs: + self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/GetCheckoutSettings', + request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['get_checkout_settings'] + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + r"""Return a callable for the create checkout settings method over gRPC. + + Creates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.CreateCheckoutSettingsRequest], + ~.CheckoutSettings]: + 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 'create_checkout_settings' not in self._stubs: + self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/CreateCheckoutSettings', + request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['create_checkout_settings'] + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + r"""Return a callable for the update checkout settings method over gRPC. + + Updates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.UpdateCheckoutSettingsRequest], + ~.CheckoutSettings]: + 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 'update_checkout_settings' not in self._stubs: + self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/UpdateCheckoutSettings', + request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['update_checkout_settings'] + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete checkout settings method over gRPC. + + Deletes ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + Returns: + Callable[[~.DeleteCheckoutSettingsRequest], + ~.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_checkout_settings' not in self._stubs: + self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/DeleteCheckoutSettings', + request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_checkout_settings'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CheckoutSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..8db843ef7fbc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,465 @@ +# -*- 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_accounts_v1beta.types import checkoutsettings +from .base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CheckoutSettingsServiceGrpcTransport + +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.accounts.v1beta.CheckoutSettingsService", + "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.accounts.v1beta.CheckoutSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class CheckoutSettingsServiceGrpcAsyncIOTransport(CheckoutSettingsServiceTransport): + """gRPC AsyncIO backend transport for CheckoutSettingsService. + + Service for supporting `checkout + settings `__. + + 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 get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings]]: + r"""Return a callable for the get checkout settings method over gRPC. + + Gets ``CheckoutSettings`` for the given merchant. This includes + information about review state, enrollment state and URL + settings. + + Returns: + Callable[[~.GetCheckoutSettingsRequest], + Awaitable[~.CheckoutSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_checkout_settings' not in self._stubs: + self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/GetCheckoutSettings', + request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['get_checkout_settings'] + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings]]: + r"""Return a callable for the create checkout settings method over gRPC. + + Creates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.CreateCheckoutSettingsRequest], + Awaitable[~.CheckoutSettings]]: + 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 'create_checkout_settings' not in self._stubs: + self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/CreateCheckoutSettings', + request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['create_checkout_settings'] + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings]]: + r"""Return a callable for the update checkout settings method over gRPC. + + Updates ``CheckoutSettings`` for the given merchant. + + Returns: + Callable[[~.UpdateCheckoutSettingsRequest], + Awaitable[~.CheckoutSettings]]: + 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 'update_checkout_settings' not in self._stubs: + self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/UpdateCheckoutSettings', + request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, + response_deserializer=checkoutsettings.CheckoutSettings.deserialize, + ) + return self._stubs['update_checkout_settings'] + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete checkout settings method over gRPC. + + Deletes ``CheckoutSettings`` and unenrolls merchant from + ``Checkout`` program. + + Returns: + Callable[[~.DeleteCheckoutSettingsRequest], + 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_checkout_settings' not in self._stubs: + self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/DeleteCheckoutSettings', + request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_checkout_settings'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_checkout_settings: self._wrap_method( + self.get_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_checkout_settings: self._wrap_method( + self.create_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_checkout_settings: self._wrap_method( + self.update_checkout_settings, + default_timeout=None, + client_info=client_info, + ), + self.delete_checkout_settings: self._wrap_method( + self.delete_checkout_settings, + 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__ = ( + 'CheckoutSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py new file mode 100644 index 000000000000..a2a905a21da7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py @@ -0,0 +1,815 @@ +# -*- 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_accounts_v1beta.types import checkoutsettings + + +from .rest_base import _BaseCheckoutSettingsServiceRestTransport +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 CheckoutSettingsServiceRestInterceptor: + """Interceptor for CheckoutSettingsService. + + 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 CheckoutSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomCheckoutSettingsServiceInterceptor(CheckoutSettingsServiceRestInterceptor): + def pre_create_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_checkout_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_checkout_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_checkout_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_checkout_settings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CheckoutSettingsServiceRestTransport(interceptor=MyCustomCheckoutSettingsServiceInterceptor()) + client = CheckoutSettingsServiceClient(transport=transport) + + + """ + def pre_create_checkout_settings(self, request: checkoutsettings.CreateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CreateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def post_create_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + """Post-rpc interceptor for create_checkout_settings + + DEPRECATED. Please use the `post_create_checkout_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CheckoutSettingsService server but before + it is returned to user code. This `post_create_checkout_settings` interceptor runs + before the `post_create_checkout_settings_with_metadata` interceptor. + """ + return response + + def post_create_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_checkout_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CheckoutSettingsService server but before it is returned to user code. + + We recommend only using this `post_create_checkout_settings_with_metadata` + interceptor in new development instead of the `post_create_checkout_settings` interceptor. + When both interceptors are used, this `post_create_checkout_settings_with_metadata` interceptor runs after the + `post_create_checkout_settings` interceptor. The (possibly modified) response returned by + `post_create_checkout_settings` will be passed to + `post_create_checkout_settings_with_metadata`. + """ + return response, metadata + + def pre_delete_checkout_settings(self, request: checkoutsettings.DeleteCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.DeleteCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def pre_get_checkout_settings(self, request: checkoutsettings.GetCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.GetCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def post_get_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + """Post-rpc interceptor for get_checkout_settings + + DEPRECATED. Please use the `post_get_checkout_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CheckoutSettingsService server but before + it is returned to user code. This `post_get_checkout_settings` interceptor runs + before the `post_get_checkout_settings_with_metadata` interceptor. + """ + return response + + def post_get_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_checkout_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CheckoutSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_checkout_settings_with_metadata` + interceptor in new development instead of the `post_get_checkout_settings` interceptor. + When both interceptors are used, this `post_get_checkout_settings_with_metadata` interceptor runs after the + `post_get_checkout_settings` interceptor. The (possibly modified) response returned by + `post_get_checkout_settings` will be passed to + `post_get_checkout_settings_with_metadata`. + """ + return response, metadata + + def pre_update_checkout_settings(self, request: checkoutsettings.UpdateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.UpdateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_checkout_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the CheckoutSettingsService server. + """ + return request, metadata + + def post_update_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + """Post-rpc interceptor for update_checkout_settings + + DEPRECATED. Please use the `post_update_checkout_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the CheckoutSettingsService server but before + it is returned to user code. This `post_update_checkout_settings` interceptor runs + before the `post_update_checkout_settings_with_metadata` interceptor. + """ + return response + + def post_update_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_checkout_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the CheckoutSettingsService server but before it is returned to user code. + + We recommend only using this `post_update_checkout_settings_with_metadata` + interceptor in new development instead of the `post_update_checkout_settings` interceptor. + When both interceptors are used, this `post_update_checkout_settings_with_metadata` interceptor runs after the + `post_update_checkout_settings` interceptor. The (possibly modified) response returned by + `post_update_checkout_settings` will be passed to + `post_update_checkout_settings_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class CheckoutSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CheckoutSettingsServiceRestInterceptor + + +class CheckoutSettingsServiceRestTransport(_BaseCheckoutSettingsServiceRestTransport): + """REST backend synchronous transport for CheckoutSettingsService. + + Service for supporting `checkout + settings `__. + + 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[CheckoutSettingsServiceRestInterceptor] = 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 CheckoutSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.CreateCheckoutSettings") + + @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: checkoutsettings.CreateCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> checkoutsettings.CheckoutSettings: + r"""Call the create checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.CreateCheckoutSettingsRequest): + The request object. Request message for the ``CreateCheckoutSettings`` + 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: + ~.checkoutsettings.CheckoutSettings: + `CheckoutSettings `__ + for a specific merchant. + + """ + + http_options = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_create_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_transcoded_request(http_options, request) + + body = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.CreateCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "CreateCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._CreateCheckoutSettings._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 = checkoutsettings.CheckoutSettings() + pb_resp = checkoutsettings.CheckoutSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_checkout_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_checkout_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1beta.CheckoutSettingsServiceClient.create_checkout_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "CreateCheckoutSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.DeleteCheckoutSettings") + + @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: checkoutsettings.DeleteCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.DeleteCheckoutSettingsRequest): + The request object. Request message for the ``DeleteCheckoutSettings`` + 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 = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_delete_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.DeleteCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "DeleteCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._DeleteCheckoutSettings._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 _GetCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.GetCheckoutSettings") + + @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: checkoutsettings.GetCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> checkoutsettings.CheckoutSettings: + r"""Call the get checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.GetCheckoutSettingsRequest): + The request object. Request message for ``GetCheckoutSettings`` 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: + ~.checkoutsettings.CheckoutSettings: + `CheckoutSettings `__ + for a specific merchant. + + """ + + http_options = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_get_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.GetCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "GetCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._GetCheckoutSettings._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 = checkoutsettings.CheckoutSettings() + pb_resp = checkoutsettings.CheckoutSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_checkout_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_checkout_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1beta.CheckoutSettingsServiceClient.get_checkout_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "GetCheckoutSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings, CheckoutSettingsServiceRestStub): + def __hash__(self): + return hash("CheckoutSettingsServiceRestTransport.UpdateCheckoutSettings") + + @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: checkoutsettings.UpdateCheckoutSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> checkoutsettings.CheckoutSettings: + r"""Call the update checkout settings method over HTTP. + + Args: + request (~.checkoutsettings.UpdateCheckoutSettingsRequest): + The request object. Request message for the ``UpdateCheckoutSettings`` + 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: + ~.checkoutsettings.CheckoutSettings: + `CheckoutSettings `__ + for a specific merchant. + + """ + + http_options = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_http_options() + + request, metadata = self._interceptor.pre_update_checkout_settings(request, metadata) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_transcoded_request(http_options, request) + + body = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.UpdateCheckoutSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "UpdateCheckoutSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = CheckoutSettingsServiceRestTransport._UpdateCheckoutSettings._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 = checkoutsettings.CheckoutSettings() + pb_resp = checkoutsettings.CheckoutSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_checkout_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_checkout_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1beta.CheckoutSettingsServiceClient.update_checkout_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "rpcName": "UpdateCheckoutSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_checkout_settings(self) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + # 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._CreateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_checkout_settings(self) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + 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._DeleteCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_checkout_settings(self) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + # 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._GetCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_checkout_settings(self) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings]: + # 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._UpdateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'CheckoutSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..889ee8285a68 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py @@ -0,0 +1,260 @@ +# -*- 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 CheckoutSettingsServiceTransport, 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_accounts_v1beta.types import checkoutsettings + + +class _BaseCheckoutSettingsServiceRestTransport(CheckoutSettingsServiceTransport): + """Base REST backend transport for CheckoutSettingsService. + + 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 _BaseCreateCheckoutSettings: + 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': '/accounts/v1beta/{parent=accounts/*/programs/*}/checkoutSettings', + 'body': 'checkout_settings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.CreateCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteCheckoutSettings: + 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': '/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.DeleteCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCheckoutSettings: + 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': '/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.GetCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCheckoutSettings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}', + 'body': 'checkout_settings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = checkoutsettings.UpdateCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseCheckoutSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/__init__.py new file mode 100644 index 000000000000..d5ee3fce97c1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_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 EmailPreferencesServiceClient +from .async_client import EmailPreferencesServiceAsyncClient + +__all__ = ( + 'EmailPreferencesServiceClient', + 'EmailPreferencesServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py new file mode 100644 index 000000000000..89c8ffe57304 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py @@ -0,0 +1,511 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import emailpreferences +from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport +from .client import EmailPreferencesServiceClient + +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 EmailPreferencesServiceAsyncClient: + """Service to support the ``EmailPreferences`` API. + + This service only permits retrieving and updating email preferences + for the authenticated user. + """ + + _client: EmailPreferencesServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + + email_preferences_path = staticmethod(EmailPreferencesServiceClient.email_preferences_path) + parse_email_preferences_path = staticmethod(EmailPreferencesServiceClient.parse_email_preferences_path) + common_billing_account_path = staticmethod(EmailPreferencesServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EmailPreferencesServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EmailPreferencesServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(EmailPreferencesServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(EmailPreferencesServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(EmailPreferencesServiceClient.parse_common_organization_path) + common_project_path = staticmethod(EmailPreferencesServiceClient.common_project_path) + parse_common_project_path = staticmethod(EmailPreferencesServiceClient.parse_common_project_path) + common_location_path = staticmethod(EmailPreferencesServiceClient.common_location_path) + parse_common_location_path = staticmethod(EmailPreferencesServiceClient.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: + EmailPreferencesServiceAsyncClient: The constructed client. + """ + return EmailPreferencesServiceClient.from_service_account_info.__func__(EmailPreferencesServiceAsyncClient, 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: + EmailPreferencesServiceAsyncClient: The constructed client. + """ + return EmailPreferencesServiceClient.from_service_account_file.__func__(EmailPreferencesServiceAsyncClient, 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 EmailPreferencesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EmailPreferencesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EmailPreferencesServiceTransport: 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 = EmailPreferencesServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the email preferences 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,EmailPreferencesServiceTransport,Callable[..., EmailPreferencesServiceTransport]]]): + 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 EmailPreferencesServiceTransport 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 = EmailPreferencesServiceClient( + 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.accounts_v1beta.EmailPreferencesServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "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.accounts.v1beta.EmailPreferencesService", + "credentialsType": None, + } + ) + + async def get_email_preferences(self, + request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Returns the email preferences for a Merchant Center account + user. + + Use the name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + .. 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_accounts_v1beta + + async def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest, dict]]): + The request object. Request message for + GetEmailPreferences method. + name (:class:`str`): + Required. The name of the ``EmailPreferences`` resource. + Format: + ``accounts/{account}/users/{email}/emailPreferences`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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, emailpreferences.GetEmailPreferencesRequest): + request = emailpreferences.GetEmailPreferencesRequest(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.get_email_preferences] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_email_preferences(self, + request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, + *, + email_preferences: Optional[emailpreferences.EmailPreferences] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Updates the email preferences for a Merchant Center account + user. MCA users should specify the MCA account rather than a + sub-account of the MCA. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + .. 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_accounts_v1beta + + async def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = await client.update_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest, dict]]): + The request object. Request message for + UpdateEmailPreferences method. + email_preferences (:class:`google.shopping.merchant_accounts_v1beta.types.EmailPreferences`): + Required. Email Preferences to be + updated. + + This corresponds to the ``email_preferences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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 = [email_preferences, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, emailpreferences.UpdateEmailPreferencesRequest): + request = emailpreferences.UpdateEmailPreferencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if email_preferences is not None: + request.email_preferences = email_preferences + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_email_preferences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("email_preferences.name", request.email_preferences.name), + )), + ) + + # 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 __aenter__(self) -> "EmailPreferencesServiceAsyncClient": + 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__ = ( + "EmailPreferencesServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py new file mode 100644 index 000000000000..7cb796ba2b36 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py @@ -0,0 +1,870 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import emailpreferences +from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EmailPreferencesServiceGrpcTransport +from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport +from .transports.rest import EmailPreferencesServiceRestTransport + + +class EmailPreferencesServiceClientMeta(type): + """Metaclass for the EmailPreferencesService 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[EmailPreferencesServiceTransport]] + _transport_registry["grpc"] = EmailPreferencesServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EmailPreferencesServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EmailPreferencesServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EmailPreferencesServiceTransport]: + """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 EmailPreferencesServiceClient(metaclass=EmailPreferencesServiceClientMeta): + """Service to support the ``EmailPreferences`` API. + + This service only permits retrieving and updating email preferences + for the authenticated user. + """ + + @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: + EmailPreferencesServiceClient: 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: + EmailPreferencesServiceClient: 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) -> EmailPreferencesServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EmailPreferencesServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def email_preferences_path(account: str,email: str,) -> str: + """Returns a fully-qualified email_preferences string.""" + return "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) + + @staticmethod + def parse_email_preferences_path(path: str) -> Dict[str,str]: + """Parses a email_preferences path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/users/(?P.+?)/emailPreferences$", 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 = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient._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, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the email preferences 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,EmailPreferencesServiceTransport,Callable[..., EmailPreferencesServiceTransport]]]): + 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 EmailPreferencesServiceTransport 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 = EmailPreferencesServiceClient._read_environment_variables() + self._client_cert_source = EmailPreferencesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EmailPreferencesServiceClient._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, EmailPreferencesServiceTransport) + if transport_provided: + # transport is a EmailPreferencesServiceTransport 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(EmailPreferencesServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EmailPreferencesServiceClient._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[EmailPreferencesServiceTransport], Callable[..., EmailPreferencesServiceTransport]] = ( + EmailPreferencesServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EmailPreferencesServiceTransport], 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.accounts_v1beta.EmailPreferencesServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "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.accounts.v1beta.EmailPreferencesService", + "credentialsType": None, + } + ) + + def get_email_preferences(self, + request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Returns the email preferences for a Merchant Center account + user. + + Use the name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + .. 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_accounts_v1beta + + def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = client.get_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest, dict]): + The request object. Request message for + GetEmailPreferences method. + name (str): + Required. The name of the ``EmailPreferences`` resource. + Format: + ``accounts/{account}/users/{email}/emailPreferences`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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, emailpreferences.GetEmailPreferencesRequest): + request = emailpreferences.GetEmailPreferencesRequest(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.get_email_preferences] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_email_preferences(self, + request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, + *, + email_preferences: Optional[emailpreferences.EmailPreferences] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: + r"""Updates the email preferences for a Merchant Center account + user. MCA users should specify the MCA account rather than a + sub-account of the MCA. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + .. 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_accounts_v1beta + + def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = client.update_email_preferences(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest, dict]): + The request object. Request message for + UpdateEmailPreferences method. + email_preferences (google.shopping.merchant_accounts_v1beta.types.EmailPreferences): + Required. Email Preferences to be + updated. + + This corresponds to the ``email_preferences`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + # 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 = [email_preferences, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, emailpreferences.UpdateEmailPreferencesRequest): + request = emailpreferences.UpdateEmailPreferencesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if email_preferences is not None: + request.email_preferences = email_preferences + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_email_preferences] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("email_preferences.name", request.email_preferences.name), + )), + ) + + # 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 __enter__(self) -> "EmailPreferencesServiceClient": + 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__ = ( + "EmailPreferencesServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst new file mode 100644 index 000000000000..210db60dee0d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EmailPreferencesServiceTransport` is the ABC for all transports. +- public child `EmailPreferencesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EmailPreferencesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEmailPreferencesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EmailPreferencesServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py new file mode 100644 index 000000000000..3bfd9590e738 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_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 EmailPreferencesServiceTransport +from .grpc import EmailPreferencesServiceGrpcTransport +from .grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport +from .rest import EmailPreferencesServiceRestTransport +from .rest import EmailPreferencesServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EmailPreferencesServiceTransport]] +_transport_registry['grpc'] = EmailPreferencesServiceGrpcTransport +_transport_registry['grpc_asyncio'] = EmailPreferencesServiceGrpcAsyncIOTransport +_transport_registry['rest'] = EmailPreferencesServiceRestTransport + +__all__ = ( + 'EmailPreferencesServiceTransport', + 'EmailPreferencesServiceGrpcTransport', + 'EmailPreferencesServiceGrpcAsyncIOTransport', + 'EmailPreferencesServiceRestTransport', + 'EmailPreferencesServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py new file mode 100644 index 000000000000..97b309b8efa6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import emailpreferences + +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 EmailPreferencesServiceTransport(abc.ABC): + """Abstract transport class for EmailPreferencesService.""" + + 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.get_email_preferences: gapic_v1.method.wrap_method( + self.get_email_preferences, + default_timeout=None, + client_info=client_info, + ), + self.update_email_preferences: gapic_v1.method.wrap_method( + self.update_email_preferences, + 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 get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + Union[ + emailpreferences.EmailPreferences, + Awaitable[emailpreferences.EmailPreferences] + ]]: + raise NotImplementedError() + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + Union[ + emailpreferences.EmailPreferences, + Awaitable[emailpreferences.EmailPreferences] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'EmailPreferencesServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py new file mode 100644 index 000000000000..fc2def7546ee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py @@ -0,0 +1,390 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import emailpreferences +from .base import EmailPreferencesServiceTransport, 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.accounts.v1beta.EmailPreferencesService", + "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.accounts.v1beta.EmailPreferencesService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EmailPreferencesServiceGrpcTransport(EmailPreferencesServiceTransport): + """gRPC backend transport for EmailPreferencesService. + + Service to support the ``EmailPreferences`` API. + + This service only permits retrieving and updating email preferences + for the authenticated user. + + 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 get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + r"""Return a callable for the get email preferences method over gRPC. + + Returns the email preferences for a Merchant Center account + user. + + Use the name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + Returns: + Callable[[~.GetEmailPreferencesRequest], + ~.EmailPreferences]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_email_preferences' not in self._stubs: + self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/GetEmailPreferences', + request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['get_email_preferences'] + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + r"""Return a callable for the update email preferences method over gRPC. + + Updates the email preferences for a Merchant Center account + user. MCA users should specify the MCA account rather than a + sub-account of the MCA. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + Returns: + Callable[[~.UpdateEmailPreferencesRequest], + ~.EmailPreferences]: + 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 'update_email_preferences' not in self._stubs: + self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/UpdateEmailPreferences', + request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['update_email_preferences'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'EmailPreferencesServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..40c3f11f0d17 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py @@ -0,0 +1,416 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import emailpreferences +from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import EmailPreferencesServiceGrpcTransport + +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.accounts.v1beta.EmailPreferencesService", + "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.accounts.v1beta.EmailPreferencesService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EmailPreferencesServiceGrpcAsyncIOTransport(EmailPreferencesServiceTransport): + """gRPC AsyncIO backend transport for EmailPreferencesService. + + Service to support the ``EmailPreferences`` API. + + This service only permits retrieving and updating email preferences + for the authenticated user. + + 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 get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + Awaitable[emailpreferences.EmailPreferences]]: + r"""Return a callable for the get email preferences method over gRPC. + + Returns the email preferences for a Merchant Center account + user. + + Use the name=accounts/*/users/me/emailPreferences alias to get + preferences for the authenticated user. + + Returns: + Callable[[~.GetEmailPreferencesRequest], + Awaitable[~.EmailPreferences]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_email_preferences' not in self._stubs: + self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/GetEmailPreferences', + request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['get_email_preferences'] + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + Awaitable[emailpreferences.EmailPreferences]]: + r"""Return a callable for the update email preferences method over gRPC. + + Updates the email preferences for a Merchant Center account + user. MCA users should specify the MCA account rather than a + sub-account of the MCA. + + Preferences which are not explicitly selected in the update mask + will not be updated. + + It is invalid for updates to specify an UNCONFIRMED opt-in + status value. + + Use the name=accounts/*/users/me/emailPreferences alias to + update preferences for the authenticated user. + + Returns: + Callable[[~.UpdateEmailPreferencesRequest], + Awaitable[~.EmailPreferences]]: + 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 'update_email_preferences' not in self._stubs: + self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/UpdateEmailPreferences', + request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, + response_deserializer=emailpreferences.EmailPreferences.deserialize, + ) + return self._stubs['update_email_preferences'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_email_preferences: self._wrap_method( + self.get_email_preferences, + default_timeout=None, + client_info=client_info, + ), + self.update_email_preferences: self._wrap_method( + self.update_email_preferences, + 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__ = ( + 'EmailPreferencesServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py new file mode 100644 index 000000000000..0a85982cd5a1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py @@ -0,0 +1,540 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import emailpreferences + + +from .rest_base import _BaseEmailPreferencesServiceRestTransport +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 EmailPreferencesServiceRestInterceptor: + """Interceptor for EmailPreferencesService. + + 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 EmailPreferencesServiceRestTransport. + + .. code-block:: python + class MyCustomEmailPreferencesServiceInterceptor(EmailPreferencesServiceRestInterceptor): + def pre_get_email_preferences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_email_preferences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_email_preferences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_email_preferences(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EmailPreferencesServiceRestTransport(interceptor=MyCustomEmailPreferencesServiceInterceptor()) + client = EmailPreferencesServiceClient(transport=transport) + + + """ + def pre_get_email_preferences(self, request: emailpreferences.GetEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_email_preferences + + Override in a subclass to manipulate the request or metadata + before they are sent to the EmailPreferencesService server. + """ + return request, metadata + + def post_get_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: + """Post-rpc interceptor for get_email_preferences + + DEPRECATED. Please use the `post_get_email_preferences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EmailPreferencesService server but before + it is returned to user code. This `post_get_email_preferences` interceptor runs + before the `post_get_email_preferences_with_metadata` interceptor. + """ + return response + + def post_get_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_email_preferences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EmailPreferencesService server but before it is returned to user code. + + We recommend only using this `post_get_email_preferences_with_metadata` + interceptor in new development instead of the `post_get_email_preferences` interceptor. + When both interceptors are used, this `post_get_email_preferences_with_metadata` interceptor runs after the + `post_get_email_preferences` interceptor. The (possibly modified) response returned by + `post_get_email_preferences` will be passed to + `post_get_email_preferences_with_metadata`. + """ + return response, metadata + + def pre_update_email_preferences(self, request: emailpreferences.UpdateEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_email_preferences + + Override in a subclass to manipulate the request or metadata + before they are sent to the EmailPreferencesService server. + """ + return request, metadata + + def post_update_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: + """Post-rpc interceptor for update_email_preferences + + DEPRECATED. Please use the `post_update_email_preferences_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EmailPreferencesService server but before + it is returned to user code. This `post_update_email_preferences` interceptor runs + before the `post_update_email_preferences_with_metadata` interceptor. + """ + return response + + def post_update_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_email_preferences + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EmailPreferencesService server but before it is returned to user code. + + We recommend only using this `post_update_email_preferences_with_metadata` + interceptor in new development instead of the `post_update_email_preferences` interceptor. + When both interceptors are used, this `post_update_email_preferences_with_metadata` interceptor runs after the + `post_update_email_preferences` interceptor. The (possibly modified) response returned by + `post_update_email_preferences` will be passed to + `post_update_email_preferences_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class EmailPreferencesServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EmailPreferencesServiceRestInterceptor + + +class EmailPreferencesServiceRestTransport(_BaseEmailPreferencesServiceRestTransport): + """REST backend synchronous transport for EmailPreferencesService. + + Service to support the ``EmailPreferences`` API. + + This service only permits retrieving and updating email preferences + for the authenticated user. + + 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[EmailPreferencesServiceRestInterceptor] = 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 EmailPreferencesServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences, EmailPreferencesServiceRestStub): + def __hash__(self): + return hash("EmailPreferencesServiceRestTransport.GetEmailPreferences") + + @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: emailpreferences.GetEmailPreferencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> emailpreferences.EmailPreferences: + r"""Call the get email preferences method over HTTP. + + Args: + request (~.emailpreferences.GetEmailPreferencesRequest): + The request object. Request message for + GetEmailPreferences 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: + ~.emailpreferences.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + + http_options = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_http_options() + + request, metadata = self._interceptor.pre_get_email_preferences(request, metadata) + transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.EmailPreferencesServiceClient.GetEmailPreferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "rpcName": "GetEmailPreferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EmailPreferencesServiceRestTransport._GetEmailPreferences._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 = emailpreferences.EmailPreferences() + pb_resp = emailpreferences.EmailPreferences.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_email_preferences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_email_preferences_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = emailpreferences.EmailPreferences.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.accounts_v1beta.EmailPreferencesServiceClient.get_email_preferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "rpcName": "GetEmailPreferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences, EmailPreferencesServiceRestStub): + def __hash__(self): + return hash("EmailPreferencesServiceRestTransport.UpdateEmailPreferences") + + @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: emailpreferences.UpdateEmailPreferencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> emailpreferences.EmailPreferences: + r"""Call the update email preferences method over HTTP. + + Args: + request (~.emailpreferences.UpdateEmailPreferencesRequest): + The request object. Request message for + UpdateEmailPreferences 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: + ~.emailpreferences.EmailPreferences: + The categories of notifications the + user opted into / opted out of. The + email preferences do not include + mandatory announcements as users can't + opt out of them. + + """ + + http_options = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_http_options() + + request, metadata = self._interceptor.pre_update_email_preferences(request, metadata) + transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_transcoded_request(http_options, request) + + body = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.EmailPreferencesServiceClient.UpdateEmailPreferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "rpcName": "UpdateEmailPreferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EmailPreferencesServiceRestTransport._UpdateEmailPreferences._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 = emailpreferences.EmailPreferences() + pb_resp = emailpreferences.EmailPreferences.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_email_preferences(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_email_preferences_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = emailpreferences.EmailPreferences.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.accounts_v1beta.EmailPreferencesServiceClient.update_email_preferences", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "rpcName": "UpdateEmailPreferences", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_email_preferences(self) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + # 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._GetEmailPreferences(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_email_preferences(self) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + emailpreferences.EmailPreferences]: + # 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._UpdateEmailPreferences(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EmailPreferencesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py new file mode 100644 index 000000000000..659b72806a24 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import emailpreferences + + +class _BaseEmailPreferencesServiceRestTransport(EmailPreferencesServiceTransport): + """Base REST backend transport for EmailPreferencesService. + + 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 _BaseGetEmailPreferences: + 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': '/accounts/v1beta/{name=accounts/*/users/*/emailPreferences}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = emailpreferences.GetEmailPreferencesRequest.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(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEmailPreferences: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{email_preferences.name=accounts/*/users/*/emailPreferences}', + 'body': 'email_preferences', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = emailpreferences.UpdateEmailPreferencesRequest.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(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseEmailPreferencesServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/__init__.py new file mode 100644 index 000000000000..38f66e5e7f00 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_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 GbpAccountsServiceClient +from .async_client import GbpAccountsServiceAsyncClient + +__all__ = ( + 'GbpAccountsServiceClient', + 'GbpAccountsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py new file mode 100644 index 000000000000..a2de8f492817 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py @@ -0,0 +1,502 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import pagers +from google.shopping.merchant_accounts_v1beta.types import gbpaccounts +from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport +from .client import GbpAccountsServiceClient + +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 GbpAccountsServiceAsyncClient: + """The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + """ + + _client: GbpAccountsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = GbpAccountsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = GbpAccountsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(GbpAccountsServiceClient.account_path) + parse_account_path = staticmethod(GbpAccountsServiceClient.parse_account_path) + gbp_account_path = staticmethod(GbpAccountsServiceClient.gbp_account_path) + parse_gbp_account_path = staticmethod(GbpAccountsServiceClient.parse_gbp_account_path) + common_billing_account_path = staticmethod(GbpAccountsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(GbpAccountsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(GbpAccountsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(GbpAccountsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(GbpAccountsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(GbpAccountsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(GbpAccountsServiceClient.common_project_path) + parse_common_project_path = staticmethod(GbpAccountsServiceClient.parse_common_project_path) + common_location_path = staticmethod(GbpAccountsServiceClient.common_location_path) + parse_common_location_path = staticmethod(GbpAccountsServiceClient.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: + GbpAccountsServiceAsyncClient: The constructed client. + """ + return GbpAccountsServiceClient.from_service_account_info.__func__(GbpAccountsServiceAsyncClient, 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: + GbpAccountsServiceAsyncClient: The constructed client. + """ + return GbpAccountsServiceClient.from_service_account_file.__func__(GbpAccountsServiceAsyncClient, 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 GbpAccountsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GbpAccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GbpAccountsServiceTransport: 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 = GbpAccountsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gbp accounts 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,GbpAccountsServiceTransport,Callable[..., GbpAccountsServiceTransport]]]): + 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 GbpAccountsServiceTransport 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 = GbpAccountsServiceClient( + 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.accounts_v1beta.GbpAccountsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "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.accounts.v1beta.GbpAccountsService", + "credentialsType": None, + } + ) + + async def list_gbp_accounts(self, + request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsAsyncPager: + r"""List the GBP accounts for a given merchant. + + .. 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_accounts_v1beta + + async def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest, dict]]): + The request object. Request message for the + ListGbpAccounts method. + parent (:class:`str`): + Required. The name of the parent resource under which + the GBP accounts are listed. Format: + ``accounts/{account}``. + + 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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsAsyncPager: + Response message for the + ListGbpAccounts 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, gbpaccounts.ListGbpAccountsRequest): + request = gbpaccounts.ListGbpAccountsRequest(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_gbp_accounts] + + # 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.ListGbpAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def link_gbp_account(self, + request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: + r"""Link the specified merchant to a GBP account for all + countries. + + .. 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_accounts_v1beta + + async def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = await client.link_gbp_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest, dict]]): + The request object. Request message for the + LinkGbpAccount method. + parent (:class:`str`): + Required. The name of the parent resource to which the + GBP account is linked. Format: ``accounts/{account}``. + + 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_accounts_v1beta.types.LinkGbpAccountResponse: + Response message for the + LinkGbpAccount method. + + """ + # 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, gbpaccounts.LinkGbpAccountRequest): + request = gbpaccounts.LinkGbpAccountRequest(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.link_gbp_account] + + # 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 __aenter__(self) -> "GbpAccountsServiceAsyncClient": + 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__ = ( + "GbpAccountsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py new file mode 100644 index 000000000000..784e95feb0ea --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py @@ -0,0 +1,870 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import pagers +from google.shopping.merchant_accounts_v1beta.types import gbpaccounts +from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import GbpAccountsServiceGrpcTransport +from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport +from .transports.rest import GbpAccountsServiceRestTransport + + +class GbpAccountsServiceClientMeta(type): + """Metaclass for the GbpAccountsService 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[GbpAccountsServiceTransport]] + _transport_registry["grpc"] = GbpAccountsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = GbpAccountsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = GbpAccountsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[GbpAccountsServiceTransport]: + """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 GbpAccountsServiceClient(metaclass=GbpAccountsServiceClientMeta): + """The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + """ + + @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: + GbpAccountsServiceClient: 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: + GbpAccountsServiceClient: 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) -> GbpAccountsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + GbpAccountsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def gbp_account_path(account: str,gbp_account: str,) -> str: + """Returns a fully-qualified gbp_account string.""" + return "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) + + @staticmethod + def parse_gbp_account_path(path: str) -> Dict[str,str]: + """Parses a gbp_account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/gbpAccounts/(?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 = GbpAccountsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = GbpAccountsServiceClient._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 = GbpAccountsServiceClient._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, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the gbp accounts 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,GbpAccountsServiceTransport,Callable[..., GbpAccountsServiceTransport]]]): + 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 GbpAccountsServiceTransport 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 = GbpAccountsServiceClient._read_environment_variables() + self._client_cert_source = GbpAccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = GbpAccountsServiceClient._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, GbpAccountsServiceTransport) + if transport_provided: + # transport is a GbpAccountsServiceTransport 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(GbpAccountsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + GbpAccountsServiceClient._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[GbpAccountsServiceTransport], Callable[..., GbpAccountsServiceTransport]] = ( + GbpAccountsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., GbpAccountsServiceTransport], 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.accounts_v1beta.GbpAccountsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "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.accounts.v1beta.GbpAccountsService", + "credentialsType": None, + } + ) + + def list_gbp_accounts(self, + request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsPager: + r"""List the GBP accounts for a given merchant. + + .. 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_accounts_v1beta + + def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest, dict]): + The request object. Request message for the + ListGbpAccounts method. + parent (str): + Required. The name of the parent resource under which + the GBP accounts are listed. Format: + ``accounts/{account}``. + + 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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsPager: + Response message for the + ListGbpAccounts 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, gbpaccounts.ListGbpAccountsRequest): + request = gbpaccounts.ListGbpAccountsRequest(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_gbp_accounts] + + # 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.ListGbpAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def link_gbp_account(self, + request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: + r"""Link the specified merchant to a GBP account for all + countries. + + .. 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_accounts_v1beta + + def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = client.link_gbp_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest, dict]): + The request object. Request message for the + LinkGbpAccount method. + parent (str): + Required. The name of the parent resource to which the + GBP account is linked. Format: ``accounts/{account}``. + + 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_accounts_v1beta.types.LinkGbpAccountResponse: + Response message for the + LinkGbpAccount method. + + """ + # 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, gbpaccounts.LinkGbpAccountRequest): + request = gbpaccounts.LinkGbpAccountRequest(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.link_gbp_account] + + # 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 __enter__(self) -> "GbpAccountsServiceClient": + 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__ = ( + "GbpAccountsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/pagers.py new file mode 100644 index 000000000000..60cac6505c7b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_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_accounts_v1beta.types import gbpaccounts + + +class ListGbpAccountsPager: + """A pager for iterating through ``list_gbp_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``gbp_accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGbpAccounts`` requests and continue to iterate + through the ``gbp_accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` + 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[..., gbpaccounts.ListGbpAccountsResponse], + request: gbpaccounts.ListGbpAccountsRequest, + response: gbpaccounts.ListGbpAccountsResponse, + *, + 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_accounts_v1beta.types.ListGbpAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse): + 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 = gbpaccounts.ListGbpAccountsRequest(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[gbpaccounts.ListGbpAccountsResponse]: + 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[gbpaccounts.GbpAccount]: + for page in self.pages: + yield from page.gbp_accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGbpAccountsAsyncPager: + """A pager for iterating through ``list_gbp_accounts`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``gbp_accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGbpAccounts`` requests and continue to iterate + through the ``gbp_accounts`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` + 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[gbpaccounts.ListGbpAccountsResponse]], + request: gbpaccounts.ListGbpAccountsRequest, + response: gbpaccounts.ListGbpAccountsResponse, + *, + 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_accounts_v1beta.types.ListGbpAccountsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse): + 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 = gbpaccounts.ListGbpAccountsRequest(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[gbpaccounts.ListGbpAccountsResponse]: + 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[gbpaccounts.GbpAccount]: + async def async_generator(): + async for page in self.pages: + for response in page.gbp_accounts: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst new file mode 100644 index 000000000000..a6f7710d74a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GbpAccountsServiceTransport` is the ABC for all transports. +- public child `GbpAccountsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GbpAccountsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGbpAccountsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GbpAccountsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/__init__.py new file mode 100644 index 000000000000..6576bf17bbcf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_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 GbpAccountsServiceTransport +from .grpc import GbpAccountsServiceGrpcTransport +from .grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport +from .rest import GbpAccountsServiceRestTransport +from .rest import GbpAccountsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[GbpAccountsServiceTransport]] +_transport_registry['grpc'] = GbpAccountsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = GbpAccountsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = GbpAccountsServiceRestTransport + +__all__ = ( + 'GbpAccountsServiceTransport', + 'GbpAccountsServiceGrpcTransport', + 'GbpAccountsServiceGrpcAsyncIOTransport', + 'GbpAccountsServiceRestTransport', + 'GbpAccountsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py new file mode 100644 index 000000000000..cfe39135bc52 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import gbpaccounts + +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 GbpAccountsServiceTransport(abc.ABC): + """Abstract transport class for GbpAccountsService.""" + + 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_gbp_accounts: gapic_v1.method.wrap_method( + self.list_gbp_accounts, + default_timeout=None, + client_info=client_info, + ), + self.link_gbp_account: gapic_v1.method.wrap_method( + self.link_gbp_account, + 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_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + Union[ + gbpaccounts.ListGbpAccountsResponse, + Awaitable[gbpaccounts.ListGbpAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + Union[ + gbpaccounts.LinkGbpAccountResponse, + Awaitable[gbpaccounts.LinkGbpAccountResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'GbpAccountsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py new file mode 100644 index 000000000000..5c856f73d726 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py @@ -0,0 +1,377 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import gbpaccounts +from .base import GbpAccountsServiceTransport, 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.accounts.v1beta.GbpAccountsService", + "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.accounts.v1beta.GbpAccountsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GbpAccountsServiceGrpcTransport(GbpAccountsServiceTransport): + """gRPC backend transport for GbpAccountsService. + + The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + + 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_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + gbpaccounts.ListGbpAccountsResponse]: + r"""Return a callable for the list gbp accounts method over gRPC. + + List the GBP accounts for a given merchant. + + Returns: + Callable[[~.ListGbpAccountsRequest], + ~.ListGbpAccountsResponse]: + 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_gbp_accounts' not in self._stubs: + self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/ListGbpAccounts', + request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, + response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, + ) + return self._stubs['list_gbp_accounts'] + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + gbpaccounts.LinkGbpAccountResponse]: + r"""Return a callable for the link gbp account method over gRPC. + + Link the specified merchant to a GBP account for all + countries. + + Returns: + Callable[[~.LinkGbpAccountRequest], + ~.LinkGbpAccountResponse]: + 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 'link_gbp_account' not in self._stubs: + self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/LinkGbpAccount', + request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, + response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, + ) + return self._stubs['link_gbp_account'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'GbpAccountsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..62bbcfae57d4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py @@ -0,0 +1,403 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import gbpaccounts +from .base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import GbpAccountsServiceGrpcTransport + +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.accounts.v1beta.GbpAccountsService", + "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.accounts.v1beta.GbpAccountsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GbpAccountsServiceGrpcAsyncIOTransport(GbpAccountsServiceTransport): + """gRPC AsyncIO backend transport for GbpAccountsService. + + The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + + 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_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + Awaitable[gbpaccounts.ListGbpAccountsResponse]]: + r"""Return a callable for the list gbp accounts method over gRPC. + + List the GBP accounts for a given merchant. + + Returns: + Callable[[~.ListGbpAccountsRequest], + Awaitable[~.ListGbpAccountsResponse]]: + 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_gbp_accounts' not in self._stubs: + self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/ListGbpAccounts', + request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, + response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, + ) + return self._stubs['list_gbp_accounts'] + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + Awaitable[gbpaccounts.LinkGbpAccountResponse]]: + r"""Return a callable for the link gbp account method over gRPC. + + Link the specified merchant to a GBP account for all + countries. + + Returns: + Callable[[~.LinkGbpAccountRequest], + Awaitable[~.LinkGbpAccountResponse]]: + 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 'link_gbp_account' not in self._stubs: + self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/LinkGbpAccount', + request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, + response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, + ) + return self._stubs['link_gbp_account'] + + 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_gbp_accounts: self._wrap_method( + self.list_gbp_accounts, + default_timeout=None, + client_info=client_info, + ), + self.link_gbp_account: self._wrap_method( + self.link_gbp_account, + 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__ = ( + 'GbpAccountsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py new file mode 100644 index 000000000000..3ea28bfe2c6b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py @@ -0,0 +1,535 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import gbpaccounts + + +from .rest_base import _BaseGbpAccountsServiceRestTransport +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 GbpAccountsServiceRestInterceptor: + """Interceptor for GbpAccountsService. + + 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 GbpAccountsServiceRestTransport. + + .. code-block:: python + class MyCustomGbpAccountsServiceInterceptor(GbpAccountsServiceRestInterceptor): + def pre_link_gbp_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_link_gbp_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_gbp_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_gbp_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GbpAccountsServiceRestTransport(interceptor=MyCustomGbpAccountsServiceInterceptor()) + client = GbpAccountsServiceClient(transport=transport) + + + """ + def pre_link_gbp_account(self, request: gbpaccounts.LinkGbpAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for link_gbp_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the GbpAccountsService server. + """ + return request, metadata + + def post_link_gbp_account(self, response: gbpaccounts.LinkGbpAccountResponse) -> gbpaccounts.LinkGbpAccountResponse: + """Post-rpc interceptor for link_gbp_account + + DEPRECATED. Please use the `post_link_gbp_account_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GbpAccountsService server but before + it is returned to user code. This `post_link_gbp_account` interceptor runs + before the `post_link_gbp_account_with_metadata` interceptor. + """ + return response + + def post_link_gbp_account_with_metadata(self, response: gbpaccounts.LinkGbpAccountResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for link_gbp_account + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GbpAccountsService server but before it is returned to user code. + + We recommend only using this `post_link_gbp_account_with_metadata` + interceptor in new development instead of the `post_link_gbp_account` interceptor. + When both interceptors are used, this `post_link_gbp_account_with_metadata` interceptor runs after the + `post_link_gbp_account` interceptor. The (possibly modified) response returned by + `post_link_gbp_account` will be passed to + `post_link_gbp_account_with_metadata`. + """ + return response, metadata + + def pre_list_gbp_accounts(self, request: gbpaccounts.ListGbpAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_gbp_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the GbpAccountsService server. + """ + return request, metadata + + def post_list_gbp_accounts(self, response: gbpaccounts.ListGbpAccountsResponse) -> gbpaccounts.ListGbpAccountsResponse: + """Post-rpc interceptor for list_gbp_accounts + + DEPRECATED. Please use the `post_list_gbp_accounts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GbpAccountsService server but before + it is returned to user code. This `post_list_gbp_accounts` interceptor runs + before the `post_list_gbp_accounts_with_metadata` interceptor. + """ + return response + + def post_list_gbp_accounts_with_metadata(self, response: gbpaccounts.ListGbpAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_gbp_accounts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GbpAccountsService server but before it is returned to user code. + + We recommend only using this `post_list_gbp_accounts_with_metadata` + interceptor in new development instead of the `post_list_gbp_accounts` interceptor. + When both interceptors are used, this `post_list_gbp_accounts_with_metadata` interceptor runs after the + `post_list_gbp_accounts` interceptor. The (possibly modified) response returned by + `post_list_gbp_accounts` will be passed to + `post_list_gbp_accounts_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class GbpAccountsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GbpAccountsServiceRestInterceptor + + +class GbpAccountsServiceRestTransport(_BaseGbpAccountsServiceRestTransport): + """REST backend synchronous transport for GbpAccountsService. + + The service facilitates the management of a merchant's Google + Business Profile (GBP) account settings. This API defines the + following resource model: + + - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] + + 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[GbpAccountsServiceRestInterceptor] = 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 GbpAccountsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _LinkGbpAccount(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount, GbpAccountsServiceRestStub): + def __hash__(self): + return hash("GbpAccountsServiceRestTransport.LinkGbpAccount") + + @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: gbpaccounts.LinkGbpAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gbpaccounts.LinkGbpAccountResponse: + r"""Call the link gbp account method over HTTP. + + Args: + request (~.gbpaccounts.LinkGbpAccountRequest): + The request object. Request message for the + LinkGbpAccount 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: + ~.gbpaccounts.LinkGbpAccountResponse: + Response message for the + LinkGbpAccount method. + + """ + + http_options = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_http_options() + + request, metadata = self._interceptor.pre_link_gbp_account(request, metadata) + transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_transcoded_request(http_options, request) + + body = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.GbpAccountsServiceClient.LinkGbpAccount", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "rpcName": "LinkGbpAccount", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GbpAccountsServiceRestTransport._LinkGbpAccount._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 = gbpaccounts.LinkGbpAccountResponse() + pb_resp = gbpaccounts.LinkGbpAccountResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_link_gbp_account(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_link_gbp_account_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gbpaccounts.LinkGbpAccountResponse.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.accounts_v1beta.GbpAccountsServiceClient.link_gbp_account", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "rpcName": "LinkGbpAccount", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListGbpAccounts(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts, GbpAccountsServiceRestStub): + def __hash__(self): + return hash("GbpAccountsServiceRestTransport.ListGbpAccounts") + + @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: gbpaccounts.ListGbpAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gbpaccounts.ListGbpAccountsResponse: + r"""Call the list gbp accounts method over HTTP. + + Args: + request (~.gbpaccounts.ListGbpAccountsRequest): + The request object. Request message for the + ListGbpAccounts 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: + ~.gbpaccounts.ListGbpAccountsResponse: + Response message for the + ListGbpAccounts method. + + """ + + http_options = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_http_options() + + request, metadata = self._interceptor.pre_list_gbp_accounts(request, metadata) + transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.GbpAccountsServiceClient.ListGbpAccounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "rpcName": "ListGbpAccounts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GbpAccountsServiceRestTransport._ListGbpAccounts._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 = gbpaccounts.ListGbpAccountsResponse() + pb_resp = gbpaccounts.ListGbpAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_gbp_accounts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_gbp_accounts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gbpaccounts.ListGbpAccountsResponse.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.accounts_v1beta.GbpAccountsServiceClient.list_gbp_accounts", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "rpcName": "ListGbpAccounts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def link_gbp_account(self) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + gbpaccounts.LinkGbpAccountResponse]: + # 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._LinkGbpAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_gbp_accounts(self) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + gbpaccounts.ListGbpAccountsResponse]: + # 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._ListGbpAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'GbpAccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py new file mode 100644 index 000000000000..4a9cd1330bde --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import gbpaccounts + + +class _BaseGbpAccountsServiceRestTransport(GbpAccountsServiceTransport): + """Base REST backend transport for GbpAccountsService. + + 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 _BaseLinkGbpAccount: + 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': '/accounts/v1beta/{parent=accounts/*}/gbpAccounts:linkGbpAccount', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gbpaccounts.LinkGbpAccountRequest.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(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGbpAccounts: + 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': '/accounts/v1beta/{parent=accounts/*}/gbpAccounts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gbpaccounts.ListGbpAccountsRequest.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(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseGbpAccountsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/__init__.py new file mode 100644 index 000000000000..96d41fc82ad2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_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 HomepageServiceClient +from .async_client import HomepageServiceAsyncClient + +__all__ = ( + 'HomepageServiceClient', + 'HomepageServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py new file mode 100644 index 000000000000..248ff620d044 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py @@ -0,0 +1,658 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage +from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from .client import HomepageServiceClient + +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 HomepageServiceAsyncClient: + """Service to support an API for a store's homepage.""" + + _client: HomepageServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = HomepageServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = HomepageServiceClient._DEFAULT_UNIVERSE + + homepage_path = staticmethod(HomepageServiceClient.homepage_path) + parse_homepage_path = staticmethod(HomepageServiceClient.parse_homepage_path) + common_billing_account_path = staticmethod(HomepageServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(HomepageServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(HomepageServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(HomepageServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(HomepageServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(HomepageServiceClient.parse_common_organization_path) + common_project_path = staticmethod(HomepageServiceClient.common_project_path) + parse_common_project_path = staticmethod(HomepageServiceClient.parse_common_project_path) + common_location_path = staticmethod(HomepageServiceClient.common_location_path) + parse_common_location_path = staticmethod(HomepageServiceClient.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: + HomepageServiceAsyncClient: The constructed client. + """ + return HomepageServiceClient.from_service_account_info.__func__(HomepageServiceAsyncClient, 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: + HomepageServiceAsyncClient: The constructed client. + """ + return HomepageServiceClient.from_service_account_file.__func__(HomepageServiceAsyncClient, 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 HomepageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> HomepageServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HomepageServiceTransport: 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 = HomepageServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the homepage 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,HomepageServiceTransport,Callable[..., HomepageServiceTransport]]]): + 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 HomepageServiceTransport 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 = HomepageServiceClient( + 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.accounts_v1beta.HomepageServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "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.accounts.v1beta.HomepageService", + "credentialsType": None, + } + ) + + async def get_homepage(self, + request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Retrieves a store's homepage. + + .. 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_accounts_v1beta + + async def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest, dict]]): + The request object. Request message for the ``GetHomepage`` method. + name (:class:`str`): + Required. The name of the homepage to retrieve. Format: + ``accounts/{account}/homepage`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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, homepage.GetHomepageRequest): + request = homepage.GetHomepageRequest(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.get_homepage] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_homepage(self, + request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, + *, + homepage: Optional[gsma_homepage.Homepage] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: + r"""Updates a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1beta + + async def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateHomepageRequest( + ) + + # Make the request + response = await client.update_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest, dict]]): + The request object. Request message for the ``UpdateHomepage`` method. + homepage (:class:`google.shopping.merchant_accounts_v1beta.types.Homepage`): + Required. The new version of the + homepage. + + This corresponds to the ``homepage`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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 = [homepage, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_homepage.UpdateHomepageRequest): + request = gsma_homepage.UpdateHomepageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if homepage is not None: + request.homepage = homepage + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_homepage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("homepage.name", request.homepage.name), + )), + ) + + # 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 claim_homepage(self, + request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the merchant is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. In case of failure, a + canonical error message will be returned: \* PERMISSION_DENIED: + user doesn't have the necessary permissions on this MC account; + \* FAILED_PRECONDITION: - The account is not a Merchant Center + account; - MC account doesn't have a homepage; - claiming failed + (in this case the error message will contain more details). + + .. 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_accounts_v1beta + + async def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.claim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest, dict]]): + The request object. Request message for the ``ClaimHomepage`` 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_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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, homepage.ClaimHomepageRequest): + request = homepage.ClaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.claim_homepage] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def unclaim_homepage(self, + request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Unclaims a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1beta + + async def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.unclaim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest, dict]]): + The request object. Request message for the ``UnclaimHomepage`` 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_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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, homepage.UnclaimHomepageRequest): + request = homepage.UnclaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.unclaim_homepage] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "HomepageServiceAsyncClient": + 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__ = ( + "HomepageServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py new file mode 100644 index 000000000000..17c17564ada4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py @@ -0,0 +1,1017 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage +from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import HomepageServiceGrpcTransport +from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from .transports.rest import HomepageServiceRestTransport + + +class HomepageServiceClientMeta(type): + """Metaclass for the HomepageService 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[HomepageServiceTransport]] + _transport_registry["grpc"] = HomepageServiceGrpcTransport + _transport_registry["grpc_asyncio"] = HomepageServiceGrpcAsyncIOTransport + _transport_registry["rest"] = HomepageServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[HomepageServiceTransport]: + """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 HomepageServiceClient(metaclass=HomepageServiceClientMeta): + """Service to support an API for a store's homepage.""" + + @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: + HomepageServiceClient: 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: + HomepageServiceClient: 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) -> HomepageServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HomepageServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def homepage_path(account: str,) -> str: + """Returns a fully-qualified homepage string.""" + return "accounts/{account}/homepage".format(account=account, ) + + @staticmethod + def parse_homepage_path(path: str) -> Dict[str,str]: + """Parses a homepage path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/homepage$", 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 = HomepageServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = HomepageServiceClient._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 = HomepageServiceClient._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, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the homepage 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,HomepageServiceTransport,Callable[..., HomepageServiceTransport]]]): + 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 HomepageServiceTransport 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 = HomepageServiceClient._read_environment_variables() + self._client_cert_source = HomepageServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = HomepageServiceClient._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, HomepageServiceTransport) + if transport_provided: + # transport is a HomepageServiceTransport 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(HomepageServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + HomepageServiceClient._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[HomepageServiceTransport], Callable[..., HomepageServiceTransport]] = ( + HomepageServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., HomepageServiceTransport], 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.accounts_v1beta.HomepageServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "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.accounts.v1beta.HomepageService", + "credentialsType": None, + } + ) + + def get_homepage(self, + request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Retrieves a store's homepage. + + .. 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_accounts_v1beta + + def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.get_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest, dict]): + The request object. Request message for the ``GetHomepage`` method. + name (str): + Required. The name of the homepage to retrieve. Format: + ``accounts/{account}/homepage`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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, homepage.GetHomepageRequest): + request = homepage.GetHomepageRequest(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.get_homepage] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_homepage(self, + request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, + *, + homepage: Optional[gsma_homepage.Homepage] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: + r"""Updates a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1beta + + def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateHomepageRequest( + ) + + # Make the request + response = client.update_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest, dict]): + The request object. Request message for the ``UpdateHomepage`` method. + homepage (google.shopping.merchant_accounts_v1beta.types.Homepage): + Required. The new version of the + homepage. + + This corresponds to the ``homepage`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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 = [homepage, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_homepage.UpdateHomepageRequest): + request = gsma_homepage.UpdateHomepageRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if homepage is not None: + request.homepage = homepage + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_homepage] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("homepage.name", request.homepage.name), + )), + ) + + # 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 claim_homepage(self, + request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the merchant is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. In case of failure, a + canonical error message will be returned: \* PERMISSION_DENIED: + user doesn't have the necessary permissions on this MC account; + \* FAILED_PRECONDITION: - The account is not a Merchant Center + account; - MC account doesn't have a homepage; - claiming failed + (in this case the error message will contain more details). + + .. 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_accounts_v1beta + + def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.claim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest, dict]): + The request object. Request message for the ``ClaimHomepage`` 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_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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, homepage.ClaimHomepageRequest): + request = homepage.ClaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.claim_homepage] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def unclaim_homepage(self, + request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: + r"""Unclaims a store's homepage. Executing this method + requires admin access. + + .. 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_accounts_v1beta + + def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.unclaim_homepage(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest, dict]): + The request object. Request message for the ``UnclaimHomepage`` 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_accounts_v1beta.types.Homepage: + A store's homepage. + """ + # 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, homepage.UnclaimHomepageRequest): + request = homepage.UnclaimHomepageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.unclaim_homepage] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "HomepageServiceClient": + 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__ = ( + "HomepageServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst new file mode 100644 index 000000000000..8c0def729b79 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`HomepageServiceTransport` is the ABC for all transports. +- public child `HomepageServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `HomepageServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseHomepageServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `HomepageServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/__init__.py new file mode 100644 index 000000000000..e935fb45c364 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_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 HomepageServiceTransport +from .grpc import HomepageServiceGrpcTransport +from .grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from .rest import HomepageServiceRestTransport +from .rest import HomepageServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[HomepageServiceTransport]] +_transport_registry['grpc'] = HomepageServiceGrpcTransport +_transport_registry['grpc_asyncio'] = HomepageServiceGrpcAsyncIOTransport +_transport_registry['rest'] = HomepageServiceRestTransport + +__all__ = ( + 'HomepageServiceTransport', + 'HomepageServiceGrpcTransport', + 'HomepageServiceGrpcAsyncIOTransport', + 'HomepageServiceRestTransport', + 'HomepageServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py new file mode 100644 index 000000000000..974ef00c8ba6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py @@ -0,0 +1,202 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage + +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 HomepageServiceTransport(abc.ABC): + """Abstract transport class for HomepageService.""" + + 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.get_homepage: gapic_v1.method.wrap_method( + self.get_homepage, + default_timeout=None, + client_info=client_info, + ), + self.update_homepage: gapic_v1.method.wrap_method( + self.update_homepage, + default_timeout=None, + client_info=client_info, + ), + self.claim_homepage: gapic_v1.method.wrap_method( + self.claim_homepage, + default_timeout=None, + client_info=client_info, + ), + self.unclaim_homepage: gapic_v1.method.wrap_method( + self.unclaim_homepage, + 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 get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + Union[ + homepage.Homepage, + Awaitable[homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + Union[ + gsma_homepage.Homepage, + Awaitable[gsma_homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + Union[ + homepage.Homepage, + Awaitable[homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + Union[ + homepage.Homepage, + Awaitable[homepage.Homepage] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'HomepageServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py new file mode 100644 index 000000000000..22d2ae117431 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py @@ -0,0 +1,439 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage +from .base import HomepageServiceTransport, 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.accounts.v1beta.HomepageService", + "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.accounts.v1beta.HomepageService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HomepageServiceGrpcTransport(HomepageServiceTransport): + """gRPC backend transport for HomepageService. + + Service to support an API for a store's homepage. + + 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 get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + homepage.Homepage]: + r"""Return a callable for the get homepage method over gRPC. + + Retrieves a store's homepage. + + Returns: + Callable[[~.GetHomepageRequest], + ~.Homepage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_homepage' not in self._stubs: + self._stubs['get_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/GetHomepage', + request_serializer=homepage.GetHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['get_homepage'] + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + gsma_homepage.Homepage]: + r"""Return a callable for the update homepage method over gRPC. + + Updates a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UpdateHomepageRequest], + ~.Homepage]: + 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 'update_homepage' not in self._stubs: + self._stubs['update_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/UpdateHomepage', + request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, + response_deserializer=gsma_homepage.Homepage.deserialize, + ) + return self._stubs['update_homepage'] + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + homepage.Homepage]: + r"""Return a callable for the claim homepage method over gRPC. + + Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the merchant is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. In case of failure, a + canonical error message will be returned: \* PERMISSION_DENIED: + user doesn't have the necessary permissions on this MC account; + \* FAILED_PRECONDITION: - The account is not a Merchant Center + account; - MC account doesn't have a homepage; - claiming failed + (in this case the error message will contain more details). + + Returns: + Callable[[~.ClaimHomepageRequest], + ~.Homepage]: + 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 'claim_homepage' not in self._stubs: + self._stubs['claim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/ClaimHomepage', + request_serializer=homepage.ClaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['claim_homepage'] + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + homepage.Homepage]: + r"""Return a callable for the unclaim homepage method over gRPC. + + Unclaims a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UnclaimHomepageRequest], + ~.Homepage]: + 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 'unclaim_homepage' not in self._stubs: + self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/UnclaimHomepage', + request_serializer=homepage.UnclaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['unclaim_homepage'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'HomepageServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..d942602731e8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py @@ -0,0 +1,475 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage +from .base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import HomepageServiceGrpcTransport + +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.accounts.v1beta.HomepageService", + "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.accounts.v1beta.HomepageService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HomepageServiceGrpcAsyncIOTransport(HomepageServiceTransport): + """gRPC AsyncIO backend transport for HomepageService. + + Service to support an API for a store's homepage. + + 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 get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + Awaitable[homepage.Homepage]]: + r"""Return a callable for the get homepage method over gRPC. + + Retrieves a store's homepage. + + Returns: + Callable[[~.GetHomepageRequest], + Awaitable[~.Homepage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_homepage' not in self._stubs: + self._stubs['get_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/GetHomepage', + request_serializer=homepage.GetHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['get_homepage'] + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + Awaitable[gsma_homepage.Homepage]]: + r"""Return a callable for the update homepage method over gRPC. + + Updates a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UpdateHomepageRequest], + Awaitable[~.Homepage]]: + 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 'update_homepage' not in self._stubs: + self._stubs['update_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/UpdateHomepage', + request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, + response_deserializer=gsma_homepage.Homepage.deserialize, + ) + return self._stubs['update_homepage'] + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + Awaitable[homepage.Homepage]]: + r"""Return a callable for the claim homepage method over gRPC. + + Claims a store's homepage. Executing this method requires admin + access. + + If the homepage is already claimed, this will recheck the + verification (unless the merchant is exempted from claiming, + which also exempts from verification) and return a successful + response. If ownership can no longer be verified, it will return + an error, but it won't clear the claim. In case of failure, a + canonical error message will be returned: \* PERMISSION_DENIED: + user doesn't have the necessary permissions on this MC account; + \* FAILED_PRECONDITION: - The account is not a Merchant Center + account; - MC account doesn't have a homepage; - claiming failed + (in this case the error message will contain more details). + + Returns: + Callable[[~.ClaimHomepageRequest], + Awaitable[~.Homepage]]: + 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 'claim_homepage' not in self._stubs: + self._stubs['claim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/ClaimHomepage', + request_serializer=homepage.ClaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['claim_homepage'] + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + Awaitable[homepage.Homepage]]: + r"""Return a callable for the unclaim homepage method over gRPC. + + Unclaims a store's homepage. Executing this method + requires admin access. + + Returns: + Callable[[~.UnclaimHomepageRequest], + Awaitable[~.Homepage]]: + 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 'unclaim_homepage' not in self._stubs: + self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.HomepageService/UnclaimHomepage', + request_serializer=homepage.UnclaimHomepageRequest.serialize, + response_deserializer=homepage.Homepage.deserialize, + ) + return self._stubs['unclaim_homepage'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_homepage: self._wrap_method( + self.get_homepage, + default_timeout=None, + client_info=client_info, + ), + self.update_homepage: self._wrap_method( + self.update_homepage, + default_timeout=None, + client_info=client_info, + ), + self.claim_homepage: self._wrap_method( + self.claim_homepage, + default_timeout=None, + client_info=client_info, + ), + self.unclaim_homepage: self._wrap_method( + self.unclaim_homepage, + 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__ = ( + 'HomepageServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py new file mode 100644 index 000000000000..9b11be9cd643 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py @@ -0,0 +1,874 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage + + +from .rest_base import _BaseHomepageServiceRestTransport +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 HomepageServiceRestInterceptor: + """Interceptor for HomepageService. + + 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 HomepageServiceRestTransport. + + .. code-block:: python + class MyCustomHomepageServiceInterceptor(HomepageServiceRestInterceptor): + def pre_claim_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_claim_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_unclaim_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_unclaim_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_homepage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_homepage(self, response): + logging.log(f"Received response: {response}") + return response + + transport = HomepageServiceRestTransport(interceptor=MyCustomHomepageServiceInterceptor()) + client = HomepageServiceClient(transport=transport) + + + """ + def pre_claim_homepage(self, request: homepage.ClaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for claim_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_claim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: + """Post-rpc interceptor for claim_homepage + + DEPRECATED. Please use the `post_claim_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_claim_homepage` interceptor runs + before the `post_claim_homepage_with_metadata` interceptor. + """ + return response + + def post_claim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for claim_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_claim_homepage_with_metadata` + interceptor in new development instead of the `post_claim_homepage` interceptor. + When both interceptors are used, this `post_claim_homepage_with_metadata` interceptor runs after the + `post_claim_homepage` interceptor. The (possibly modified) response returned by + `post_claim_homepage` will be passed to + `post_claim_homepage_with_metadata`. + """ + return response, metadata + + def pre_get_homepage(self, request: homepage.GetHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_get_homepage(self, response: homepage.Homepage) -> homepage.Homepage: + """Post-rpc interceptor for get_homepage + + DEPRECATED. Please use the `post_get_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_get_homepage` interceptor runs + before the `post_get_homepage_with_metadata` interceptor. + """ + return response + + def post_get_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_get_homepage_with_metadata` + interceptor in new development instead of the `post_get_homepage` interceptor. + When both interceptors are used, this `post_get_homepage_with_metadata` interceptor runs after the + `post_get_homepage` interceptor. The (possibly modified) response returned by + `post_get_homepage` will be passed to + `post_get_homepage_with_metadata`. + """ + return response, metadata + + def pre_unclaim_homepage(self, request: homepage.UnclaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for unclaim_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_unclaim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: + """Post-rpc interceptor for unclaim_homepage + + DEPRECATED. Please use the `post_unclaim_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_unclaim_homepage` interceptor runs + before the `post_unclaim_homepage_with_metadata` interceptor. + """ + return response + + def post_unclaim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for unclaim_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_unclaim_homepage_with_metadata` + interceptor in new development instead of the `post_unclaim_homepage` interceptor. + When both interceptors are used, this `post_unclaim_homepage_with_metadata` interceptor runs after the + `post_unclaim_homepage` interceptor. The (possibly modified) response returned by + `post_unclaim_homepage` will be passed to + `post_unclaim_homepage_with_metadata`. + """ + return response, metadata + + def pre_update_homepage(self, request: gsma_homepage.UpdateHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_homepage + + Override in a subclass to manipulate the request or metadata + before they are sent to the HomepageService server. + """ + return request, metadata + + def post_update_homepage(self, response: gsma_homepage.Homepage) -> gsma_homepage.Homepage: + """Post-rpc interceptor for update_homepage + + DEPRECATED. Please use the `post_update_homepage_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HomepageService server but before + it is returned to user code. This `post_update_homepage` interceptor runs + before the `post_update_homepage_with_metadata` interceptor. + """ + return response + + def post_update_homepage_with_metadata(self, response: gsma_homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_homepage + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HomepageService server but before it is returned to user code. + + We recommend only using this `post_update_homepage_with_metadata` + interceptor in new development instead of the `post_update_homepage` interceptor. + When both interceptors are used, this `post_update_homepage_with_metadata` interceptor runs after the + `post_update_homepage` interceptor. The (possibly modified) response returned by + `post_update_homepage` will be passed to + `post_update_homepage_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class HomepageServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: HomepageServiceRestInterceptor + + +class HomepageServiceRestTransport(_BaseHomepageServiceRestTransport): + """REST backend synchronous transport for HomepageService. + + Service to support an API for a store's homepage. + + 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[HomepageServiceRestInterceptor] = 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 HomepageServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ClaimHomepage(_BaseHomepageServiceRestTransport._BaseClaimHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.ClaimHomepage") + + @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: homepage.ClaimHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> homepage.Homepage: + r"""Call the claim homepage method over HTTP. + + Args: + request (~.homepage.ClaimHomepageRequest): + The request object. Request message for the ``ClaimHomepage`` 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: + ~.homepage.Homepage: + A store's homepage. + """ + + http_options = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_http_options() + + request, metadata = self._interceptor.pre_claim_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_transcoded_request(http_options, request) + + body = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.ClaimHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "ClaimHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._ClaimHomepage._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 = homepage.Homepage() + pb_resp = homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_claim_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_claim_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.claim_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "ClaimHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetHomepage(_BaseHomepageServiceRestTransport._BaseGetHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.GetHomepage") + + @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: homepage.GetHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> homepage.Homepage: + r"""Call the get homepage method over HTTP. + + Args: + request (~.homepage.GetHomepageRequest): + The request object. Request message for the ``GetHomepage`` 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: + ~.homepage.Homepage: + A store's homepage. + """ + + http_options = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_http_options() + + request, metadata = self._interceptor.pre_get_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.GetHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "GetHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._GetHomepage._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 = homepage.Homepage() + pb_resp = homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.get_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "GetHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UnclaimHomepage(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.UnclaimHomepage") + + @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: homepage.UnclaimHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> homepage.Homepage: + r"""Call the unclaim homepage method over HTTP. + + Args: + request (~.homepage.UnclaimHomepageRequest): + The request object. Request message for the ``UnclaimHomepage`` 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: + ~.homepage.Homepage: + A store's homepage. + """ + + http_options = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_http_options() + + request, metadata = self._interceptor.pre_unclaim_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_transcoded_request(http_options, request) + + body = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.UnclaimHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "UnclaimHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._UnclaimHomepage._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 = homepage.Homepage() + pb_resp = homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_unclaim_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_unclaim_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.unclaim_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "UnclaimHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateHomepage(_BaseHomepageServiceRestTransport._BaseUpdateHomepage, HomepageServiceRestStub): + def __hash__(self): + return hash("HomepageServiceRestTransport.UpdateHomepage") + + @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: gsma_homepage.UpdateHomepageRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_homepage.Homepage: + r"""Call the update homepage method over HTTP. + + Args: + request (~.gsma_homepage.UpdateHomepageRequest): + The request object. Request message for the ``UpdateHomepage`` 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: + ~.gsma_homepage.Homepage: + A store's homepage. + """ + + http_options = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_http_options() + + request, metadata = self._interceptor.pre_update_homepage(request, metadata) + transcoded_request = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_transcoded_request(http_options, request) + + body = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.UpdateHomepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "UpdateHomepage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HomepageServiceRestTransport._UpdateHomepage._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 = gsma_homepage.Homepage() + pb_resp = gsma_homepage.Homepage.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_homepage(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_homepage_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.update_homepage", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "rpcName": "UpdateHomepage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def claim_homepage(self) -> Callable[ + [homepage.ClaimHomepageRequest], + homepage.Homepage]: + # 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._ClaimHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_homepage(self) -> Callable[ + [homepage.GetHomepageRequest], + homepage.Homepage]: + # 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._GetHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def unclaim_homepage(self) -> Callable[ + [homepage.UnclaimHomepageRequest], + homepage.Homepage]: + # 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._UnclaimHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_homepage(self) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + gsma_homepage.Homepage]: + # 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._UpdateHomepage(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'HomepageServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py new file mode 100644 index 000000000000..b9664f2922e0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py @@ -0,0 +1,270 @@ +# -*- 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 HomepageServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage + + +class _BaseHomepageServiceRestTransport(HomepageServiceTransport): + """Base REST backend transport for HomepageService. + + 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 _BaseClaimHomepage: + 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': '/accounts/v1beta/{name=accounts/*/homepage}:claim', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = homepage.ClaimHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseClaimHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetHomepage: + 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': '/accounts/v1beta/{name=accounts/*/homepage}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = homepage.GetHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseGetHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUnclaimHomepage: + 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': '/accounts/v1beta/{name=accounts/*/homepage}:unclaim', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = homepage.UnclaimHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateHomepage: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{homepage.name=accounts/*/homepage}', + 'body': 'homepage', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_homepage.UpdateHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseHomepageServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/__init__.py new file mode 100644 index 000000000000..bdfa6c11d195 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_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 LfpProvidersServiceClient +from .async_client import LfpProvidersServiceAsyncClient + +__all__ = ( + 'LfpProvidersServiceClient', + 'LfpProvidersServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py new file mode 100644 index 000000000000..568e636b870f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py @@ -0,0 +1,503 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import pagers +from google.shopping.merchant_accounts_v1beta.types import lfpproviders +from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport +from .client import LfpProvidersServiceClient + +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 LfpProvidersServiceAsyncClient: + """The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + """ + + _client: LfpProvidersServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = LfpProvidersServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = LfpProvidersServiceClient._DEFAULT_UNIVERSE + + lfp_provider_path = staticmethod(LfpProvidersServiceClient.lfp_provider_path) + parse_lfp_provider_path = staticmethod(LfpProvidersServiceClient.parse_lfp_provider_path) + omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.omnichannel_setting_path) + parse_omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.parse_omnichannel_setting_path) + common_billing_account_path = staticmethod(LfpProvidersServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(LfpProvidersServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(LfpProvidersServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(LfpProvidersServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(LfpProvidersServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(LfpProvidersServiceClient.parse_common_organization_path) + common_project_path = staticmethod(LfpProvidersServiceClient.common_project_path) + parse_common_project_path = staticmethod(LfpProvidersServiceClient.parse_common_project_path) + common_location_path = staticmethod(LfpProvidersServiceClient.common_location_path) + parse_common_location_path = staticmethod(LfpProvidersServiceClient.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: + LfpProvidersServiceAsyncClient: The constructed client. + """ + return LfpProvidersServiceClient.from_service_account_info.__func__(LfpProvidersServiceAsyncClient, 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: + LfpProvidersServiceAsyncClient: The constructed client. + """ + return LfpProvidersServiceClient.from_service_account_file.__func__(LfpProvidersServiceAsyncClient, 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 LfpProvidersServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> LfpProvidersServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpProvidersServiceTransport: 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 = LfpProvidersServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp providers 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,LfpProvidersServiceTransport,Callable[..., LfpProvidersServiceTransport]]]): + 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 LfpProvidersServiceTransport 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 = LfpProvidersServiceClient( + 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.accounts_v1beta.LfpProvidersServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "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.accounts.v1beta.LfpProvidersService", + "credentialsType": None, + } + ) + + async def find_lfp_providers(self, + request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersAsyncPager: + r"""Find the LFP provider candidates in a given country. + + .. 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_accounts_v1beta + + async def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest, dict]]): + The request object. Request message for the + FindLfpProviders method. + parent (:class:`str`): + Required. The name of the parent resource under which + the LFP providers are found. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. + + 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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersAsyncPager: + Response message for the + FindLfpProviders 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, lfpproviders.FindLfpProvidersRequest): + request = lfpproviders.FindLfpProvidersRequest(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.find_lfp_providers] + + # 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.FindLfpProvidersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def link_lfp_provider(self, + request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: + r"""Link the specified merchant to a LFP provider for the + specified country. + + .. 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_accounts_v1beta + + async def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = await client.link_lfp_provider(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest, dict]]): + The request object. Request message for the + LinkLfpProvider method. + name (:class:`str`): + Required. The name of the LFP provider resource to link. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. + The ``lfp_provider`` is the LFP provider ID. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse: + Response message for the + LinkLfpProvider method. + + """ + # 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, lfpproviders.LinkLfpProviderRequest): + request = lfpproviders.LinkLfpProviderRequest(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.link_lfp_provider] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "LfpProvidersServiceAsyncClient": + 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__ = ( + "LfpProvidersServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py new file mode 100644 index 000000000000..28f3b739a88e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py @@ -0,0 +1,871 @@ +# -*- 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_accounts_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.protobuf import empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import pagers +from google.shopping.merchant_accounts_v1beta.types import lfpproviders +from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LfpProvidersServiceGrpcTransport +from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport +from .transports.rest import LfpProvidersServiceRestTransport + + +class LfpProvidersServiceClientMeta(type): + """Metaclass for the LfpProvidersService 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[LfpProvidersServiceTransport]] + _transport_registry["grpc"] = LfpProvidersServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LfpProvidersServiceGrpcAsyncIOTransport + _transport_registry["rest"] = LfpProvidersServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[LfpProvidersServiceTransport]: + """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 LfpProvidersServiceClient(metaclass=LfpProvidersServiceClientMeta): + """The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + """ + + @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: + LfpProvidersServiceClient: 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: + LfpProvidersServiceClient: 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) -> LfpProvidersServiceTransport: + """Returns the transport used by the client instance. + + Returns: + LfpProvidersServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def lfp_provider_path(account: str,omnichannel_setting: str,lfp_provider: str,) -> str: + """Returns a fully-qualified lfp_provider string.""" + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) + + @staticmethod + def parse_lfp_provider_path(path: str) -> Dict[str,str]: + """Parses a lfp_provider path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)/lfpProviders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: + """Returns a fully-qualified omnichannel_setting string.""" + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + + @staticmethod + def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: + """Parses a omnichannel_setting path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?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 = LfpProvidersServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = LfpProvidersServiceClient._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 = LfpProvidersServiceClient._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, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the lfp providers 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,LfpProvidersServiceTransport,Callable[..., LfpProvidersServiceTransport]]]): + 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 LfpProvidersServiceTransport 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 = LfpProvidersServiceClient._read_environment_variables() + self._client_cert_source = LfpProvidersServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = LfpProvidersServiceClient._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, LfpProvidersServiceTransport) + if transport_provided: + # transport is a LfpProvidersServiceTransport 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(LfpProvidersServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + LfpProvidersServiceClient._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[LfpProvidersServiceTransport], Callable[..., LfpProvidersServiceTransport]] = ( + LfpProvidersServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., LfpProvidersServiceTransport], 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.accounts_v1beta.LfpProvidersServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "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.accounts.v1beta.LfpProvidersService", + "credentialsType": None, + } + ) + + def find_lfp_providers(self, + request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersPager: + r"""Find the LFP provider candidates in a given country. + + .. 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_accounts_v1beta + + def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest, dict]): + The request object. Request message for the + FindLfpProviders method. + parent (str): + Required. The name of the parent resource under which + the LFP providers are found. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. + + 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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersPager: + Response message for the + FindLfpProviders 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, lfpproviders.FindLfpProvidersRequest): + request = lfpproviders.FindLfpProvidersRequest(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.find_lfp_providers] + + # 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.FindLfpProvidersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def link_lfp_provider(self, + request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: + r"""Link the specified merchant to a LFP provider for the + specified country. + + .. 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_accounts_v1beta + + def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = client.link_lfp_provider(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest, dict]): + The request object. Request message for the + LinkLfpProvider method. + name (str): + Required. The name of the LFP provider resource to link. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. + The ``lfp_provider`` is the LFP provider ID. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse: + Response message for the + LinkLfpProvider method. + + """ + # 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, lfpproviders.LinkLfpProviderRequest): + request = lfpproviders.LinkLfpProviderRequest(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.link_lfp_provider] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "LfpProvidersServiceClient": + 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__ = ( + "LfpProvidersServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/pagers.py new file mode 100644 index 000000000000..805c4d815ee2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_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_accounts_v1beta.types import lfpproviders + + +class FindLfpProvidersPager: + """A pager for iterating through ``find_lfp_providers`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``lfp_providers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FindLfpProviders`` requests and continue to iterate + through the ``lfp_providers`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` + 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[..., lfpproviders.FindLfpProvidersResponse], + request: lfpproviders.FindLfpProvidersRequest, + response: lfpproviders.FindLfpProvidersResponse, + *, + 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_accounts_v1beta.types.FindLfpProvidersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse): + 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 = lfpproviders.FindLfpProvidersRequest(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[lfpproviders.FindLfpProvidersResponse]: + 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[lfpproviders.LfpProvider]: + for page in self.pages: + yield from page.lfp_providers + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class FindLfpProvidersAsyncPager: + """A pager for iterating through ``find_lfp_providers`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``lfp_providers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FindLfpProviders`` requests and continue to iterate + through the ``lfp_providers`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` + 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[lfpproviders.FindLfpProvidersResponse]], + request: lfpproviders.FindLfpProvidersRequest, + response: lfpproviders.FindLfpProvidersResponse, + *, + 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_accounts_v1beta.types.FindLfpProvidersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse): + 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 = lfpproviders.FindLfpProvidersRequest(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[lfpproviders.FindLfpProvidersResponse]: + 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[lfpproviders.LfpProvider]: + async def async_generator(): + async for page in self.pages: + for response in page.lfp_providers: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst new file mode 100644 index 000000000000..9ef07da24bc0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`LfpProvidersServiceTransport` is the ABC for all transports. +- public child `LfpProvidersServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `LfpProvidersServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseLfpProvidersServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `LfpProvidersServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/__init__.py new file mode 100644 index 000000000000..f6510b1f8477 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_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 LfpProvidersServiceTransport +from .grpc import LfpProvidersServiceGrpcTransport +from .grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport +from .rest import LfpProvidersServiceRestTransport +from .rest import LfpProvidersServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LfpProvidersServiceTransport]] +_transport_registry['grpc'] = LfpProvidersServiceGrpcTransport +_transport_registry['grpc_asyncio'] = LfpProvidersServiceGrpcAsyncIOTransport +_transport_registry['rest'] = LfpProvidersServiceRestTransport + +__all__ = ( + 'LfpProvidersServiceTransport', + 'LfpProvidersServiceGrpcTransport', + 'LfpProvidersServiceGrpcAsyncIOTransport', + 'LfpProvidersServiceRestTransport', + 'LfpProvidersServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py new file mode 100644 index 000000000000..4ef183de0240 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import lfpproviders + +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 LfpProvidersServiceTransport(abc.ABC): + """Abstract transport class for LfpProvidersService.""" + + 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.find_lfp_providers: gapic_v1.method.wrap_method( + self.find_lfp_providers, + default_timeout=None, + client_info=client_info, + ), + self.link_lfp_provider: gapic_v1.method.wrap_method( + self.link_lfp_provider, + 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 find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + Union[ + lfpproviders.FindLfpProvidersResponse, + Awaitable[lfpproviders.FindLfpProvidersResponse] + ]]: + raise NotImplementedError() + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + Union[ + lfpproviders.LinkLfpProviderResponse, + Awaitable[lfpproviders.LinkLfpProviderResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'LfpProvidersServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py new file mode 100644 index 000000000000..3b895a104779 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py @@ -0,0 +1,376 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import lfpproviders +from .base import LfpProvidersServiceTransport, 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.accounts.v1beta.LfpProvidersService", + "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.accounts.v1beta.LfpProvidersService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpProvidersServiceGrpcTransport(LfpProvidersServiceTransport): + """gRPC backend transport for LfpProvidersService. + + The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + + 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 find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + lfpproviders.FindLfpProvidersResponse]: + r"""Return a callable for the find lfp providers method over gRPC. + + Find the LFP provider candidates in a given country. + + Returns: + Callable[[~.FindLfpProvidersRequest], + ~.FindLfpProvidersResponse]: + 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 'find_lfp_providers' not in self._stubs: + self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/FindLfpProviders', + request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, + response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, + ) + return self._stubs['find_lfp_providers'] + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + lfpproviders.LinkLfpProviderResponse]: + r"""Return a callable for the link lfp provider method over gRPC. + + Link the specified merchant to a LFP provider for the + specified country. + + Returns: + Callable[[~.LinkLfpProviderRequest], + ~.LinkLfpProviderResponse]: + 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 'link_lfp_provider' not in self._stubs: + self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/LinkLfpProvider', + request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, + response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, + ) + return self._stubs['link_lfp_provider'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'LfpProvidersServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..74eacd7b3931 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py @@ -0,0 +1,402 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import lfpproviders +from .base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LfpProvidersServiceGrpcTransport + +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.accounts.v1beta.LfpProvidersService", + "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.accounts.v1beta.LfpProvidersService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class LfpProvidersServiceGrpcAsyncIOTransport(LfpProvidersServiceTransport): + """gRPC AsyncIO backend transport for LfpProvidersService. + + The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + + 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 find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + Awaitable[lfpproviders.FindLfpProvidersResponse]]: + r"""Return a callable for the find lfp providers method over gRPC. + + Find the LFP provider candidates in a given country. + + Returns: + Callable[[~.FindLfpProvidersRequest], + Awaitable[~.FindLfpProvidersResponse]]: + 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 'find_lfp_providers' not in self._stubs: + self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/FindLfpProviders', + request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, + response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, + ) + return self._stubs['find_lfp_providers'] + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + Awaitable[lfpproviders.LinkLfpProviderResponse]]: + r"""Return a callable for the link lfp provider method over gRPC. + + Link the specified merchant to a LFP provider for the + specified country. + + Returns: + Callable[[~.LinkLfpProviderRequest], + Awaitable[~.LinkLfpProviderResponse]]: + 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 'link_lfp_provider' not in self._stubs: + self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/LinkLfpProvider', + request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, + response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, + ) + return self._stubs['link_lfp_provider'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.find_lfp_providers: self._wrap_method( + self.find_lfp_providers, + default_timeout=None, + client_info=client_info, + ), + self.link_lfp_provider: self._wrap_method( + self.link_lfp_provider, + 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__ = ( + 'LfpProvidersServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py new file mode 100644 index 000000000000..7657118ca9e6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py @@ -0,0 +1,534 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import lfpproviders + + +from .rest_base import _BaseLfpProvidersServiceRestTransport +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 LfpProvidersServiceRestInterceptor: + """Interceptor for LfpProvidersService. + + 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 LfpProvidersServiceRestTransport. + + .. code-block:: python + class MyCustomLfpProvidersServiceInterceptor(LfpProvidersServiceRestInterceptor): + def pre_find_lfp_providers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_find_lfp_providers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_link_lfp_provider(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_link_lfp_provider(self, response): + logging.log(f"Received response: {response}") + return response + + transport = LfpProvidersServiceRestTransport(interceptor=MyCustomLfpProvidersServiceInterceptor()) + client = LfpProvidersServiceClient(transport=transport) + + + """ + def pre_find_lfp_providers(self, request: lfpproviders.FindLfpProvidersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for find_lfp_providers + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpProvidersService server. + """ + return request, metadata + + def post_find_lfp_providers(self, response: lfpproviders.FindLfpProvidersResponse) -> lfpproviders.FindLfpProvidersResponse: + """Post-rpc interceptor for find_lfp_providers + + DEPRECATED. Please use the `post_find_lfp_providers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LfpProvidersService server but before + it is returned to user code. This `post_find_lfp_providers` interceptor runs + before the `post_find_lfp_providers_with_metadata` interceptor. + """ + return response + + def post_find_lfp_providers_with_metadata(self, response: lfpproviders.FindLfpProvidersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for find_lfp_providers + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LfpProvidersService server but before it is returned to user code. + + We recommend only using this `post_find_lfp_providers_with_metadata` + interceptor in new development instead of the `post_find_lfp_providers` interceptor. + When both interceptors are used, this `post_find_lfp_providers_with_metadata` interceptor runs after the + `post_find_lfp_providers` interceptor. The (possibly modified) response returned by + `post_find_lfp_providers` will be passed to + `post_find_lfp_providers_with_metadata`. + """ + return response, metadata + + def pre_link_lfp_provider(self, request: lfpproviders.LinkLfpProviderRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for link_lfp_provider + + Override in a subclass to manipulate the request or metadata + before they are sent to the LfpProvidersService server. + """ + return request, metadata + + def post_link_lfp_provider(self, response: lfpproviders.LinkLfpProviderResponse) -> lfpproviders.LinkLfpProviderResponse: + """Post-rpc interceptor for link_lfp_provider + + DEPRECATED. Please use the `post_link_lfp_provider_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the LfpProvidersService server but before + it is returned to user code. This `post_link_lfp_provider` interceptor runs + before the `post_link_lfp_provider_with_metadata` interceptor. + """ + return response + + def post_link_lfp_provider_with_metadata(self, response: lfpproviders.LinkLfpProviderResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for link_lfp_provider + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the LfpProvidersService server but before it is returned to user code. + + We recommend only using this `post_link_lfp_provider_with_metadata` + interceptor in new development instead of the `post_link_lfp_provider` interceptor. + When both interceptors are used, this `post_link_lfp_provider_with_metadata` interceptor runs after the + `post_link_lfp_provider` interceptor. The (possibly modified) response returned by + `post_link_lfp_provider` will be passed to + `post_link_lfp_provider_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class LfpProvidersServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: LfpProvidersServiceRestInterceptor + + +class LfpProvidersServiceRestTransport(_BaseLfpProvidersServiceRestTransport): + """REST backend synchronous transport for LfpProvidersService. + + The service facilitates the management of a merchant's LFP provider + settings. This API defines the following resource model: + + - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] + + 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[LfpProvidersServiceRestInterceptor] = 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 LfpProvidersServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _FindLfpProviders(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders, LfpProvidersServiceRestStub): + def __hash__(self): + return hash("LfpProvidersServiceRestTransport.FindLfpProviders") + + @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: lfpproviders.FindLfpProvidersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpproviders.FindLfpProvidersResponse: + r"""Call the find lfp providers method over HTTP. + + Args: + request (~.lfpproviders.FindLfpProvidersRequest): + The request object. Request message for the + FindLfpProviders 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: + ~.lfpproviders.FindLfpProvidersResponse: + Response message for the + FindLfpProviders method. + + """ + + http_options = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_http_options() + + request, metadata = self._interceptor.pre_find_lfp_providers(request, metadata) + transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.LfpProvidersServiceClient.FindLfpProviders", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "rpcName": "FindLfpProviders", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpProvidersServiceRestTransport._FindLfpProviders._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 = lfpproviders.FindLfpProvidersResponse() + pb_resp = lfpproviders.FindLfpProvidersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_find_lfp_providers(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_find_lfp_providers_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpproviders.FindLfpProvidersResponse.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.accounts_v1beta.LfpProvidersServiceClient.find_lfp_providers", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "rpcName": "FindLfpProviders", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _LinkLfpProvider(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider, LfpProvidersServiceRestStub): + def __hash__(self): + return hash("LfpProvidersServiceRestTransport.LinkLfpProvider") + + @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: lfpproviders.LinkLfpProviderRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> lfpproviders.LinkLfpProviderResponse: + r"""Call the link lfp provider method over HTTP. + + Args: + request (~.lfpproviders.LinkLfpProviderRequest): + The request object. Request message for the + LinkLfpProvider 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: + ~.lfpproviders.LinkLfpProviderResponse: + Response message for the + LinkLfpProvider method. + + """ + + http_options = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_http_options() + + request, metadata = self._interceptor.pre_link_lfp_provider(request, metadata) + transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_transcoded_request(http_options, request) + + body = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.LfpProvidersServiceClient.LinkLfpProvider", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "rpcName": "LinkLfpProvider", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = LfpProvidersServiceRestTransport._LinkLfpProvider._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 = lfpproviders.LinkLfpProviderResponse() + pb_resp = lfpproviders.LinkLfpProviderResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_link_lfp_provider(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_link_lfp_provider_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = lfpproviders.LinkLfpProviderResponse.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.accounts_v1beta.LfpProvidersServiceClient.link_lfp_provider", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "rpcName": "LinkLfpProvider", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def find_lfp_providers(self) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + lfpproviders.FindLfpProvidersResponse]: + # 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._FindLfpProviders(self._session, self._host, self._interceptor) # type: ignore + + @property + def link_lfp_provider(self) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + lfpproviders.LinkLfpProviderResponse]: + # 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._LinkLfpProvider(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'LfpProvidersServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py new file mode 100644 index 000000000000..eecd7728d991 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import lfpproviders + + +class _BaseLfpProvidersServiceRestTransport(LfpProvidersServiceTransport): + """Base REST backend transport for LfpProvidersService. + + 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 _BaseFindLfpProviders: + 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': '/accounts/v1beta/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpproviders.FindLfpProvidersRequest.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(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseLinkLfpProvider: + 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': '/accounts/v1beta/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = lfpproviders.LinkLfpProviderRequest.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(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseLfpProvidersServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/__init__.py new file mode 100644 index 000000000000..242598846a6e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_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 OmnichannelSettingsServiceClient +from .async_client import OmnichannelSettingsServiceAsyncClient + +__all__ = ( + 'OmnichannelSettingsServiceClient', + 'OmnichannelSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py new file mode 100644 index 000000000000..7c890b9abcf5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py @@ -0,0 +1,866 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import pagers +from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings +from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport +from .client import OmnichannelSettingsServiceClient + +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 OmnichannelSettingsServiceAsyncClient: + """The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + """ + + _client: OmnichannelSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(OmnichannelSettingsServiceClient.account_path) + parse_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_account_path) + omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.omnichannel_setting_path) + parse_omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.parse_omnichannel_setting_path) + common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OmnichannelSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OmnichannelSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OmnichannelSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(OmnichannelSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(OmnichannelSettingsServiceClient.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: + OmnichannelSettingsServiceAsyncClient: The constructed client. + """ + return OmnichannelSettingsServiceClient.from_service_account_info.__func__(OmnichannelSettingsServiceAsyncClient, 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: + OmnichannelSettingsServiceAsyncClient: The constructed client. + """ + return OmnichannelSettingsServiceClient.from_service_account_file.__func__(OmnichannelSettingsServiceAsyncClient, 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 OmnichannelSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> OmnichannelSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OmnichannelSettingsServiceTransport: 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 = OmnichannelSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the omnichannel settings 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,OmnichannelSettingsServiceTransport,Callable[..., OmnichannelSettingsServiceTransport]]]): + 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 OmnichannelSettingsServiceTransport 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 = OmnichannelSettingsServiceClient( + 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.accounts_v1beta.OmnichannelSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "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.accounts.v1beta.OmnichannelSettingsService", + "credentialsType": None, + } + ) + + async def get_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Get the omnichannel settings for a given merchant. + + .. 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_accounts_v1beta + + async def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest, dict]]): + The request object. Request message for the + GetOmnichannelSettings method. + name (:class:`str`): + Required. The name of the omnichannel setting to + retrieve. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannelsettings.GetOmnichannelSettingRequest): + request = omnichannelsettings.GetOmnichannelSettingRequest(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.get_omnichannel_setting] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_omnichannel_settings(self, + request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsAsyncPager: + r"""List all the omnichannel settings for a given + merchant. + + .. 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_accounts_v1beta + + async def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest, dict]]): + The request object. Request message for the + ListOmnichannelSettings method. + parent (:class:`str`): + Required. The parent, which owns this collection of + omnichannel settings. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsAsyncPager: + Response message for the + ListOmnichannelSettings 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, omnichannelsettings.ListOmnichannelSettingsRequest): + request = omnichannelsettings.ListOmnichannelSettingsRequest(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_omnichannel_settings] + + # 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.ListOmnichannelSettingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, + *, + parent: Optional[str] = None, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Create the omnichannel settings for a given merchant. + + .. 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_accounts_v1beta + + async def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest, dict]]): + The request object. Request message for the + CreateOmnichannelSetting method. + parent (:class:`str`): + Required. The parent resource where this omnichannel + setting will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + omnichannel_setting (:class:`google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting`): + Required. The omnichannel setting to + create. + + This corresponds to the ``omnichannel_setting`` 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_accounts_v1beta.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannel_setting] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.CreateOmnichannelSettingRequest): + request = omnichannelsettings.CreateOmnichannelSettingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_omnichannel_setting] + + # 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 update_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, + *, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Update the omnichannel setting for a given merchant + in a given country. + + .. 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_accounts_v1beta + + async def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest, dict]]): + The request object. Request message for the + UpdateOmnichannelSetting method. + omnichannel_setting (:class:`google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting`): + Required. The omnichannel setting to update. + + The omnichannel setting's ``name`` field is used to + identify the omnichannel setting to be updated. + + This corresponds to the ``omnichannel_setting`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. + + The following fields are supported in snake_case only: + + - ``lsf_type`` + - ``in_stock`` + - ``pickup`` + - ``odo`` + - ``about`` + - ``inventory_verification`` + + Full replacement with wildcard ``*``\ is supported, + while empty/implied update mask is not. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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 = [omnichannel_setting, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.UpdateOmnichannelSettingRequest): + request = omnichannelsettings.UpdateOmnichannelSettingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_omnichannel_setting] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("omnichannel_setting.name", request.omnichannel_setting.name), + )), + ) + + # 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 request_inventory_verification(self, + request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: + r"""Requests inventory verification for a given merchant + in a given country. + + .. 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_accounts_v1beta + + async def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = await client.request_inventory_verification(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest, dict]]): + The request object. Request message for the + RequestInventoryVerification method. + name (:class:`str`): + Required. The name of the omnichannel setting to request + inventory verification. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. + + """ + # 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, omnichannelsettings.RequestInventoryVerificationRequest): + request = omnichannelsettings.RequestInventoryVerificationRequest(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.request_inventory_verification] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "OmnichannelSettingsServiceAsyncClient": + 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__ = ( + "OmnichannelSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py new file mode 100644 index 000000000000..c7bf69f16a48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py @@ -0,0 +1,1231 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import pagers +from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings +from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OmnichannelSettingsServiceGrpcTransport +from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport +from .transports.rest import OmnichannelSettingsServiceRestTransport + + +class OmnichannelSettingsServiceClientMeta(type): + """Metaclass for the OmnichannelSettingsService 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[OmnichannelSettingsServiceTransport]] + _transport_registry["grpc"] = OmnichannelSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OmnichannelSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = OmnichannelSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[OmnichannelSettingsServiceTransport]: + """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 OmnichannelSettingsServiceClient(metaclass=OmnichannelSettingsServiceClientMeta): + """The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + """ + + @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: + OmnichannelSettingsServiceClient: 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: + OmnichannelSettingsServiceClient: 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) -> OmnichannelSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OmnichannelSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: + """Returns a fully-qualified omnichannel_setting string.""" + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + + @staticmethod + def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: + """Parses a omnichannel_setting path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?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 = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient._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, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the omnichannel settings 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,OmnichannelSettingsServiceTransport,Callable[..., OmnichannelSettingsServiceTransport]]]): + 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 OmnichannelSettingsServiceTransport 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 = OmnichannelSettingsServiceClient._read_environment_variables() + self._client_cert_source = OmnichannelSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = OmnichannelSettingsServiceClient._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, OmnichannelSettingsServiceTransport) + if transport_provided: + # transport is a OmnichannelSettingsServiceTransport 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(OmnichannelSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + OmnichannelSettingsServiceClient._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[OmnichannelSettingsServiceTransport], Callable[..., OmnichannelSettingsServiceTransport]] = ( + OmnichannelSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OmnichannelSettingsServiceTransport], 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.accounts_v1beta.OmnichannelSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "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.accounts.v1beta.OmnichannelSettingsService", + "credentialsType": None, + } + ) + + def get_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Get the omnichannel settings for a given merchant. + + .. 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_accounts_v1beta + + def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest, dict]): + The request object. Request message for the + GetOmnichannelSettings method. + name (str): + Required. The name of the omnichannel setting to + retrieve. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannelsettings.GetOmnichannelSettingRequest): + request = omnichannelsettings.GetOmnichannelSettingRequest(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.get_omnichannel_setting] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_omnichannel_settings(self, + request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsPager: + r"""List all the omnichannel settings for a given + merchant. + + .. 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_accounts_v1beta + + def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest, dict]): + The request object. Request message for the + ListOmnichannelSettings method. + parent (str): + Required. The parent, which owns this collection of + omnichannel settings. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsPager: + Response message for the + ListOmnichannelSettings 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, omnichannelsettings.ListOmnichannelSettingsRequest): + request = omnichannelsettings.ListOmnichannelSettingsRequest(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_omnichannel_settings] + + # 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.ListOmnichannelSettingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, + *, + parent: Optional[str] = None, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Create the omnichannel settings for a given merchant. + + .. 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_accounts_v1beta + + def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest, dict]): + The request object. Request message for the + CreateOmnichannelSetting method. + parent (str): + Required. The parent resource where this omnichannel + setting will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): + Required. The omnichannel setting to + create. + + This corresponds to the ``omnichannel_setting`` 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_accounts_v1beta.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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, omnichannel_setting] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.CreateOmnichannelSettingRequest): + request = omnichannelsettings.CreateOmnichannelSettingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_omnichannel_setting] + + # 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 update_omnichannel_setting(self, + request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, + *, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Update the omnichannel setting for a given merchant + in a given country. + + .. 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_accounts_v1beta + + def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest, dict]): + The request object. Request message for the + UpdateOmnichannelSetting method. + omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): + Required. The omnichannel setting to update. + + The omnichannel setting's ``name`` field is used to + identify the omnichannel setting to be updated. + + This corresponds to the ``omnichannel_setting`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + + The following fields are supported in snake_case only: + + - ``lsf_type`` + - ``in_stock`` + - ``pickup`` + - ``odo`` + - ``about`` + - ``inventory_verification`` + + Full replacement with wildcard ``*``\ is supported, + while empty/implied update mask is not. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + # 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 = [omnichannel_setting, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, omnichannelsettings.UpdateOmnichannelSettingRequest): + request = omnichannelsettings.UpdateOmnichannelSettingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if omnichannel_setting is not None: + request.omnichannel_setting = omnichannel_setting + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_omnichannel_setting] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("omnichannel_setting.name", request.omnichannel_setting.name), + )), + ) + + # 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 request_inventory_verification(self, + request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: + r"""Requests inventory verification for a given merchant + in a given country. + + .. 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_accounts_v1beta + + def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = client.request_inventory_verification(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest, dict]): + The request object. Request message for the + RequestInventoryVerification method. + name (str): + Required. The name of the omnichannel setting to request + inventory verification. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. + + """ + # 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, omnichannelsettings.RequestInventoryVerificationRequest): + request = omnichannelsettings.RequestInventoryVerificationRequest(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.request_inventory_verification] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "OmnichannelSettingsServiceClient": + 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__ = ( + "OmnichannelSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/pagers.py new file mode 100644 index 000000000000..878a0a1d8f7a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_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_accounts_v1beta.types import omnichannelsettings + + +class ListOmnichannelSettingsPager: + """A pager for iterating through ``list_omnichannel_settings`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``omnichannel_settings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOmnichannelSettings`` requests and continue to iterate + through the ``omnichannel_settings`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` + 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[..., omnichannelsettings.ListOmnichannelSettingsResponse], + request: omnichannelsettings.ListOmnichannelSettingsRequest, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + *, + 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_accounts_v1beta.types.ListOmnichannelSettingsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse): + 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 = omnichannelsettings.ListOmnichannelSettingsRequest(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[omnichannelsettings.ListOmnichannelSettingsResponse]: + 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[omnichannelsettings.OmnichannelSetting]: + for page in self.pages: + yield from page.omnichannel_settings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOmnichannelSettingsAsyncPager: + """A pager for iterating through ``list_omnichannel_settings`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``omnichannel_settings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOmnichannelSettings`` requests and continue to iterate + through the ``omnichannel_settings`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` + 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[omnichannelsettings.ListOmnichannelSettingsResponse]], + request: omnichannelsettings.ListOmnichannelSettingsRequest, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + *, + 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_accounts_v1beta.types.ListOmnichannelSettingsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse): + 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 = omnichannelsettings.ListOmnichannelSettingsRequest(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[omnichannelsettings.ListOmnichannelSettingsResponse]: + 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[omnichannelsettings.OmnichannelSetting]: + async def async_generator(): + async for page in self.pages: + for response in page.omnichannel_settings: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst new file mode 100644 index 000000000000..494c6b3d2bd7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OmnichannelSettingsServiceTransport` is the ABC for all transports. +- public child `OmnichannelSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OmnichannelSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOmnichannelSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OmnichannelSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/__init__.py new file mode 100644 index 000000000000..60f6dbfcf9cd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_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 OmnichannelSettingsServiceTransport +from .grpc import OmnichannelSettingsServiceGrpcTransport +from .grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport +from .rest import OmnichannelSettingsServiceRestTransport +from .rest import OmnichannelSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] +_transport_registry['grpc'] = OmnichannelSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OmnichannelSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = OmnichannelSettingsServiceRestTransport + +__all__ = ( + 'OmnichannelSettingsServiceTransport', + 'OmnichannelSettingsServiceGrpcTransport', + 'OmnichannelSettingsServiceGrpcAsyncIOTransport', + 'OmnichannelSettingsServiceRestTransport', + 'OmnichannelSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py new file mode 100644 index 000000000000..f829a9364942 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py @@ -0,0 +1,215 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import omnichannelsettings + +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 OmnichannelSettingsServiceTransport(abc.ABC): + """Abstract transport class for OmnichannelSettingsService.""" + + 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.get_omnichannel_setting: gapic_v1.method.wrap_method( + self.get_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.list_omnichannel_settings: gapic_v1.method.wrap_method( + self.list_omnichannel_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_omnichannel_setting: gapic_v1.method.wrap_method( + self.create_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.update_omnichannel_setting: gapic_v1.method.wrap_method( + self.update_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.request_inventory_verification: gapic_v1.method.wrap_method( + self.request_inventory_verification, + 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 get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting] + ]]: + raise NotImplementedError() + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + Union[ + omnichannelsettings.ListOmnichannelSettingsResponse, + Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse] + ]]: + raise NotImplementedError() + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting] + ]]: + raise NotImplementedError() + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting] + ]]: + raise NotImplementedError() + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + Union[ + omnichannelsettings.RequestInventoryVerificationResponse, + Awaitable[omnichannelsettings.RequestInventoryVerificationResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'OmnichannelSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py new file mode 100644 index 000000000000..b2d67d4d7b40 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py @@ -0,0 +1,459 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import omnichannelsettings +from .base import OmnichannelSettingsServiceTransport, 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.accounts.v1beta.OmnichannelSettingsService", + "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.accounts.v1beta.OmnichannelSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OmnichannelSettingsServiceGrpcTransport(OmnichannelSettingsServiceTransport): + """gRPC backend transport for OmnichannelSettingsService. + + The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + + 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 get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + r"""Return a callable for the get omnichannel setting method over gRPC. + + Get the omnichannel settings for a given merchant. + + Returns: + Callable[[~.GetOmnichannelSettingRequest], + ~.OmnichannelSetting]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_omnichannel_setting' not in self._stubs: + self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/GetOmnichannelSetting', + request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['get_omnichannel_setting'] + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + omnichannelsettings.ListOmnichannelSettingsResponse]: + r"""Return a callable for the list omnichannel settings method over gRPC. + + List all the omnichannel settings for a given + merchant. + + Returns: + Callable[[~.ListOmnichannelSettingsRequest], + ~.ListOmnichannelSettingsResponse]: + 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_omnichannel_settings' not in self._stubs: + self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/ListOmnichannelSettings', + request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, + response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, + ) + return self._stubs['list_omnichannel_settings'] + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + r"""Return a callable for the create omnichannel setting method over gRPC. + + Create the omnichannel settings for a given merchant. + + Returns: + Callable[[~.CreateOmnichannelSettingRequest], + ~.OmnichannelSetting]: + 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 'create_omnichannel_setting' not in self._stubs: + self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/CreateOmnichannelSetting', + request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['create_omnichannel_setting'] + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + r"""Return a callable for the update omnichannel setting method over gRPC. + + Update the omnichannel setting for a given merchant + in a given country. + + Returns: + Callable[[~.UpdateOmnichannelSettingRequest], + ~.OmnichannelSetting]: + 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 'update_omnichannel_setting' not in self._stubs: + self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/UpdateOmnichannelSetting', + request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['update_omnichannel_setting'] + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + omnichannelsettings.RequestInventoryVerificationResponse]: + r"""Return a callable for the request inventory verification method over gRPC. + + Requests inventory verification for a given merchant + in a given country. + + Returns: + Callable[[~.RequestInventoryVerificationRequest], + ~.RequestInventoryVerificationResponse]: + 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 'request_inventory_verification' not in self._stubs: + self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/RequestInventoryVerification', + request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, + response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, + ) + return self._stubs['request_inventory_verification'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'OmnichannelSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..92d72348b164 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,500 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import omnichannelsettings +from .base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OmnichannelSettingsServiceGrpcTransport + +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.accounts.v1beta.OmnichannelSettingsService", + "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.accounts.v1beta.OmnichannelSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OmnichannelSettingsServiceGrpcAsyncIOTransport(OmnichannelSettingsServiceTransport): + """gRPC AsyncIO backend transport for OmnichannelSettingsService. + + The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + + 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 get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting]]: + r"""Return a callable for the get omnichannel setting method over gRPC. + + Get the omnichannel settings for a given merchant. + + Returns: + Callable[[~.GetOmnichannelSettingRequest], + Awaitable[~.OmnichannelSetting]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_omnichannel_setting' not in self._stubs: + self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/GetOmnichannelSetting', + request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['get_omnichannel_setting'] + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse]]: + r"""Return a callable for the list omnichannel settings method over gRPC. + + List all the omnichannel settings for a given + merchant. + + Returns: + Callable[[~.ListOmnichannelSettingsRequest], + Awaitable[~.ListOmnichannelSettingsResponse]]: + 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_omnichannel_settings' not in self._stubs: + self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/ListOmnichannelSettings', + request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, + response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, + ) + return self._stubs['list_omnichannel_settings'] + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting]]: + r"""Return a callable for the create omnichannel setting method over gRPC. + + Create the omnichannel settings for a given merchant. + + Returns: + Callable[[~.CreateOmnichannelSettingRequest], + Awaitable[~.OmnichannelSetting]]: + 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 'create_omnichannel_setting' not in self._stubs: + self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/CreateOmnichannelSetting', + request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['create_omnichannel_setting'] + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting]]: + r"""Return a callable for the update omnichannel setting method over gRPC. + + Update the omnichannel setting for a given merchant + in a given country. + + Returns: + Callable[[~.UpdateOmnichannelSettingRequest], + Awaitable[~.OmnichannelSetting]]: + 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 'update_omnichannel_setting' not in self._stubs: + self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/UpdateOmnichannelSetting', + request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, + response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, + ) + return self._stubs['update_omnichannel_setting'] + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + Awaitable[omnichannelsettings.RequestInventoryVerificationResponse]]: + r"""Return a callable for the request inventory verification method over gRPC. + + Requests inventory verification for a given merchant + in a given country. + + Returns: + Callable[[~.RequestInventoryVerificationRequest], + Awaitable[~.RequestInventoryVerificationResponse]]: + 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 'request_inventory_verification' not in self._stubs: + self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/RequestInventoryVerification', + request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, + response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, + ) + return self._stubs['request_inventory_verification'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_omnichannel_setting: self._wrap_method( + self.get_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.list_omnichannel_settings: self._wrap_method( + self.list_omnichannel_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_omnichannel_setting: self._wrap_method( + self.create_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.update_omnichannel_setting: self._wrap_method( + self.update_omnichannel_setting, + default_timeout=None, + client_info=client_info, + ), + self.request_inventory_verification: self._wrap_method( + self.request_inventory_verification, + 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__ = ( + 'OmnichannelSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py new file mode 100644 index 000000000000..2e96b40c696d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py @@ -0,0 +1,1068 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import omnichannelsettings + + +from .rest_base import _BaseOmnichannelSettingsServiceRestTransport +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 OmnichannelSettingsServiceRestInterceptor: + """Interceptor for OmnichannelSettingsService. + + 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 OmnichannelSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomOmnichannelSettingsServiceInterceptor(OmnichannelSettingsServiceRestInterceptor): + def pre_create_omnichannel_setting(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_omnichannel_setting(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_omnichannel_setting(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_omnichannel_setting(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_omnichannel_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_omnichannel_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_request_inventory_verification(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_request_inventory_verification(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_omnichannel_setting(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_omnichannel_setting(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OmnichannelSettingsServiceRestTransport(interceptor=MyCustomOmnichannelSettingsServiceInterceptor()) + client = OmnichannelSettingsServiceClient(transport=transport) + + + """ + def pre_create_omnichannel_setting(self, request: omnichannelsettings.CreateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.CreateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_omnichannel_setting + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_create_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + """Post-rpc interceptor for create_omnichannel_setting + + DEPRECATED. Please use the `post_create_omnichannel_setting_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_create_omnichannel_setting` interceptor runs + before the `post_create_omnichannel_setting_with_metadata` interceptor. + """ + return response + + def post_create_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_omnichannel_setting + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_create_omnichannel_setting_with_metadata` + interceptor in new development instead of the `post_create_omnichannel_setting` interceptor. + When both interceptors are used, this `post_create_omnichannel_setting_with_metadata` interceptor runs after the + `post_create_omnichannel_setting` interceptor. The (possibly modified) response returned by + `post_create_omnichannel_setting` will be passed to + `post_create_omnichannel_setting_with_metadata`. + """ + return response, metadata + + def pre_get_omnichannel_setting(self, request: omnichannelsettings.GetOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.GetOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_omnichannel_setting + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_get_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + """Post-rpc interceptor for get_omnichannel_setting + + DEPRECATED. Please use the `post_get_omnichannel_setting_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_get_omnichannel_setting` interceptor runs + before the `post_get_omnichannel_setting_with_metadata` interceptor. + """ + return response + + def post_get_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_omnichannel_setting + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_omnichannel_setting_with_metadata` + interceptor in new development instead of the `post_get_omnichannel_setting` interceptor. + When both interceptors are used, this `post_get_omnichannel_setting_with_metadata` interceptor runs after the + `post_get_omnichannel_setting` interceptor. The (possibly modified) response returned by + `post_get_omnichannel_setting` will be passed to + `post_get_omnichannel_setting_with_metadata`. + """ + return response, metadata + + def pre_list_omnichannel_settings(self, request: omnichannelsettings.ListOmnichannelSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_omnichannel_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_list_omnichannel_settings(self, response: omnichannelsettings.ListOmnichannelSettingsResponse) -> omnichannelsettings.ListOmnichannelSettingsResponse: + """Post-rpc interceptor for list_omnichannel_settings + + DEPRECATED. Please use the `post_list_omnichannel_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_list_omnichannel_settings` interceptor runs + before the `post_list_omnichannel_settings_with_metadata` interceptor. + """ + return response + + def post_list_omnichannel_settings_with_metadata(self, response: omnichannelsettings.ListOmnichannelSettingsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_omnichannel_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_list_omnichannel_settings_with_metadata` + interceptor in new development instead of the `post_list_omnichannel_settings` interceptor. + When both interceptors are used, this `post_list_omnichannel_settings_with_metadata` interceptor runs after the + `post_list_omnichannel_settings` interceptor. The (possibly modified) response returned by + `post_list_omnichannel_settings` will be passed to + `post_list_omnichannel_settings_with_metadata`. + """ + return response, metadata + + def pre_request_inventory_verification(self, request: omnichannelsettings.RequestInventoryVerificationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for request_inventory_verification + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_request_inventory_verification(self, response: omnichannelsettings.RequestInventoryVerificationResponse) -> omnichannelsettings.RequestInventoryVerificationResponse: + """Post-rpc interceptor for request_inventory_verification + + DEPRECATED. Please use the `post_request_inventory_verification_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_request_inventory_verification` interceptor runs + before the `post_request_inventory_verification_with_metadata` interceptor. + """ + return response + + def post_request_inventory_verification_with_metadata(self, response: omnichannelsettings.RequestInventoryVerificationResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for request_inventory_verification + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_request_inventory_verification_with_metadata` + interceptor in new development instead of the `post_request_inventory_verification` interceptor. + When both interceptors are used, this `post_request_inventory_verification_with_metadata` interceptor runs after the + `post_request_inventory_verification` interceptor. The (possibly modified) response returned by + `post_request_inventory_verification` will be passed to + `post_request_inventory_verification_with_metadata`. + """ + return response, metadata + + def pre_update_omnichannel_setting(self, request: omnichannelsettings.UpdateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.UpdateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_omnichannel_setting + + Override in a subclass to manipulate the request or metadata + before they are sent to the OmnichannelSettingsService server. + """ + return request, metadata + + def post_update_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + """Post-rpc interceptor for update_omnichannel_setting + + DEPRECATED. Please use the `post_update_omnichannel_setting_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OmnichannelSettingsService server but before + it is returned to user code. This `post_update_omnichannel_setting` interceptor runs + before the `post_update_omnichannel_setting_with_metadata` interceptor. + """ + return response + + def post_update_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_omnichannel_setting + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OmnichannelSettingsService server but before it is returned to user code. + + We recommend only using this `post_update_omnichannel_setting_with_metadata` + interceptor in new development instead of the `post_update_omnichannel_setting` interceptor. + When both interceptors are used, this `post_update_omnichannel_setting_with_metadata` interceptor runs after the + `post_update_omnichannel_setting` interceptor. The (possibly modified) response returned by + `post_update_omnichannel_setting` will be passed to + `post_update_omnichannel_setting_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class OmnichannelSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OmnichannelSettingsServiceRestInterceptor + + +class OmnichannelSettingsServiceRestTransport(_BaseOmnichannelSettingsServiceRestTransport): + """REST backend synchronous transport for OmnichannelSettingsService. + + The service facilitates the management of a merchant's omnichannel + settings. + + This API defines the following resource model: + ---------------------------------------------- + + [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + + 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[OmnichannelSettingsServiceRestInterceptor] = 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 OmnichannelSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.CreateOmnichannelSetting") + + @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: omnichannelsettings.CreateOmnichannelSettingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Call the create omnichannel + setting method over HTTP. + + Args: + request (~.omnichannelsettings.CreateOmnichannelSettingRequest): + The request object. Request message for the + CreateOmnichannelSetting 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_http_options() + + request, metadata = self._interceptor.pre_create_omnichannel_setting(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_transcoded_request(http_options, request) + + body = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.CreateOmnichannelSetting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "CreateOmnichannelSetting", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._CreateOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() + pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_omnichannel_setting(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_omnichannel_setting_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1beta.OmnichannelSettingsServiceClient.create_omnichannel_setting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "CreateOmnichannelSetting", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.GetOmnichannelSetting") + + @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: omnichannelsettings.GetOmnichannelSettingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Call the get omnichannel setting method over HTTP. + + Args: + request (~.omnichannelsettings.GetOmnichannelSettingRequest): + The request object. Request message for the + GetOmnichannelSettings 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_http_options() + + request, metadata = self._interceptor.pre_get_omnichannel_setting(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.GetOmnichannelSetting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "GetOmnichannelSetting", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._GetOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() + pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_omnichannel_setting(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_omnichannel_setting_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1beta.OmnichannelSettingsServiceClient.get_omnichannel_setting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "GetOmnichannelSetting", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOmnichannelSettings(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.ListOmnichannelSettings") + + @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: omnichannelsettings.ListOmnichannelSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.ListOmnichannelSettingsResponse: + r"""Call the list omnichannel settings method over HTTP. + + Args: + request (~.omnichannelsettings.ListOmnichannelSettingsRequest): + The request object. Request message for the + ListOmnichannelSettings 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: + ~.omnichannelsettings.ListOmnichannelSettingsResponse: + Response message for the + ListOmnichannelSettings method. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_http_options() + + request, metadata = self._interceptor.pre_list_omnichannel_settings(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.ListOmnichannelSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "ListOmnichannelSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._ListOmnichannelSettings._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 = omnichannelsettings.ListOmnichannelSettingsResponse() + pb_resp = omnichannelsettings.ListOmnichannelSettingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_omnichannel_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_omnichannel_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.ListOmnichannelSettingsResponse.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.accounts_v1beta.OmnichannelSettingsServiceClient.list_omnichannel_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "ListOmnichannelSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RequestInventoryVerification(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.RequestInventoryVerification") + + @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: omnichannelsettings.RequestInventoryVerificationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: + r"""Call the request inventory + verification method over HTTP. + + Args: + request (~.omnichannelsettings.RequestInventoryVerificationRequest): + The request object. Request message for the + RequestInventoryVerification 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: + ~.omnichannelsettings.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_http_options() + + request, metadata = self._interceptor.pre_request_inventory_verification(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_transcoded_request(http_options, request) + + body = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.RequestInventoryVerification", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "RequestInventoryVerification", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._RequestInventoryVerification._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 = omnichannelsettings.RequestInventoryVerificationResponse() + pb_resp = omnichannelsettings.RequestInventoryVerificationResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_request_inventory_verification(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_request_inventory_verification_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.RequestInventoryVerificationResponse.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.accounts_v1beta.OmnichannelSettingsServiceClient.request_inventory_verification", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "RequestInventoryVerification", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting, OmnichannelSettingsServiceRestStub): + def __hash__(self): + return hash("OmnichannelSettingsServiceRestTransport.UpdateOmnichannelSetting") + + @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: omnichannelsettings.UpdateOmnichannelSettingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> omnichannelsettings.OmnichannelSetting: + r"""Call the update omnichannel + setting method over HTTP. + + Args: + request (~.omnichannelsettings.UpdateOmnichannelSettingRequest): + The request object. Request message for the + UpdateOmnichannelSetting 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. + + """ + + http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_http_options() + + request, metadata = self._interceptor.pre_update_omnichannel_setting(request, metadata) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_transcoded_request(http_options, request) + + body = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.UpdateOmnichannelSetting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "UpdateOmnichannelSetting", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OmnichannelSettingsServiceRestTransport._UpdateOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() + pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_omnichannel_setting(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_omnichannel_setting_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1beta.OmnichannelSettingsServiceClient.update_omnichannel_setting", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "rpcName": "UpdateOmnichannelSetting", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + # 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._CreateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + # 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._GetOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_omnichannel_settings(self) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + omnichannelsettings.ListOmnichannelSettingsResponse]: + # 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._ListOmnichannelSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def request_inventory_verification(self) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + omnichannelsettings.RequestInventoryVerificationResponse]: + # 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._RequestInventoryVerification(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_omnichannel_setting(self) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting]: + # 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._UpdateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'OmnichannelSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..b726584914c0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py @@ -0,0 +1,306 @@ +# -*- 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 OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings + + +class _BaseOmnichannelSettingsServiceRestTransport(OmnichannelSettingsServiceTransport): + """Base REST backend transport for OmnichannelSettingsService. + + 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 _BaseCreateOmnichannelSetting: + 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': '/accounts/v1beta/{parent=accounts/*}/omnichannelSettings', + 'body': 'omnichannel_setting', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.CreateOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOmnichannelSetting: + 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': '/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.GetOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListOmnichannelSettings: + 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': '/accounts/v1beta/{parent=accounts/*}/omnichannelSettings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.ListOmnichannelSettingsRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRequestInventoryVerification: + 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': '/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.RequestInventoryVerificationRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateOmnichannelSetting: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}', + 'body': 'omnichannel_setting', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = omnichannelsettings.UpdateOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseOmnichannelSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/__init__.py new file mode 100644 index 000000000000..856118f59e37 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_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 OnlineReturnPolicyServiceClient +from .async_client import OnlineReturnPolicyServiceAsyncClient + +__all__ = ( + 'OnlineReturnPolicyServiceClient', + 'OnlineReturnPolicyServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py new file mode 100644 index 000000000000..84414ea78901 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py @@ -0,0 +1,860 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy +from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport +from .client import OnlineReturnPolicyServiceClient + +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 OnlineReturnPolicyServiceAsyncClient: + """The service facilitates the management of a merchant's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + """ + + _client: OnlineReturnPolicyServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + + online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.online_return_policy_path) + parse_online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.parse_online_return_policy_path) + common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_organization_path) + common_project_path = staticmethod(OnlineReturnPolicyServiceClient.common_project_path) + parse_common_project_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_project_path) + common_location_path = staticmethod(OnlineReturnPolicyServiceClient.common_location_path) + parse_common_location_path = staticmethod(OnlineReturnPolicyServiceClient.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: + OnlineReturnPolicyServiceAsyncClient: The constructed client. + """ + return OnlineReturnPolicyServiceClient.from_service_account_info.__func__(OnlineReturnPolicyServiceAsyncClient, 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: + OnlineReturnPolicyServiceAsyncClient: The constructed client. + """ + return OnlineReturnPolicyServiceClient.from_service_account_file.__func__(OnlineReturnPolicyServiceAsyncClient, 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 OnlineReturnPolicyServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> OnlineReturnPolicyServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OnlineReturnPolicyServiceTransport: 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 = OnlineReturnPolicyServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the online return policy 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,OnlineReturnPolicyServiceTransport,Callable[..., OnlineReturnPolicyServiceTransport]]]): + 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 OnlineReturnPolicyServiceTransport 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 = OnlineReturnPolicyServiceClient( + 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.accounts_v1beta.OnlineReturnPolicyServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "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.accounts.v1beta.OnlineReturnPolicyService", + "credentialsType": None, + } + ) + + async def get_online_return_policy(self, + request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: + r"""Gets an existing return policy for a given merchant. + + .. 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_accounts_v1beta + + async def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``GetOnlineReturnPolicy`` + method. + name (:class:`str`): + Required. The name of the return policy to retrieve. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy.GetOnlineReturnPolicyRequest): + request = online_return_policy.GetOnlineReturnPolicyRequest(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.get_online_return_policy] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_online_return_policies(self, + request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesAsyncPager: + r"""Lists all existing return policies for a given + merchant. + + .. 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_accounts_v1beta + + async def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest, dict]]): + The request object. Request message for the ``ListOnlineReturnPolicies`` + method. + parent (:class:`str`): + Required. The merchant account for which to list return + policies. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager: + Response message for the ListOnlineReturnPolicies + 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, online_return_policy.ListOnlineReturnPoliciesRequest): + request = online_return_policy.ListOnlineReturnPoliciesRequest(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_online_return_policies] + + # 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.ListOnlineReturnPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_online_return_policy(self, + request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Creates a new return policy for a given merchant. + + .. 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_accounts_v1beta + + async def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = await client.create_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + method. + parent (:class:`str`): + Required. The merchant account for which the return + policy will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + online_return_policy (:class:`google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy`): + Required. The return policy object to + create. + + This corresponds to the ``online_return_policy`` 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_accounts_v1beta.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if online_return_policy is not None: + request.online_return_policy = online_return_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_online_return_policy] + + # 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 update_online_return_policy(self, + request: Optional[Union[gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, dict]] = None, + *, + online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Updates an existing return policy for a given + merchant. + + .. 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_accounts_v1beta + + async def sample_update_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( + online_return_policy=online_return_policy, + ) + + # Make the request + response = await client.update_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``UpdateOnlineReturnPolicy`` + method. The method supports field masks and when the + mask is provided, only the fields specified in the mask + are updated. + online_return_policy (:class:`google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy`): + Required. The online return policy to update. The online + return policy's ``name`` field is used to identify the + online return policy to be updated. + + This corresponds to the ``online_return_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``accept_defective_only`` + - ``accept_exchange`` + - ``item_conditions`` + - ``policy`` + - ``process_refund_days`` + - ``restocking_fee`` + - ``return_methods`` + - ``return_policy_uri`` + - ``return_shipping_fee`` + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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 = [online_return_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): + request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if online_return_policy is not None: + request.online_return_policy = online_return_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_online_return_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("online_return_policy.name", request.online_return_policy.name), + )), + ) + + # 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_online_return_policy(self, + request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, + *, + name: 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 an existing return policy. + + .. 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_accounts_v1beta + + async def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + await client.delete_online_return_policy(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest, dict]]): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + method. + name (:class:`str`): + Required. The name of the return policy to delete. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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, online_return_policy.DeleteOnlineReturnPolicyRequest): + request = online_return_policy.DeleteOnlineReturnPolicyRequest(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_online_return_policy] + + # 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) -> "OnlineReturnPolicyServiceAsyncClient": + 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__ = ( + "OnlineReturnPolicyServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py new file mode 100644 index 000000000000..eef815896c83 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py @@ -0,0 +1,1216 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy +from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import OnlineReturnPolicyServiceGrpcTransport +from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport +from .transports.rest import OnlineReturnPolicyServiceRestTransport + + +class OnlineReturnPolicyServiceClientMeta(type): + """Metaclass for the OnlineReturnPolicyService 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[OnlineReturnPolicyServiceTransport]] + _transport_registry["grpc"] = OnlineReturnPolicyServiceGrpcTransport + _transport_registry["grpc_asyncio"] = OnlineReturnPolicyServiceGrpcAsyncIOTransport + _transport_registry["rest"] = OnlineReturnPolicyServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[OnlineReturnPolicyServiceTransport]: + """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 OnlineReturnPolicyServiceClient(metaclass=OnlineReturnPolicyServiceClientMeta): + """The service facilitates the management of a merchant's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + """ + + @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: + OnlineReturnPolicyServiceClient: 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: + OnlineReturnPolicyServiceClient: 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) -> OnlineReturnPolicyServiceTransport: + """Returns the transport used by the client instance. + + Returns: + OnlineReturnPolicyServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def online_return_policy_path(account: str,return_policy: str,) -> str: + """Returns a fully-qualified online_return_policy string.""" + return "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) + + @staticmethod + def parse_online_return_policy_path(path: str) -> Dict[str,str]: + """Parses a online_return_policy path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/onlineReturnPolicies/(?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 = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient._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, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the online return policy 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,OnlineReturnPolicyServiceTransport,Callable[..., OnlineReturnPolicyServiceTransport]]]): + 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 OnlineReturnPolicyServiceTransport 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 = OnlineReturnPolicyServiceClient._read_environment_variables() + self._client_cert_source = OnlineReturnPolicyServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = OnlineReturnPolicyServiceClient._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, OnlineReturnPolicyServiceTransport) + if transport_provided: + # transport is a OnlineReturnPolicyServiceTransport 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(OnlineReturnPolicyServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + OnlineReturnPolicyServiceClient._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[OnlineReturnPolicyServiceTransport], Callable[..., OnlineReturnPolicyServiceTransport]] = ( + OnlineReturnPolicyServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OnlineReturnPolicyServiceTransport], 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.accounts_v1beta.OnlineReturnPolicyServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "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.accounts.v1beta.OnlineReturnPolicyService", + "credentialsType": None, + } + ) + + def get_online_return_policy(self, + request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: + r"""Gets an existing return policy for a given merchant. + + .. 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_accounts_v1beta + + def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``GetOnlineReturnPolicy`` + method. + name (str): + Required. The name of the return policy to retrieve. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy.GetOnlineReturnPolicyRequest): + request = online_return_policy.GetOnlineReturnPolicyRequest(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.get_online_return_policy] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_online_return_policies(self, + request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesPager: + r"""Lists all existing return policies for a given + merchant. + + .. 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_accounts_v1beta + + def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest, dict]): + The request object. Request message for the ``ListOnlineReturnPolicies`` + method. + parent (str): + Required. The merchant account for which to list return + policies. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager: + Response message for the ListOnlineReturnPolicies + 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, online_return_policy.ListOnlineReturnPoliciesRequest): + request = online_return_policy.ListOnlineReturnPoliciesRequest(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_online_return_policies] + + # 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.ListOnlineReturnPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_online_return_policy(self, + request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, + *, + parent: Optional[str] = None, + online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Creates a new return policy for a given merchant. + + .. 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_accounts_v1beta + + def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = client.create_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + method. + parent (str): + Required. The merchant account for which the return + policy will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): + Required. The return policy object to + create. + + This corresponds to the ``online_return_policy`` 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_accounts_v1beta.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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, online_return_policy] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if online_return_policy is not None: + request.online_return_policy = online_return_policy + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_online_return_policy] + + # 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 update_online_return_policy(self, + request: Optional[Union[gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, dict]] = None, + *, + online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Updates an existing return policy for a given + merchant. + + .. 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_accounts_v1beta + + def sample_update_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( + online_return_policy=online_return_policy, + ) + + # Make the request + response = client.update_online_return_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``UpdateOnlineReturnPolicy`` + method. The method supports field masks and when the + mask is provided, only the fields specified in the mask + are updated. + online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): + Required. The online return policy to update. The online + return policy's ``name`` field is used to identify the + online return policy to be updated. + + This corresponds to the ``online_return_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both + ``snake_case`` and ``lowerCamelCase``): + + - ``accept_defective_only`` + - ``accept_exchange`` + - ``item_conditions`` + - ``policy`` + - ``process_refund_days`` + - ``restocking_fee`` + - ``return_methods`` + - ``return_policy_uri`` + - ``return_shipping_fee`` + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OnlineReturnPolicy: + [Online return policy](\ https://support.google.com/merchants/answer/10220642) + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + # 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 = [online_return_policy, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): + request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if online_return_policy is not None: + request.online_return_policy = online_return_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_online_return_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("online_return_policy.name", request.online_return_policy.name), + )), + ) + + # 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_online_return_policy(self, + request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, + *, + name: 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 an existing return policy. + + .. 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_accounts_v1beta + + def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + client.delete_online_return_policy(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest, dict]): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + method. + name (str): + Required. The name of the return policy to delete. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + + 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, online_return_policy.DeleteOnlineReturnPolicyRequest): + request = online_return_policy.DeleteOnlineReturnPolicyRequest(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_online_return_policy] + + # 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) -> "OnlineReturnPolicyServiceClient": + 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__ = ( + "OnlineReturnPolicyServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py new file mode 100644 index 000000000000..2d550a648397 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_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_accounts_v1beta.types import online_return_policy + + +class ListOnlineReturnPoliciesPager: + """A pager for iterating through ``list_online_return_policies`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``online_return_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListOnlineReturnPolicies`` requests and continue to iterate + through the ``online_return_policies`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` + 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[..., online_return_policy.ListOnlineReturnPoliciesResponse], + request: online_return_policy.ListOnlineReturnPoliciesRequest, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + *, + 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_accounts_v1beta.types.ListOnlineReturnPoliciesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse): + 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 = online_return_policy.ListOnlineReturnPoliciesRequest(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[online_return_policy.ListOnlineReturnPoliciesResponse]: + 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[online_return_policy.OnlineReturnPolicy]: + for page in self.pages: + yield from page.online_return_policies + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListOnlineReturnPoliciesAsyncPager: + """A pager for iterating through ``list_online_return_policies`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``online_return_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListOnlineReturnPolicies`` requests and continue to iterate + through the ``online_return_policies`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` + 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[online_return_policy.ListOnlineReturnPoliciesResponse]], + request: online_return_policy.ListOnlineReturnPoliciesRequest, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + *, + 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_accounts_v1beta.types.ListOnlineReturnPoliciesRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse): + 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 = online_return_policy.ListOnlineReturnPoliciesRequest(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[online_return_policy.ListOnlineReturnPoliciesResponse]: + 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[online_return_policy.OnlineReturnPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.online_return_policies: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst new file mode 100644 index 000000000000..a6e34721a621 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`OnlineReturnPolicyServiceTransport` is the ABC for all transports. +- public child `OnlineReturnPolicyServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `OnlineReturnPolicyServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseOnlineReturnPolicyServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `OnlineReturnPolicyServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/__init__.py new file mode 100644 index 000000000000..406ed1cc95a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_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 OnlineReturnPolicyServiceTransport +from .grpc import OnlineReturnPolicyServiceGrpcTransport +from .grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport +from .rest import OnlineReturnPolicyServiceRestTransport +from .rest import OnlineReturnPolicyServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] +_transport_registry['grpc'] = OnlineReturnPolicyServiceGrpcTransport +_transport_registry['grpc_asyncio'] = OnlineReturnPolicyServiceGrpcAsyncIOTransport +_transport_registry['rest'] = OnlineReturnPolicyServiceRestTransport + +__all__ = ( + 'OnlineReturnPolicyServiceTransport', + 'OnlineReturnPolicyServiceGrpcTransport', + 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', + 'OnlineReturnPolicyServiceRestTransport', + 'OnlineReturnPolicyServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py new file mode 100644 index 000000000000..8e455d20465e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py @@ -0,0 +1,217 @@ +# -*- 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_accounts_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_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy + +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 OnlineReturnPolicyServiceTransport(abc.ABC): + """Abstract transport class for OnlineReturnPolicyService.""" + + 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.get_online_return_policy: gapic_v1.method.wrap_method( + self.get_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_online_return_policies: gapic_v1.method.wrap_method( + self.list_online_return_policies, + default_timeout=None, + client_info=client_info, + ), + self.create_online_return_policy: gapic_v1.method.wrap_method( + self.create_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_online_return_policy: gapic_v1.method.wrap_method( + self.update_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_online_return_policy: gapic_v1.method.wrap_method( + self.delete_online_return_policy, + 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 get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + Union[ + online_return_policy.OnlineReturnPolicy, + Awaitable[online_return_policy.OnlineReturnPolicy] + ]]: + raise NotImplementedError() + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + Union[ + online_return_policy.ListOnlineReturnPoliciesResponse, + Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + Union[ + gsma_online_return_policy.OnlineReturnPolicy, + Awaitable[gsma_online_return_policy.OnlineReturnPolicy] + ]]: + raise NotImplementedError() + + @property + def update_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], + Union[ + gsma_online_return_policy.OnlineReturnPolicy, + Awaitable[gsma_online_return_policy.OnlineReturnPolicy] + ]]: + raise NotImplementedError() + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'OnlineReturnPolicyServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py new file mode 100644 index 000000000000..dbfb87c664c8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py @@ -0,0 +1,461 @@ +# -*- 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_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy +from .base import OnlineReturnPolicyServiceTransport, 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.accounts.v1beta.OnlineReturnPolicyService", + "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.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OnlineReturnPolicyServiceGrpcTransport(OnlineReturnPolicyServiceTransport): + """gRPC backend transport for OnlineReturnPolicyService. + + The service facilitates the management of a merchant's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + + 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 get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + online_return_policy.OnlineReturnPolicy]: + r"""Return a callable for the get online return policy method over gRPC. + + Gets an existing return policy for a given merchant. + + Returns: + Callable[[~.GetOnlineReturnPolicyRequest], + ~.OnlineReturnPolicy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_online_return_policy' not in self._stubs: + self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/GetOnlineReturnPolicy', + request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, + response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['get_online_return_policy'] + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + online_return_policy.ListOnlineReturnPoliciesResponse]: + r"""Return a callable for the list online return policies method over gRPC. + + Lists all existing return policies for a given + merchant. + + Returns: + Callable[[~.ListOnlineReturnPoliciesRequest], + ~.ListOnlineReturnPoliciesResponse]: + 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_online_return_policies' not in self._stubs: + self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/ListOnlineReturnPolicies', + request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, + response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, + ) + return self._stubs['list_online_return_policies'] + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy]: + r"""Return a callable for the create online return policy method over gRPC. + + Creates a new return policy for a given merchant. + + Returns: + Callable[[~.CreateOnlineReturnPolicyRequest], + ~.OnlineReturnPolicy]: + 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 'create_online_return_policy' not in self._stubs: + self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/CreateOnlineReturnPolicy', + request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, + response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['create_online_return_policy'] + + @property + def update_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy]: + r"""Return a callable for the update online return policy method over gRPC. + + Updates an existing return policy for a given + merchant. + + Returns: + Callable[[~.UpdateOnlineReturnPolicyRequest], + ~.OnlineReturnPolicy]: + 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 'update_online_return_policy' not in self._stubs: + self._stubs['update_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/UpdateOnlineReturnPolicy', + request_serializer=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.serialize, + response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['update_online_return_policy'] + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete online return policy method over gRPC. + + Deletes an existing return policy. + + Returns: + Callable[[~.DeleteOnlineReturnPolicyRequest], + ~.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_online_return_policy' not in self._stubs: + self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', + request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_online_return_policy'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'OnlineReturnPolicyServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..f22ed6845d38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py @@ -0,0 +1,502 @@ +# -*- 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_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy +from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import OnlineReturnPolicyServiceGrpcTransport + +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.accounts.v1beta.OnlineReturnPolicyService", + "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.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class OnlineReturnPolicyServiceGrpcAsyncIOTransport(OnlineReturnPolicyServiceTransport): + """gRPC AsyncIO backend transport for OnlineReturnPolicyService. + + The service facilitates the management of a merchant's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + + 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 get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + Awaitable[online_return_policy.OnlineReturnPolicy]]: + r"""Return a callable for the get online return policy method over gRPC. + + Gets an existing return policy for a given merchant. + + Returns: + Callable[[~.GetOnlineReturnPolicyRequest], + Awaitable[~.OnlineReturnPolicy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_online_return_policy' not in self._stubs: + self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/GetOnlineReturnPolicy', + request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, + response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['get_online_return_policy'] + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse]]: + r"""Return a callable for the list online return policies method over gRPC. + + Lists all existing return policies for a given + merchant. + + Returns: + Callable[[~.ListOnlineReturnPoliciesRequest], + Awaitable[~.ListOnlineReturnPoliciesResponse]]: + 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_online_return_policies' not in self._stubs: + self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/ListOnlineReturnPolicies', + request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, + response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, + ) + return self._stubs['list_online_return_policies'] + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + Awaitable[gsma_online_return_policy.OnlineReturnPolicy]]: + r"""Return a callable for the create online return policy method over gRPC. + + Creates a new return policy for a given merchant. + + Returns: + Callable[[~.CreateOnlineReturnPolicyRequest], + Awaitable[~.OnlineReturnPolicy]]: + 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 'create_online_return_policy' not in self._stubs: + self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/CreateOnlineReturnPolicy', + request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, + response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['create_online_return_policy'] + + @property + def update_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], + Awaitable[gsma_online_return_policy.OnlineReturnPolicy]]: + r"""Return a callable for the update online return policy method over gRPC. + + Updates an existing return policy for a given + merchant. + + Returns: + Callable[[~.UpdateOnlineReturnPolicyRequest], + Awaitable[~.OnlineReturnPolicy]]: + 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 'update_online_return_policy' not in self._stubs: + self._stubs['update_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/UpdateOnlineReturnPolicy', + request_serializer=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.serialize, + response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, + ) + return self._stubs['update_online_return_policy'] + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete online return policy method over gRPC. + + Deletes an existing return policy. + + Returns: + Callable[[~.DeleteOnlineReturnPolicyRequest], + 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_online_return_policy' not in self._stubs: + self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', + request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_online_return_policy'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_online_return_policy: self._wrap_method( + self.get_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.list_online_return_policies: self._wrap_method( + self.list_online_return_policies, + default_timeout=None, + client_info=client_info, + ), + self.create_online_return_policy: self._wrap_method( + self.create_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.update_online_return_policy: self._wrap_method( + self.update_online_return_policy, + default_timeout=None, + client_info=client_info, + ), + self.delete_online_return_policy: self._wrap_method( + self.delete_online_return_policy, + 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__ = ( + 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py new file mode 100644 index 000000000000..e8dd549853b8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py @@ -0,0 +1,1009 @@ +# -*- 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_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy + + +from .rest_base import _BaseOnlineReturnPolicyServiceRestTransport +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 OnlineReturnPolicyServiceRestInterceptor: + """Interceptor for OnlineReturnPolicyService. + + 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 OnlineReturnPolicyServiceRestTransport. + + .. code-block:: python + class MyCustomOnlineReturnPolicyServiceInterceptor(OnlineReturnPolicyServiceRestInterceptor): + def pre_create_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_online_return_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_online_return_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_online_return_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_online_return_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_online_return_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_online_return_policy(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OnlineReturnPolicyServiceRestTransport(interceptor=MyCustomOnlineReturnPolicyServiceInterceptor()) + client = OnlineReturnPolicyServiceClient(transport=transport) + + + """ + def pre_create_online_return_policy(self, request: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_create_online_return_policy(self, response: gsma_online_return_policy.OnlineReturnPolicy) -> gsma_online_return_policy.OnlineReturnPolicy: + """Post-rpc interceptor for create_online_return_policy + + DEPRECATED. Please use the `post_create_online_return_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_create_online_return_policy` interceptor runs + before the `post_create_online_return_policy_with_metadata` interceptor. + """ + return response + + def post_create_online_return_policy_with_metadata(self, response: gsma_online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_online_return_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_create_online_return_policy_with_metadata` + interceptor in new development instead of the `post_create_online_return_policy` interceptor. + When both interceptors are used, this `post_create_online_return_policy_with_metadata` interceptor runs after the + `post_create_online_return_policy` interceptor. The (possibly modified) response returned by + `post_create_online_return_policy` will be passed to + `post_create_online_return_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_online_return_policy(self, request: online_return_policy.DeleteOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.DeleteOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def pre_get_online_return_policy(self, request: online_return_policy.GetOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_get_online_return_policy(self, response: online_return_policy.OnlineReturnPolicy) -> online_return_policy.OnlineReturnPolicy: + """Post-rpc interceptor for get_online_return_policy + + DEPRECATED. Please use the `post_get_online_return_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_get_online_return_policy` interceptor runs + before the `post_get_online_return_policy_with_metadata` interceptor. + """ + return response + + def post_get_online_return_policy_with_metadata(self, response: online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_online_return_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_get_online_return_policy_with_metadata` + interceptor in new development instead of the `post_get_online_return_policy` interceptor. + When both interceptors are used, this `post_get_online_return_policy_with_metadata` interceptor runs after the + `post_get_online_return_policy` interceptor. The (possibly modified) response returned by + `post_get_online_return_policy` will be passed to + `post_get_online_return_policy_with_metadata`. + """ + return response, metadata + + def pre_list_online_return_policies(self, request: online_return_policy.ListOnlineReturnPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_online_return_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_list_online_return_policies(self, response: online_return_policy.ListOnlineReturnPoliciesResponse) -> online_return_policy.ListOnlineReturnPoliciesResponse: + """Post-rpc interceptor for list_online_return_policies + + DEPRECATED. Please use the `post_list_online_return_policies_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_list_online_return_policies` interceptor runs + before the `post_list_online_return_policies_with_metadata` interceptor. + """ + return response + + def post_list_online_return_policies_with_metadata(self, response: online_return_policy.ListOnlineReturnPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_online_return_policies + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_list_online_return_policies_with_metadata` + interceptor in new development instead of the `post_list_online_return_policies` interceptor. + When both interceptors are used, this `post_list_online_return_policies_with_metadata` interceptor runs after the + `post_list_online_return_policies` interceptor. The (possibly modified) response returned by + `post_list_online_return_policies` will be passed to + `post_list_online_return_policies_with_metadata`. + """ + return response, metadata + + def pre_update_online_return_policy(self, request: gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_online_return_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the OnlineReturnPolicyService server. + """ + return request, metadata + + def post_update_online_return_policy(self, response: gsma_online_return_policy.OnlineReturnPolicy) -> gsma_online_return_policy.OnlineReturnPolicy: + """Post-rpc interceptor for update_online_return_policy + + DEPRECATED. Please use the `post_update_online_return_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OnlineReturnPolicyService server but before + it is returned to user code. This `post_update_online_return_policy` interceptor runs + before the `post_update_online_return_policy_with_metadata` interceptor. + """ + return response + + def post_update_online_return_policy_with_metadata(self, response: gsma_online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_online_return_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OnlineReturnPolicyService server but before it is returned to user code. + + We recommend only using this `post_update_online_return_policy_with_metadata` + interceptor in new development instead of the `post_update_online_return_policy` interceptor. + When both interceptors are used, this `post_update_online_return_policy_with_metadata` interceptor runs after the + `post_update_online_return_policy` interceptor. The (possibly modified) response returned by + `post_update_online_return_policy` will be passed to + `post_update_online_return_policy_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class OnlineReturnPolicyServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OnlineReturnPolicyServiceRestInterceptor + + +class OnlineReturnPolicyServiceRestTransport(_BaseOnlineReturnPolicyServiceRestTransport): + """REST backend synchronous transport for OnlineReturnPolicyService. + + The service facilitates the management of a merchant's remorse + return policy configuration, encompassing return policies for both + ads and free listings + + programs. This API defines the following resource model: + -------------------------------------------------------- + + `OnlineReturnPolicy `__ + + 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[OnlineReturnPolicyServiceRestInterceptor] = 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 OnlineReturnPolicyServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.CreateOnlineReturnPolicy") + + @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: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Call the create online return + policy method over HTTP. + + Args: + request (~.gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + 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: + ~.gsma_online_return_policy.OnlineReturnPolicy: + `Online return + policy `__ + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_create_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_transcoded_request(http_options, request) + + body = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.CreateOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "CreateOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._CreateOnlineReturnPolicy._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 = gsma_online_return_policy.OnlineReturnPolicy() + pb_resp = gsma_online_return_policy.OnlineReturnPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_online_return_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_online_return_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_online_return_policy.OnlineReturnPolicy.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.accounts_v1beta.OnlineReturnPolicyServiceClient.create_online_return_policy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "CreateOnlineReturnPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.DeleteOnlineReturnPolicy") + + @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: online_return_policy.DeleteOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete online return + policy method over HTTP. + + Args: + request (~.online_return_policy.DeleteOnlineReturnPolicyRequest): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_delete_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.DeleteOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "DeleteOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._DeleteOnlineReturnPolicy._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 _GetOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.GetOnlineReturnPolicy") + + @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: online_return_policy.GetOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> online_return_policy.OnlineReturnPolicy: + r"""Call the get online return policy method over HTTP. + + Args: + request (~.online_return_policy.GetOnlineReturnPolicyRequest): + The request object. Request message for the ``GetOnlineReturnPolicy`` + 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: + ~.online_return_policy.OnlineReturnPolicy: + `Online return + policy `__ + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.GetOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "GetOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._GetOnlineReturnPolicy._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 = online_return_policy.OnlineReturnPolicy() + pb_resp = online_return_policy.OnlineReturnPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_online_return_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_online_return_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = online_return_policy.OnlineReturnPolicy.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.accounts_v1beta.OnlineReturnPolicyServiceClient.get_online_return_policy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "GetOnlineReturnPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListOnlineReturnPolicies(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.ListOnlineReturnPolicies") + + @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: online_return_policy.ListOnlineReturnPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> online_return_policy.ListOnlineReturnPoliciesResponse: + r"""Call the list online return + policies method over HTTP. + + Args: + request (~.online_return_policy.ListOnlineReturnPoliciesRequest): + The request object. Request message for the ``ListOnlineReturnPolicies`` + 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: + ~.online_return_policy.ListOnlineReturnPoliciesResponse: + Response message for the ``ListOnlineReturnPolicies`` + method. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_http_options() + + request, metadata = self._interceptor.pre_list_online_return_policies(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.ListOnlineReturnPolicies", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "ListOnlineReturnPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._ListOnlineReturnPolicies._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 = online_return_policy.ListOnlineReturnPoliciesResponse() + pb_resp = online_return_policy.ListOnlineReturnPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_online_return_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_online_return_policies_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = online_return_policy.ListOnlineReturnPoliciesResponse.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.accounts_v1beta.OnlineReturnPolicyServiceClient.list_online_return_policies", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "ListOnlineReturnPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + def __hash__(self): + return hash("OnlineReturnPolicyServiceRestTransport.UpdateOnlineReturnPolicy") + + @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: gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_online_return_policy.OnlineReturnPolicy: + r"""Call the update online return + policy method over HTTP. + + Args: + request (~.gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): + The request object. Request message for the ``UpdateOnlineReturnPolicy`` + method. The method supports field masks and when the + mask is provided, only the fields specified in the mask + are updated. + 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: + ~.gsma_online_return_policy.OnlineReturnPolicy: + `Online return + policy `__ + object. This is currently used to represent return + policies for ads and free listings programs. + + """ + + http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_http_options() + + request, metadata = self._interceptor.pre_update_online_return_policy(request, metadata) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_transcoded_request(http_options, request) + + body = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.UpdateOnlineReturnPolicy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "UpdateOnlineReturnPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OnlineReturnPolicyServiceRestTransport._UpdateOnlineReturnPolicy._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 = gsma_online_return_policy.OnlineReturnPolicy() + pb_resp = gsma_online_return_policy.OnlineReturnPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_online_return_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_online_return_policy_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_online_return_policy.OnlineReturnPolicy.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.accounts_v1beta.OnlineReturnPolicyServiceClient.update_online_return_policy", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "rpcName": "UpdateOnlineReturnPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy]: + # 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._CreateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_online_return_policy(self) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + 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._DeleteOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_online_return_policy(self) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + online_return_policy.OnlineReturnPolicy]: + # 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._GetOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_online_return_policies(self) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + online_return_policy.ListOnlineReturnPoliciesResponse]: + # 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._ListOnlineReturnPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_online_return_policy(self) -> Callable[ + [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy]: + # 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._UpdateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'OnlineReturnPolicyServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py new file mode 100644 index 000000000000..58371e3cbd32 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py @@ -0,0 +1,298 @@ +# -*- 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 OnlineReturnPolicyServiceTransport, 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_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy + + +class _BaseOnlineReturnPolicyServiceRestTransport(OnlineReturnPolicyServiceTransport): + """Base REST backend transport for OnlineReturnPolicyService. + + 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 _BaseCreateOnlineReturnPolicy: + 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': '/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies', + 'body': 'online_return_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteOnlineReturnPolicy: + 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': '/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = online_return_policy.DeleteOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetOnlineReturnPolicy: + 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': '/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = online_return_policy.GetOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListOnlineReturnPolicies: + 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': '/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = online_return_policy.ListOnlineReturnPoliciesRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateOnlineReturnPolicy: + 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': 'patch', + 'uri': '/accounts/v1beta/{online_return_policy.name=accounts/*/onlineReturnPolicies/*}', + 'body': 'online_return_policy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseOnlineReturnPolicyServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py new file mode 100644 index 000000000000..400e3ec082c8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_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 ProgramsServiceClient +from .async_client import ProgramsServiceAsyncClient + +__all__ = ( + 'ProgramsServiceClient', + 'ProgramsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py new file mode 100644 index 000000000000..3be254a282c6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py @@ -0,0 +1,740 @@ +# -*- 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_accounts_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_accounts_v1beta.services.programs_service import pagers +from google.shopping.merchant_accounts_v1beta.types import programs +from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport +from .client import ProgramsServiceClient + +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 ProgramsServiceAsyncClient: + """Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a merchant's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + """ + + _client: ProgramsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ProgramsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ProgramsServiceClient._DEFAULT_UNIVERSE + + program_path = staticmethod(ProgramsServiceClient.program_path) + parse_program_path = staticmethod(ProgramsServiceClient.parse_program_path) + common_billing_account_path = staticmethod(ProgramsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProgramsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProgramsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ProgramsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ProgramsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ProgramsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ProgramsServiceClient.common_project_path) + parse_common_project_path = staticmethod(ProgramsServiceClient.parse_common_project_path) + common_location_path = staticmethod(ProgramsServiceClient.common_location_path) + parse_common_location_path = staticmethod(ProgramsServiceClient.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: + ProgramsServiceAsyncClient: The constructed client. + """ + return ProgramsServiceClient.from_service_account_info.__func__(ProgramsServiceAsyncClient, 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: + ProgramsServiceAsyncClient: The constructed client. + """ + return ProgramsServiceClient.from_service_account_file.__func__(ProgramsServiceAsyncClient, 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 ProgramsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProgramsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProgramsServiceTransport: 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 = ProgramsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the programs 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,ProgramsServiceTransport,Callable[..., ProgramsServiceTransport]]]): + 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 ProgramsServiceTransport 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 = ProgramsServiceClient( + 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.accounts_v1beta.ProgramsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "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.accounts.v1beta.ProgramsService", + "credentialsType": None, + } + ) + + async def get_program(self, + request: Optional[Union[programs.GetProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Retrieves the specified program for the 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_accounts_v1beta + + async def sample_get_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.get_program(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetProgramRequest, dict]]): + The request object. Request message for the GetProgram + method. + name (:class:`str`): + Required. The name of the program to retrieve. Format: + ``accounts/{account}/programs/{program}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to merchant accounts. A typical example of this is + the [Free product + listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) + program, which enables products from a merchant's + store to be shown across Google for free. + + """ + # 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, programs.GetProgramRequest): + request = programs.GetProgramRequest(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.get_program] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_programs(self, + request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsAsyncPager: + r"""Retrieves all programs for the 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_accounts_v1beta + + async def sample_list_programs(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest, dict]]): + The request object. Request message for the ListPrograms + method. + parent (:class:`str`): + Required. The name of the account for which to retrieve + all programs. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.programs_service.pagers.ListProgramsAsyncPager: + Response message for the ListPrograms + 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, programs.ListProgramsRequest): + request = programs.ListProgramsRequest(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_programs] + + # 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.ListProgramsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def enable_program(self, + request: Optional[Union[programs.EnableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Enable participation in the specified program for the + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_enable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.enable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest, dict]]): + The request object. Request message for the EnableProgram + method. + name (:class:`str`): + Required. The name of the program for which to enable + participation for the given account. Format: + ``accounts/{account}/programs/{program}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to merchant accounts. A typical example of this is + the [Free product + listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) + program, which enables products from a merchant's + store to be shown across Google for free. + + """ + # 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, programs.EnableProgramRequest): + request = programs.EnableProgramRequest(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.enable_program] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def disable_program(self, + request: Optional[Union[programs.DisableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Disable participation in the specified program for + the account. Executing this method requires admin + access. + + .. 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_accounts_v1beta + + async def sample_disable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.disable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest, dict]]): + The request object. Request message for the + DisableProgram method. + name (:class:`str`): + Required. The name of the program for which to disable + participation for the given account. Format: + ``accounts/{account}/programs/{program}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to merchant accounts. A typical example of this is + the [Free product + listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) + program, which enables products from a merchant's + store to be shown across Google for free. + + """ + # 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, programs.DisableProgramRequest): + request = programs.DisableProgramRequest(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.disable_program] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ProgramsServiceAsyncClient": + 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__ = ( + "ProgramsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py new file mode 100644 index 000000000000..8a5514d19412 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py @@ -0,0 +1,1097 @@ +# -*- 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_accounts_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_accounts_v1beta.services.programs_service import pagers +from google.shopping.merchant_accounts_v1beta.types import programs +from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProgramsServiceGrpcTransport +from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport +from .transports.rest import ProgramsServiceRestTransport + + +class ProgramsServiceClientMeta(type): + """Metaclass for the ProgramsService 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[ProgramsServiceTransport]] + _transport_registry["grpc"] = ProgramsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ProgramsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ProgramsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProgramsServiceTransport]: + """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 ProgramsServiceClient(metaclass=ProgramsServiceClientMeta): + """Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a merchant's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + """ + + @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: + ProgramsServiceClient: 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: + ProgramsServiceClient: 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) -> ProgramsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ProgramsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def program_path(account: str,program: str,) -> str: + """Returns a fully-qualified program string.""" + return "accounts/{account}/programs/{program}".format(account=account, program=program, ) + + @staticmethod + def parse_program_path(path: str) -> Dict[str,str]: + """Parses a program path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/programs/(?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 = ProgramsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ProgramsServiceClient._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 = ProgramsServiceClient._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, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the programs 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,ProgramsServiceTransport,Callable[..., ProgramsServiceTransport]]]): + 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 ProgramsServiceTransport 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 = ProgramsServiceClient._read_environment_variables() + self._client_cert_source = ProgramsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ProgramsServiceClient._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, ProgramsServiceTransport) + if transport_provided: + # transport is a ProgramsServiceTransport 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(ProgramsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ProgramsServiceClient._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[ProgramsServiceTransport], Callable[..., ProgramsServiceTransport]] = ( + ProgramsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProgramsServiceTransport], 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.accounts_v1beta.ProgramsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "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.accounts.v1beta.ProgramsService", + "credentialsType": None, + } + ) + + def get_program(self, + request: Optional[Union[programs.GetProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Retrieves the specified program for the 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_accounts_v1beta + + def sample_get_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = client.get_program(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetProgramRequest, dict]): + The request object. Request message for the GetProgram + method. + name (str): + Required. The name of the program to retrieve. Format: + ``accounts/{account}/programs/{program}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to merchant accounts. A typical example of this is + the [Free product + listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) + program, which enables products from a merchant's + store to be shown across Google for free. + + """ + # 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, programs.GetProgramRequest): + request = programs.GetProgramRequest(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.get_program] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_programs(self, + request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsPager: + r"""Retrieves all programs for the 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_accounts_v1beta + + def sample_list_programs(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest, dict]): + The request object. Request message for the ListPrograms + method. + parent (str): + Required. The name of the account for which to retrieve + all programs. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.programs_service.pagers.ListProgramsPager: + Response message for the ListPrograms + 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, programs.ListProgramsRequest): + request = programs.ListProgramsRequest(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_programs] + + # 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.ListProgramsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def enable_program(self, + request: Optional[Union[programs.EnableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Enable participation in the specified program for the + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + def sample_enable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.enable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest, dict]): + The request object. Request message for the EnableProgram + method. + name (str): + Required. The name of the program for which to enable + participation for the given account. Format: + ``accounts/{account}/programs/{program}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to merchant accounts. A typical example of this is + the [Free product + listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) + program, which enables products from a merchant's + store to be shown across Google for free. + + """ + # 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, programs.EnableProgramRequest): + request = programs.EnableProgramRequest(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.enable_program] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def disable_program(self, + request: Optional[Union[programs.DisableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: + r"""Disable participation in the specified program for + the account. Executing this method requires admin + access. + + .. 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_accounts_v1beta + + def sample_disable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.disable_program(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest, dict]): + The request object. Request message for the + DisableProgram method. + name (str): + Required. The name of the program for which to disable + participation for the given account. Format: + ``accounts/{account}/programs/{program}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality + to merchant accounts. A typical example of this is + the [Free product + listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) + program, which enables products from a merchant's + store to be shown across Google for free. + + """ + # 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, programs.DisableProgramRequest): + request = programs.DisableProgramRequest(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.disable_program] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProgramsServiceClient": + 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__ = ( + "ProgramsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py new file mode 100644 index 000000000000..640983cf175e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_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_accounts_v1beta.types import programs + + +class ListProgramsPager: + """A pager for iterating through ``list_programs`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``programs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPrograms`` requests and continue to iterate + through the ``programs`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` + 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[..., programs.ListProgramsResponse], + request: programs.ListProgramsRequest, + response: programs.ListProgramsResponse, + *, + 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_accounts_v1beta.types.ListProgramsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse): + 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 = programs.ListProgramsRequest(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[programs.ListProgramsResponse]: + 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[programs.Program]: + for page in self.pages: + yield from page.programs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListProgramsAsyncPager: + """A pager for iterating through ``list_programs`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``programs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPrograms`` requests and continue to iterate + through the ``programs`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` + 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[programs.ListProgramsResponse]], + request: programs.ListProgramsRequest, + response: programs.ListProgramsResponse, + *, + 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_accounts_v1beta.types.ListProgramsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse): + 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 = programs.ListProgramsRequest(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[programs.ListProgramsResponse]: + 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[programs.Program]: + async def async_generator(): + async for page in self.pages: + for response in page.programs: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst new file mode 100644 index 000000000000..b36d6af5aeda --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ProgramsServiceTransport` is the ABC for all transports. +- public child `ProgramsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ProgramsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseProgramsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ProgramsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py new file mode 100644 index 000000000000..dc803437b5a1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_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 ProgramsServiceTransport +from .grpc import ProgramsServiceGrpcTransport +from .grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport +from .rest import ProgramsServiceRestTransport +from .rest import ProgramsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProgramsServiceTransport]] +_transport_registry['grpc'] = ProgramsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ProgramsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ProgramsServiceRestTransport + +__all__ = ( + 'ProgramsServiceTransport', + 'ProgramsServiceGrpcTransport', + 'ProgramsServiceGrpcAsyncIOTransport', + 'ProgramsServiceRestTransport', + 'ProgramsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py new file mode 100644 index 000000000000..d32f143bd271 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py @@ -0,0 +1,201 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import programs + +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 ProgramsServiceTransport(abc.ABC): + """Abstract transport class for ProgramsService.""" + + 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.get_program: gapic_v1.method.wrap_method( + self.get_program, + default_timeout=None, + client_info=client_info, + ), + self.list_programs: gapic_v1.method.wrap_method( + self.list_programs, + default_timeout=None, + client_info=client_info, + ), + self.enable_program: gapic_v1.method.wrap_method( + self.enable_program, + default_timeout=None, + client_info=client_info, + ), + self.disable_program: gapic_v1.method.wrap_method( + self.disable_program, + 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 get_program(self) -> Callable[ + [programs.GetProgramRequest], + Union[ + programs.Program, + Awaitable[programs.Program] + ]]: + raise NotImplementedError() + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + Union[ + programs.ListProgramsResponse, + Awaitable[programs.ListProgramsResponse] + ]]: + raise NotImplementedError() + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + Union[ + programs.Program, + Awaitable[programs.Program] + ]]: + raise NotImplementedError() + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + Union[ + programs.Program, + Awaitable[programs.Program] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ProgramsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py new file mode 100644 index 000000000000..d6654539650f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py @@ -0,0 +1,437 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import programs +from .base import ProgramsServiceTransport, 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.accounts.v1beta.ProgramsService", + "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.accounts.v1beta.ProgramsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ProgramsServiceGrpcTransport(ProgramsServiceTransport): + """gRPC backend transport for ProgramsService. + + Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a merchant's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + + 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 get_program(self) -> Callable[ + [programs.GetProgramRequest], + programs.Program]: + r"""Return a callable for the get program method over gRPC. + + Retrieves the specified program for the account. + + Returns: + Callable[[~.GetProgramRequest], + ~.Program]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_program' not in self._stubs: + self._stubs['get_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/GetProgram', + request_serializer=programs.GetProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['get_program'] + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + programs.ListProgramsResponse]: + r"""Return a callable for the list programs method over gRPC. + + Retrieves all programs for the account. + + Returns: + Callable[[~.ListProgramsRequest], + ~.ListProgramsResponse]: + 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_programs' not in self._stubs: + self._stubs['list_programs'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/ListPrograms', + request_serializer=programs.ListProgramsRequest.serialize, + response_deserializer=programs.ListProgramsResponse.deserialize, + ) + return self._stubs['list_programs'] + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + programs.Program]: + r"""Return a callable for the enable program method over gRPC. + + Enable participation in the specified program for the + account. Executing this method requires admin access. + + Returns: + Callable[[~.EnableProgramRequest], + ~.Program]: + 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 'enable_program' not in self._stubs: + self._stubs['enable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/EnableProgram', + request_serializer=programs.EnableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['enable_program'] + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + programs.Program]: + r"""Return a callable for the disable program method over gRPC. + + Disable participation in the specified program for + the account. Executing this method requires admin + access. + + Returns: + Callable[[~.DisableProgramRequest], + ~.Program]: + 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 'disable_program' not in self._stubs: + self._stubs['disable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/DisableProgram', + request_serializer=programs.DisableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['disable_program'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProgramsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..83fe0e73dc07 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py @@ -0,0 +1,473 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import programs +from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ProgramsServiceGrpcTransport + +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.accounts.v1beta.ProgramsService", + "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.accounts.v1beta.ProgramsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ProgramsServiceGrpcAsyncIOTransport(ProgramsServiceTransport): + """gRPC AsyncIO backend transport for ProgramsService. + + Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a merchant's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + + 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 get_program(self) -> Callable[ + [programs.GetProgramRequest], + Awaitable[programs.Program]]: + r"""Return a callable for the get program method over gRPC. + + Retrieves the specified program for the account. + + Returns: + Callable[[~.GetProgramRequest], + Awaitable[~.Program]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_program' not in self._stubs: + self._stubs['get_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/GetProgram', + request_serializer=programs.GetProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['get_program'] + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + Awaitable[programs.ListProgramsResponse]]: + r"""Return a callable for the list programs method over gRPC. + + Retrieves all programs for the account. + + Returns: + Callable[[~.ListProgramsRequest], + Awaitable[~.ListProgramsResponse]]: + 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_programs' not in self._stubs: + self._stubs['list_programs'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/ListPrograms', + request_serializer=programs.ListProgramsRequest.serialize, + response_deserializer=programs.ListProgramsResponse.deserialize, + ) + return self._stubs['list_programs'] + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + Awaitable[programs.Program]]: + r"""Return a callable for the enable program method over gRPC. + + Enable participation in the specified program for the + account. Executing this method requires admin access. + + Returns: + Callable[[~.EnableProgramRequest], + Awaitable[~.Program]]: + 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 'enable_program' not in self._stubs: + self._stubs['enable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/EnableProgram', + request_serializer=programs.EnableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['enable_program'] + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + Awaitable[programs.Program]]: + r"""Return a callable for the disable program method over gRPC. + + Disable participation in the specified program for + the account. Executing this method requires admin + access. + + Returns: + Callable[[~.DisableProgramRequest], + Awaitable[~.Program]]: + 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 'disable_program' not in self._stubs: + self._stubs['disable_program'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ProgramsService/DisableProgram', + request_serializer=programs.DisableProgramRequest.serialize, + response_deserializer=programs.Program.deserialize, + ) + return self._stubs['disable_program'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_program: self._wrap_method( + self.get_program, + default_timeout=None, + client_info=client_info, + ), + self.list_programs: self._wrap_method( + self.list_programs, + default_timeout=None, + client_info=client_info, + ), + self.enable_program: self._wrap_method( + self.enable_program, + default_timeout=None, + client_info=client_info, + ), + self.disable_program: self._wrap_method( + self.disable_program, + 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__ = ( + 'ProgramsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py new file mode 100644 index 000000000000..6ed479278432 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py @@ -0,0 +1,913 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import programs + + +from .rest_base import _BaseProgramsServiceRestTransport +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 ProgramsServiceRestInterceptor: + """Interceptor for ProgramsService. + + 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 ProgramsServiceRestTransport. + + .. code-block:: python + class MyCustomProgramsServiceInterceptor(ProgramsServiceRestInterceptor): + def pre_disable_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_disable_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_enable_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_program(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_program(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_programs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_programs(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProgramsServiceRestTransport(interceptor=MyCustomProgramsServiceInterceptor()) + client = ProgramsServiceClient(transport=transport) + + + """ + def pre_disable_program(self, request: programs.DisableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for disable_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_disable_program(self, response: programs.Program) -> programs.Program: + """Post-rpc interceptor for disable_program + + DEPRECATED. Please use the `post_disable_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_disable_program` interceptor runs + before the `post_disable_program_with_metadata` interceptor. + """ + return response + + def post_disable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for disable_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_disable_program_with_metadata` + interceptor in new development instead of the `post_disable_program` interceptor. + When both interceptors are used, this `post_disable_program_with_metadata` interceptor runs after the + `post_disable_program` interceptor. The (possibly modified) response returned by + `post_disable_program` will be passed to + `post_disable_program_with_metadata`. + """ + return response, metadata + + def pre_enable_program(self, request: programs.EnableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for enable_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_enable_program(self, response: programs.Program) -> programs.Program: + """Post-rpc interceptor for enable_program + + DEPRECATED. Please use the `post_enable_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_enable_program` interceptor runs + before the `post_enable_program_with_metadata` interceptor. + """ + return response + + def post_enable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for enable_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_enable_program_with_metadata` + interceptor in new development instead of the `post_enable_program` interceptor. + When both interceptors are used, this `post_enable_program_with_metadata` interceptor runs after the + `post_enable_program` interceptor. The (possibly modified) response returned by + `post_enable_program` will be passed to + `post_enable_program_with_metadata`. + """ + return response, metadata + + def pre_get_program(self, request: programs.GetProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_program + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_get_program(self, response: programs.Program) -> programs.Program: + """Post-rpc interceptor for get_program + + DEPRECATED. Please use the `post_get_program_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_get_program` interceptor runs + before the `post_get_program_with_metadata` interceptor. + """ + return response + + def post_get_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_program + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_get_program_with_metadata` + interceptor in new development instead of the `post_get_program` interceptor. + When both interceptors are used, this `post_get_program_with_metadata` interceptor runs after the + `post_get_program` interceptor. The (possibly modified) response returned by + `post_get_program` will be passed to + `post_get_program_with_metadata`. + """ + return response, metadata + + def pre_list_programs(self, request: programs.ListProgramsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_programs + + Override in a subclass to manipulate the request or metadata + before they are sent to the ProgramsService server. + """ + return request, metadata + + def post_list_programs(self, response: programs.ListProgramsResponse) -> programs.ListProgramsResponse: + """Post-rpc interceptor for list_programs + + DEPRECATED. Please use the `post_list_programs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ProgramsService server but before + it is returned to user code. This `post_list_programs` interceptor runs + before the `post_list_programs_with_metadata` interceptor. + """ + return response + + def post_list_programs_with_metadata(self, response: programs.ListProgramsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_programs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ProgramsService server but before it is returned to user code. + + We recommend only using this `post_list_programs_with_metadata` + interceptor in new development instead of the `post_list_programs` interceptor. + When both interceptors are used, this `post_list_programs_with_metadata` interceptor runs after the + `post_list_programs` interceptor. The (possibly modified) response returned by + `post_list_programs` will be passed to + `post_list_programs_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ProgramsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProgramsServiceRestInterceptor + + +class ProgramsServiceRestTransport(_BaseProgramsServiceRestTransport): + """REST backend synchronous transport for ProgramsService. + + Service for program management. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + This service exposes methods to retrieve a merchant's participation + in all available programs, in addition to methods for explicitly + enabling or disabling participation in each program. + + 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[ProgramsServiceRestInterceptor] = 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 ProgramsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _DisableProgram(_BaseProgramsServiceRestTransport._BaseDisableProgram, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.DisableProgram") + + @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: programs.DisableProgramRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.Program: + r"""Call the disable program method over HTTP. + + Args: + request (~.programs.DisableProgramRequest): + The request object. Request message for the + DisableProgram 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: + ~.programs.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality to + merchant accounts. A typical example of this is the + `Free product + listings `__ + program, which enables products from a merchant's store + to be shown across Google for free. + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_http_options() + + request, metadata = self._interceptor.pre_disable_program(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_transcoded_request(http_options, request) + + body = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.DisableProgram", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "DisableProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._DisableProgram._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 = programs.Program() + pb_resp = programs.Program.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_disable_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_disable_program_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.Program.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.accounts_v1beta.ProgramsServiceClient.disable_program", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "DisableProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _EnableProgram(_BaseProgramsServiceRestTransport._BaseEnableProgram, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.EnableProgram") + + @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: programs.EnableProgramRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.Program: + r"""Call the enable program method over HTTP. + + Args: + request (~.programs.EnableProgramRequest): + The request object. Request message for the EnableProgram + 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: + ~.programs.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality to + merchant accounts. A typical example of this is the + `Free product + listings `__ + program, which enables products from a merchant's store + to be shown across Google for free. + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_http_options() + + request, metadata = self._interceptor.pre_enable_program(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_transcoded_request(http_options, request) + + body = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.EnableProgram", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "EnableProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._EnableProgram._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 = programs.Program() + pb_resp = programs.Program.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_enable_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_enable_program_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.Program.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.accounts_v1beta.ProgramsServiceClient.enable_program", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "EnableProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetProgram(_BaseProgramsServiceRestTransport._BaseGetProgram, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.GetProgram") + + @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: programs.GetProgramRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.Program: + r"""Call the get program method over HTTP. + + Args: + request (~.programs.GetProgramRequest): + The request object. Request message for the GetProgram + 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: + ~.programs.Program: + Defines participation in a given program for the + specified account. + + Programs provide a mechanism for adding functionality to + merchant accounts. A typical example of this is the + `Free product + listings `__ + program, which enables products from a merchant's store + to be shown across Google for free. + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseGetProgram._get_http_options() + + request, metadata = self._interceptor.pre_get_program(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseGetProgram._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseGetProgram._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.GetProgram", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "GetProgram", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._GetProgram._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 = programs.Program() + pb_resp = programs.Program.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_program(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_program_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.Program.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.accounts_v1beta.ProgramsServiceClient.get_program", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "GetProgram", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPrograms(_BaseProgramsServiceRestTransport._BaseListPrograms, ProgramsServiceRestStub): + def __hash__(self): + return hash("ProgramsServiceRestTransport.ListPrograms") + + @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: programs.ListProgramsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> programs.ListProgramsResponse: + r"""Call the list programs method over HTTP. + + Args: + request (~.programs.ListProgramsRequest): + The request object. Request message for the ListPrograms + 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: + ~.programs.ListProgramsResponse: + Response message for the ListPrograms + method. + + """ + + http_options = _BaseProgramsServiceRestTransport._BaseListPrograms._get_http_options() + + request, metadata = self._interceptor.pre_list_programs(request, metadata) + transcoded_request = _BaseProgramsServiceRestTransport._BaseListPrograms._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseProgramsServiceRestTransport._BaseListPrograms._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.ListPrograms", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "ListPrograms", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProgramsServiceRestTransport._ListPrograms._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 = programs.ListProgramsResponse() + pb_resp = programs.ListProgramsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_programs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_programs_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = programs.ListProgramsResponse.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.accounts_v1beta.ProgramsServiceClient.list_programs", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "rpcName": "ListPrograms", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def disable_program(self) -> Callable[ + [programs.DisableProgramRequest], + programs.Program]: + # 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._DisableProgram(self._session, self._host, self._interceptor) # type: ignore + + @property + def enable_program(self) -> Callable[ + [programs.EnableProgramRequest], + programs.Program]: + # 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._EnableProgram(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_program(self) -> Callable[ + [programs.GetProgramRequest], + programs.Program]: + # 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._GetProgram(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_programs(self) -> Callable[ + [programs.ListProgramsRequest], + programs.ListProgramsResponse]: + # 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._ListPrograms(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ProgramsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py new file mode 100644 index 000000000000..5365133a004b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py @@ -0,0 +1,259 @@ +# -*- 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 ProgramsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import programs + + +class _BaseProgramsServiceRestTransport(ProgramsServiceTransport): + """Base REST backend transport for ProgramsService. + + 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 _BaseDisableProgram: + 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': '/accounts/v1beta/{name=accounts/*/programs/*}:disable', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.DisableProgramRequest.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(_BaseProgramsServiceRestTransport._BaseDisableProgram._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEnableProgram: + 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': '/accounts/v1beta/{name=accounts/*/programs/*}:enable', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.EnableProgramRequest.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(_BaseProgramsServiceRestTransport._BaseEnableProgram._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetProgram: + 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': '/accounts/v1beta/{name=accounts/*/programs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.GetProgramRequest.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(_BaseProgramsServiceRestTransport._BaseGetProgram._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPrograms: + 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': '/accounts/v1beta/{parent=accounts/*}/programs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = programs.ListProgramsRequest.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(_BaseProgramsServiceRestTransport._BaseListPrograms._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseProgramsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/__init__.py new file mode 100644 index 000000000000..4809e9fed9f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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 RegionsServiceClient +from .async_client import RegionsServiceAsyncClient + +__all__ = ( + 'RegionsServiceClient', + 'RegionsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py new file mode 100644 index 000000000000..15b74ad96d1b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py @@ -0,0 +1,847 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.regions_service import pagers +from google.shopping.merchant_accounts_v1beta.types import regions +from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport +from .client import RegionsServiceClient + +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 RegionsServiceAsyncClient: + """Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1main.Region] + """ + + _client: RegionsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RegionsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RegionsServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(RegionsServiceClient.account_path) + parse_account_path = staticmethod(RegionsServiceClient.parse_account_path) + region_path = staticmethod(RegionsServiceClient.region_path) + parse_region_path = staticmethod(RegionsServiceClient.parse_region_path) + common_billing_account_path = staticmethod(RegionsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegionsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegionsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RegionsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RegionsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RegionsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RegionsServiceClient.common_project_path) + parse_common_project_path = staticmethod(RegionsServiceClient.parse_common_project_path) + common_location_path = staticmethod(RegionsServiceClient.common_location_path) + parse_common_location_path = staticmethod(RegionsServiceClient.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: + RegionsServiceAsyncClient: The constructed client. + """ + return RegionsServiceClient.from_service_account_info.__func__(RegionsServiceAsyncClient, 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: + RegionsServiceAsyncClient: The constructed client. + """ + return RegionsServiceClient.from_service_account_file.__func__(RegionsServiceAsyncClient, 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 RegionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RegionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionsServiceTransport: 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 = RegionsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regions 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,RegionsServiceTransport,Callable[..., RegionsServiceTransport]]]): + 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 RegionsServiceTransport 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 = RegionsServiceClient( + 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.accounts_v1beta.RegionsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "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.accounts.v1beta.RegionsService", + "credentialsType": None, + } + ) + + async def get_region(self, + request: Optional[Union[regions.GetRegionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Retrieves a region defined in your Merchant Center + 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_accounts_v1beta + + async def sample_get_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_region(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetRegionRequest, dict]]): + The request object. Request message for the ``GetRegion`` method. + name (:class:`str`): + Required. The name of the region to retrieve. Format: + ``accounts/{account}/regions/{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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, regions.GetRegionRequest): + request = regions.GetRegionRequest(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.get_region] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_region(self, + request: Optional[Union[regions.CreateRegionRequest, dict]] = None, + *, + parent: Optional[str] = None, + region: Optional[regions.Region] = None, + region_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_create_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = await client.create_region(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest, dict]]): + The request object. Request message for the ``CreateRegion`` method. + parent (:class:`str`): + Required. The account to create a region for. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (:class:`google.shopping.merchant_accounts_v1beta.types.Region`): + Required. The region to create. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_id (:class:`str`): + Required. The identifier for the + region, unique over all regions of the + same account. + + This corresponds to the ``region_id`` 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_accounts_v1beta.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, region, region_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.CreateRegionRequest): + request = regions.CreateRegionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if region is not None: + request.region = region + if region_id is not None: + request.region_id = region_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_region] + + # 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 update_region(self, + request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, + *, + region: Optional[regions.Region] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_update_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateRegionRequest( + ) + + # Make the request + response = await client.update_region(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest, dict]]): + The request object. Request message for the ``UpdateRegion`` method. + region (:class:`google.shopping.merchant_accounts_v1beta.types.Region`): + Required. The updated region. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The comma-separated field mask indicating the + fields to update. Example: + ``"displayName,postalCodeArea.regionCode"``. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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 = [region, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.UpdateRegionRequest): + request = regions.UpdateRegionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if region is not None: + request.region = region + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_region] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("region.name", request.region.name), + )), + ) + + # 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_region(self, + request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, + *, + name: 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 a region definition from your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_delete_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + await client.delete_region(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest, dict]]): + The request object. Request message for the ``DeleteRegion`` method. + name (:class:`str`): + Required. The name of the region to delete. Format: + ``accounts/{account}/regions/{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, regions.DeleteRegionRequest): + request = regions.DeleteRegionRequest(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_region] + + # 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 list_regions(self, + request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsAsyncPager: + r"""Lists the regions in your Merchant Center 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_accounts_v1beta + + async def sample_list_regions(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest, dict]]): + The request object. Request message for the ``ListRegions`` method. + parent (:class:`str`): + Required. The account to list regions for. Format: + ``accounts/{account}`` + + 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_accounts_v1beta.services.regions_service.pagers.ListRegionsAsyncPager: + Response message for the ListRegions 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, regions.ListRegionsRequest): + request = regions.ListRegionsRequest(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_regions] + + # 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.ListRegionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RegionsServiceAsyncClient": + 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__ = ( + "RegionsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py new file mode 100644 index 000000000000..a3ef9c4bec4f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py @@ -0,0 +1,1212 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.regions_service import pagers +from google.shopping.merchant_accounts_v1beta.types import regions +from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegionsServiceGrpcTransport +from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport +from .transports.rest import RegionsServiceRestTransport + + +class RegionsServiceClientMeta(type): + """Metaclass for the RegionsService 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[RegionsServiceTransport]] + _transport_registry["grpc"] = RegionsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegionsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RegionsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RegionsServiceTransport]: + """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 RegionsServiceClient(metaclass=RegionsServiceClientMeta): + """Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1main.Region] + """ + + @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: + RegionsServiceClient: 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: + RegionsServiceClient: 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) -> RegionsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RegionsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def region_path(account: str,region: str,) -> str: + """Returns a fully-qualified region string.""" + return "accounts/{account}/regions/{region}".format(account=account, region=region, ) + + @staticmethod + def parse_region_path(path: str) -> Dict[str,str]: + """Parses a region path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/regions/(?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 = RegionsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RegionsServiceClient._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 = RegionsServiceClient._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, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the regions 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,RegionsServiceTransport,Callable[..., RegionsServiceTransport]]]): + 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 RegionsServiceTransport 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 = RegionsServiceClient._read_environment_variables() + self._client_cert_source = RegionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = RegionsServiceClient._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, RegionsServiceTransport) + if transport_provided: + # transport is a RegionsServiceTransport 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(RegionsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + RegionsServiceClient._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[RegionsServiceTransport], Callable[..., RegionsServiceTransport]] = ( + RegionsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionsServiceTransport], 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.accounts_v1beta.RegionsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "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.accounts.v1beta.RegionsService", + "credentialsType": None, + } + ) + + def get_region(self, + request: Optional[Union[regions.GetRegionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Retrieves a region defined in your Merchant Center + 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_accounts_v1beta + + def sample_get_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = client.get_region(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetRegionRequest, dict]): + The request object. Request message for the ``GetRegion`` method. + name (str): + Required. The name of the region to retrieve. Format: + ``accounts/{account}/regions/{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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, regions.GetRegionRequest): + request = regions.GetRegionRequest(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.get_region] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_region(self, + request: Optional[Union[regions.CreateRegionRequest, dict]] = None, + *, + parent: Optional[str] = None, + region: Optional[regions.Region] = None, + region_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + def sample_create_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = client.create_region(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest, dict]): + The request object. Request message for the ``CreateRegion`` method. + parent (str): + Required. The account to create a region for. Format: + ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (google.shopping.merchant_accounts_v1beta.types.Region): + Required. The region to create. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region_id (str): + Required. The identifier for the + region, unique over all regions of the + same account. + + This corresponds to the ``region_id`` 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_accounts_v1beta.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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, region, region_id] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.CreateRegionRequest): + request = regions.CreateRegionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if region is not None: + request.region = region + if region_id is not None: + request.region_id = region_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_region] + + # 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 update_region(self, + request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, + *, + region: Optional[regions.Region] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: + r"""Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + def sample_update_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateRegionRequest( + ) + + # Make the request + response = client.update_region(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest, dict]): + The request object. Request message for the ``UpdateRegion`` method. + region (google.shopping.merchant_accounts_v1beta.types.Region): + Required. The updated region. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The comma-separated field mask indicating the + fields to update. Example: + ``"displayName,postalCodeArea.regionCode"``. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Region: + Represents a geographic region that you can use as a target with both the + RegionalInventory and ShippingSettings services. You + can define regions as collections of either postal + codes or, in some countries, using predefined + geotargets. For more information, see [Set up regions + ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) + for more information. + + """ + # 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 = [region, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, regions.UpdateRegionRequest): + request = regions.UpdateRegionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if region is not None: + request.region = region + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_region] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("region.name", request.region.name), + )), + ) + + # 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_region(self, + request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, + *, + name: 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 a region definition from your Merchant Center + account. Executing this method requires admin access. + + .. 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_accounts_v1beta + + def sample_delete_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + client.delete_region(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest, dict]): + The request object. Request message for the ``DeleteRegion`` method. + name (str): + Required. The name of the region to delete. Format: + ``accounts/{account}/regions/{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, regions.DeleteRegionRequest): + request = regions.DeleteRegionRequest(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_region] + + # 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 list_regions(self, + request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsPager: + r"""Lists the regions in your Merchant Center 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_accounts_v1beta + + def sample_list_regions(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest, dict]): + The request object. Request message for the ``ListRegions`` method. + parent (str): + Required. The account to list regions for. Format: + ``accounts/{account}`` + + 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_accounts_v1beta.services.regions_service.pagers.ListRegionsPager: + Response message for the ListRegions 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, regions.ListRegionsRequest): + request = regions.ListRegionsRequest(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_regions] + + # 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.ListRegionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RegionsServiceClient": + 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__ = ( + "RegionsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py new file mode 100644 index 000000000000..0edde3c4b20c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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_accounts_v1beta.types import regions + + +class ListRegionsPager: + """A pager for iterating through ``list_regions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``regions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRegions`` requests and continue to iterate + through the ``regions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` + 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[..., regions.ListRegionsResponse], + request: regions.ListRegionsRequest, + response: regions.ListRegionsResponse, + *, + 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_accounts_v1beta.types.ListRegionsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse): + 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 = regions.ListRegionsRequest(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[regions.ListRegionsResponse]: + 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[regions.Region]: + for page in self.pages: + yield from page.regions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRegionsAsyncPager: + """A pager for iterating through ``list_regions`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``regions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRegions`` requests and continue to iterate + through the ``regions`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` + 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[regions.ListRegionsResponse]], + request: regions.ListRegionsRequest, + response: regions.ListRegionsResponse, + *, + 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_accounts_v1beta.types.ListRegionsRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse): + 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 = regions.ListRegionsRequest(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[regions.ListRegionsResponse]: + 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[regions.Region]: + async def async_generator(): + async for page in self.pages: + for response in page.regions: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst new file mode 100644 index 000000000000..58b1a6574ad7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionsServiceTransport` is the ABC for all transports. +- public child `RegionsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py new file mode 100644 index 000000000000..e958dfda0512 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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 RegionsServiceTransport +from .grpc import RegionsServiceGrpcTransport +from .grpc_asyncio import RegionsServiceGrpcAsyncIOTransport +from .rest import RegionsServiceRestTransport +from .rest import RegionsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegionsServiceTransport]] +_transport_registry['grpc'] = RegionsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RegionsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RegionsServiceRestTransport + +__all__ = ( + 'RegionsServiceTransport', + 'RegionsServiceGrpcTransport', + 'RegionsServiceGrpcAsyncIOTransport', + 'RegionsServiceRestTransport', + 'RegionsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py new file mode 100644 index 000000000000..f88c19fb292f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py @@ -0,0 +1,216 @@ +# -*- 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_accounts_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_accounts_v1beta.types import regions + +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 RegionsServiceTransport(abc.ABC): + """Abstract transport class for RegionsService.""" + + 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.get_region: gapic_v1.method.wrap_method( + self.get_region, + default_timeout=None, + client_info=client_info, + ), + self.create_region: gapic_v1.method.wrap_method( + self.create_region, + default_timeout=None, + client_info=client_info, + ), + self.update_region: gapic_v1.method.wrap_method( + self.update_region, + default_timeout=None, + client_info=client_info, + ), + self.delete_region: gapic_v1.method.wrap_method( + self.delete_region, + default_timeout=None, + client_info=client_info, + ), + self.list_regions: gapic_v1.method.wrap_method( + self.list_regions, + 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 get_region(self) -> Callable[ + [regions.GetRegionRequest], + Union[ + regions.Region, + Awaitable[regions.Region] + ]]: + raise NotImplementedError() + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + Union[ + regions.Region, + Awaitable[regions.Region] + ]]: + raise NotImplementedError() + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + Union[ + regions.Region, + Awaitable[regions.Region] + ]]: + raise NotImplementedError() + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + Union[ + regions.ListRegionsResponse, + Awaitable[regions.ListRegionsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RegionsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py new file mode 100644 index 000000000000..b5a01c06cea2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py @@ -0,0 +1,459 @@ +# -*- 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_accounts_v1beta.types import regions +from .base import RegionsServiceTransport, 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.accounts.v1beta.RegionsService", + "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.accounts.v1beta.RegionsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionsServiceGrpcTransport(RegionsServiceTransport): + """gRPC backend transport for RegionsService. + + Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1main.Region] + + 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 get_region(self) -> Callable[ + [regions.GetRegionRequest], + regions.Region]: + r"""Return a callable for the get region method over gRPC. + + Retrieves a region defined in your Merchant Center + account. + + Returns: + Callable[[~.GetRegionRequest], + ~.Region]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_region' not in self._stubs: + self._stubs['get_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/GetRegion', + request_serializer=regions.GetRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['get_region'] + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + regions.Region]: + r"""Return a callable for the create region method over gRPC. + + Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.CreateRegionRequest], + ~.Region]: + 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 'create_region' not in self._stubs: + self._stubs['create_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/CreateRegion', + request_serializer=regions.CreateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['create_region'] + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + regions.Region]: + r"""Return a callable for the update region method over gRPC. + + Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.UpdateRegionRequest], + ~.Region]: + 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 'update_region' not in self._stubs: + self._stubs['update_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/UpdateRegion', + request_serializer=regions.UpdateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['update_region'] + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete region method over gRPC. + + Deletes a region definition from your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.DeleteRegionRequest], + ~.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_region' not in self._stubs: + self._stubs['delete_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/DeleteRegion', + request_serializer=regions.DeleteRegionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_region'] + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + regions.ListRegionsResponse]: + r"""Return a callable for the list regions method over gRPC. + + Lists the regions in your Merchant Center account. + + Returns: + Callable[[~.ListRegionsRequest], + ~.ListRegionsResponse]: + 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_regions' not in self._stubs: + self._stubs['list_regions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/ListRegions', + request_serializer=regions.ListRegionsRequest.serialize, + response_deserializer=regions.ListRegionsResponse.deserialize, + ) + return self._stubs['list_regions'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RegionsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..6c72dc1d4595 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py @@ -0,0 +1,500 @@ +# -*- 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_accounts_v1beta.types import regions +from .base import RegionsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegionsServiceGrpcTransport + +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.accounts.v1beta.RegionsService", + "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.accounts.v1beta.RegionsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class RegionsServiceGrpcAsyncIOTransport(RegionsServiceTransport): + """gRPC AsyncIO backend transport for RegionsService. + + Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1main.Region] + + 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 get_region(self) -> Callable[ + [regions.GetRegionRequest], + Awaitable[regions.Region]]: + r"""Return a callable for the get region method over gRPC. + + Retrieves a region defined in your Merchant Center + account. + + Returns: + Callable[[~.GetRegionRequest], + Awaitable[~.Region]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_region' not in self._stubs: + self._stubs['get_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/GetRegion', + request_serializer=regions.GetRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['get_region'] + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + Awaitable[regions.Region]]: + r"""Return a callable for the create region method over gRPC. + + Creates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.CreateRegionRequest], + Awaitable[~.Region]]: + 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 'create_region' not in self._stubs: + self._stubs['create_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/CreateRegion', + request_serializer=regions.CreateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['create_region'] + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + Awaitable[regions.Region]]: + r"""Return a callable for the update region method over gRPC. + + Updates a region definition in your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.UpdateRegionRequest], + Awaitable[~.Region]]: + 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 'update_region' not in self._stubs: + self._stubs['update_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/UpdateRegion', + request_serializer=regions.UpdateRegionRequest.serialize, + response_deserializer=regions.Region.deserialize, + ) + return self._stubs['update_region'] + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete region method over gRPC. + + Deletes a region definition from your Merchant Center + account. Executing this method requires admin access. + + Returns: + Callable[[~.DeleteRegionRequest], + 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_region' not in self._stubs: + self._stubs['delete_region'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/DeleteRegion', + request_serializer=regions.DeleteRegionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_region'] + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + Awaitable[regions.ListRegionsResponse]]: + r"""Return a callable for the list regions method over gRPC. + + Lists the regions in your Merchant Center account. + + Returns: + Callable[[~.ListRegionsRequest], + Awaitable[~.ListRegionsResponse]]: + 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_regions' not in self._stubs: + self._stubs['list_regions'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.RegionsService/ListRegions', + request_serializer=regions.ListRegionsRequest.serialize, + response_deserializer=regions.ListRegionsResponse.deserialize, + ) + return self._stubs['list_regions'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_region: self._wrap_method( + self.get_region, + default_timeout=None, + client_info=client_info, + ), + self.create_region: self._wrap_method( + self.create_region, + default_timeout=None, + client_info=client_info, + ), + self.update_region: self._wrap_method( + self.update_region, + default_timeout=None, + client_info=client_info, + ), + self.delete_region: self._wrap_method( + self.delete_region, + default_timeout=None, + client_info=client_info, + ), + self.list_regions: self._wrap_method( + self.list_regions, + 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__ = ( + 'RegionsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py new file mode 100644 index 000000000000..9160e7a04b93 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py @@ -0,0 +1,1004 @@ +# -*- 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_accounts_v1beta.types import regions + + +from .rest_base import _BaseRegionsServiceRestTransport +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 RegionsServiceRestInterceptor: + """Interceptor for RegionsService. + + 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 RegionsServiceRestTransport. + + .. code-block:: python + class MyCustomRegionsServiceInterceptor(RegionsServiceRestInterceptor): + def pre_create_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_region(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_region(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_regions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_regions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_region(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_region(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegionsServiceRestTransport(interceptor=MyCustomRegionsServiceInterceptor()) + client = RegionsServiceClient(transport=transport) + + + """ + def pre_create_region(self, request: regions.CreateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_create_region(self, response: regions.Region) -> regions.Region: + """Post-rpc interceptor for create_region + + DEPRECATED. Please use the `post_create_region_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_create_region` interceptor runs + before the `post_create_region_with_metadata` interceptor. + """ + return response + + def post_create_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_region + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_create_region_with_metadata` + interceptor in new development instead of the `post_create_region` interceptor. + When both interceptors are used, this `post_create_region_with_metadata` interceptor runs after the + `post_create_region` interceptor. The (possibly modified) response returned by + `post_create_region` will be passed to + `post_create_region_with_metadata`. + """ + return response, metadata + + def pre_delete_region(self, request: regions.DeleteRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def pre_get_region(self, request: regions.GetRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_get_region(self, response: regions.Region) -> regions.Region: + """Post-rpc interceptor for get_region + + DEPRECATED. Please use the `post_get_region_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_get_region` interceptor runs + before the `post_get_region_with_metadata` interceptor. + """ + return response + + def post_get_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_region + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_get_region_with_metadata` + interceptor in new development instead of the `post_get_region` interceptor. + When both interceptors are used, this `post_get_region_with_metadata` interceptor runs after the + `post_get_region` interceptor. The (possibly modified) response returned by + `post_get_region` will be passed to + `post_get_region_with_metadata`. + """ + return response, metadata + + def pre_list_regions(self, request: regions.ListRegionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_regions + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_list_regions(self, response: regions.ListRegionsResponse) -> regions.ListRegionsResponse: + """Post-rpc interceptor for list_regions + + DEPRECATED. Please use the `post_list_regions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_list_regions` interceptor runs + before the `post_list_regions_with_metadata` interceptor. + """ + return response + + def post_list_regions_with_metadata(self, response: regions.ListRegionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_regions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_list_regions_with_metadata` + interceptor in new development instead of the `post_list_regions` interceptor. + When both interceptors are used, this `post_list_regions_with_metadata` interceptor runs after the + `post_list_regions` interceptor. The (possibly modified) response returned by + `post_list_regions` will be passed to + `post_list_regions_with_metadata`. + """ + return response, metadata + + def pre_update_region(self, request: regions.UpdateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_region + + Override in a subclass to manipulate the request or metadata + before they are sent to the RegionsService server. + """ + return request, metadata + + def post_update_region(self, response: regions.Region) -> regions.Region: + """Post-rpc interceptor for update_region + + DEPRECATED. Please use the `post_update_region_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the RegionsService server but before + it is returned to user code. This `post_update_region` interceptor runs + before the `post_update_region_with_metadata` interceptor. + """ + return response + + def post_update_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_region + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the RegionsService server but before it is returned to user code. + + We recommend only using this `post_update_region_with_metadata` + interceptor in new development instead of the `post_update_region` interceptor. + When both interceptors are used, this `post_update_region_with_metadata` interceptor runs after the + `post_update_region` interceptor. The (possibly modified) response returned by + `post_update_region` will be passed to + `post_update_region_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class RegionsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionsServiceRestInterceptor + + +class RegionsServiceRestTransport(_BaseRegionsServiceRestTransport): + """REST backend synchronous transport for RegionsService. + + Manages regions configuration. + + This API defines the following resource model: + + - [Region][google.shopping.merchant.accounts.v1main.Region] + + 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[RegionsServiceRestInterceptor] = 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 RegionsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateRegion(_BaseRegionsServiceRestTransport._BaseCreateRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.CreateRegion") + + @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: regions.CreateRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.Region: + r"""Call the create region method over HTTP. + + Args: + request (~.regions.CreateRegionRequest): + The request object. Request message for the ``CreateRegion`` 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: + ~.regions.Region: + Represents a geographic region that you can use as a + target with both the ``RegionalInventory`` and + ``ShippingSettings`` services. You can define regions as + collections of either postal codes or, in some + countries, using predefined geotargets. For more + information, see `Set up + regions `__ + for more information. + + """ + + http_options = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_http_options() + + request, metadata = self._interceptor.pre_create_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_transcoded_request(http_options, request) + + body = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.CreateRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "CreateRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._CreateRegion._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 = regions.Region() + pb_resp = regions.Region.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_region(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_region_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.Region.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.accounts_v1beta.RegionsServiceClient.create_region", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "CreateRegion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteRegion(_BaseRegionsServiceRestTransport._BaseDeleteRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.DeleteRegion") + + @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: regions.DeleteRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete region method over HTTP. + + Args: + request (~.regions.DeleteRegionRequest): + The request object. Request message for the ``DeleteRegion`` 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 = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_http_options() + + request, metadata = self._interceptor.pre_delete_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.DeleteRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "DeleteRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._DeleteRegion._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 _GetRegion(_BaseRegionsServiceRestTransport._BaseGetRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.GetRegion") + + @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: regions.GetRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.Region: + r"""Call the get region method over HTTP. + + Args: + request (~.regions.GetRegionRequest): + The request object. Request message for the ``GetRegion`` 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: + ~.regions.Region: + Represents a geographic region that you can use as a + target with both the ``RegionalInventory`` and + ``ShippingSettings`` services. You can define regions as + collections of either postal codes or, in some + countries, using predefined geotargets. For more + information, see `Set up + regions `__ + for more information. + + """ + + http_options = _BaseRegionsServiceRestTransport._BaseGetRegion._get_http_options() + + request, metadata = self._interceptor.pre_get_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseGetRegion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseGetRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.GetRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "GetRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._GetRegion._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 = regions.Region() + pb_resp = regions.Region.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_region(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_region_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.Region.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.accounts_v1beta.RegionsServiceClient.get_region", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "GetRegion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRegions(_BaseRegionsServiceRestTransport._BaseListRegions, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.ListRegions") + + @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: regions.ListRegionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.ListRegionsResponse: + r"""Call the list regions method over HTTP. + + Args: + request (~.regions.ListRegionsRequest): + The request object. Request message for the ``ListRegions`` 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: + ~.regions.ListRegionsResponse: + Response message for the ``ListRegions`` method. + """ + + http_options = _BaseRegionsServiceRestTransport._BaseListRegions._get_http_options() + + request, metadata = self._interceptor.pre_list_regions(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseListRegions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseListRegions._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.ListRegions", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "ListRegions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._ListRegions._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 = regions.ListRegionsResponse() + pb_resp = regions.ListRegionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_regions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_regions_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.ListRegionsResponse.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.accounts_v1beta.RegionsServiceClient.list_regions", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "ListRegions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateRegion(_BaseRegionsServiceRestTransport._BaseUpdateRegion, RegionsServiceRestStub): + def __hash__(self): + return hash("RegionsServiceRestTransport.UpdateRegion") + + @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: regions.UpdateRegionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> regions.Region: + r"""Call the update region method over HTTP. + + Args: + request (~.regions.UpdateRegionRequest): + The request object. Request message for the ``UpdateRegion`` 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: + ~.regions.Region: + Represents a geographic region that you can use as a + target with both the ``RegionalInventory`` and + ``ShippingSettings`` services. You can define regions as + collections of either postal codes or, in some + countries, using predefined geotargets. For more + information, see `Set up + regions `__ + for more information. + + """ + + http_options = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_http_options() + + request, metadata = self._interceptor.pre_update_region(request, metadata) + transcoded_request = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_transcoded_request(http_options, request) + + body = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.UpdateRegion", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "UpdateRegion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionsServiceRestTransport._UpdateRegion._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 = regions.Region() + pb_resp = regions.Region.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_region(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_region_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = regions.Region.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.accounts_v1beta.RegionsServiceClient.update_region", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "rpcName": "UpdateRegion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_region(self) -> Callable[ + [regions.CreateRegionRequest], + regions.Region]: + # 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._CreateRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_region(self) -> Callable[ + [regions.DeleteRegionRequest], + 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._DeleteRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_region(self) -> Callable[ + [regions.GetRegionRequest], + regions.Region]: + # 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._GetRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_regions(self) -> Callable[ + [regions.ListRegionsRequest], + regions.ListRegionsResponse]: + # 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._ListRegions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_region(self) -> Callable[ + [regions.UpdateRegionRequest], + regions.Region]: + # 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._UpdateRegion(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RegionsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py new file mode 100644 index 000000000000..31c30d3d35e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py @@ -0,0 +1,297 @@ +# -*- 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 RegionsServiceTransport, 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_accounts_v1beta.types import regions + + +class _BaseRegionsServiceRestTransport(RegionsServiceTransport): + """Base REST backend transport for RegionsService. + + 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 _BaseCreateRegion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "regionId" : "", } + + @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': '/accounts/v1beta/{parent=accounts/*}/regions', + 'body': 'region', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.CreateRegionRequest.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(_BaseRegionsServiceRestTransport._BaseCreateRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteRegion: + 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': '/accounts/v1beta/{name=accounts/*/regions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.DeleteRegionRequest.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(_BaseRegionsServiceRestTransport._BaseDeleteRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRegion: + 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': '/accounts/v1beta/{name=accounts/*/regions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.GetRegionRequest.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(_BaseRegionsServiceRestTransport._BaseGetRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRegions: + 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': '/accounts/v1beta/{parent=accounts/*}/regions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.ListRegionsRequest.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(_BaseRegionsServiceRestTransport._BaseListRegions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateRegion: + 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': 'patch', + 'uri': '/accounts/v1beta/{region.name=accounts/*/regions/*}', + 'body': 'region', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = regions.UpdateRegionRequest.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(_BaseRegionsServiceRestTransport._BaseUpdateRegion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseRegionsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/__init__.py new file mode 100644 index 000000000000..023e41c50a7f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_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 ShippingSettingsServiceClient +from .async_client import ShippingSettingsServiceAsyncClient + +__all__ = ( + 'ShippingSettingsServiceClient', + 'ShippingSettingsServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py new file mode 100644 index 000000000000..220f282c9e2d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py @@ -0,0 +1,461 @@ +# -*- 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_accounts_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_accounts_v1beta.types import shippingsettings +from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport +from .client import ShippingSettingsServiceClient + +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 ShippingSettingsServiceAsyncClient: + """Service to get method call shipping setting information per + Merchant API method. + """ + + _client: ShippingSettingsServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + + shipping_settings_path = staticmethod(ShippingSettingsServiceClient.shipping_settings_path) + parse_shipping_settings_path = staticmethod(ShippingSettingsServiceClient.parse_shipping_settings_path) + common_billing_account_path = staticmethod(ShippingSettingsServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ShippingSettingsServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ShippingSettingsServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ShippingSettingsServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ShippingSettingsServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ShippingSettingsServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ShippingSettingsServiceClient.common_project_path) + parse_common_project_path = staticmethod(ShippingSettingsServiceClient.parse_common_project_path) + common_location_path = staticmethod(ShippingSettingsServiceClient.common_location_path) + parse_common_location_path = staticmethod(ShippingSettingsServiceClient.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: + ShippingSettingsServiceAsyncClient: The constructed client. + """ + return ShippingSettingsServiceClient.from_service_account_info.__func__(ShippingSettingsServiceAsyncClient, 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: + ShippingSettingsServiceAsyncClient: The constructed client. + """ + return ShippingSettingsServiceClient.from_service_account_file.__func__(ShippingSettingsServiceAsyncClient, 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 ShippingSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ShippingSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ShippingSettingsServiceTransport: 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 = ShippingSettingsServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the shipping settings 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,ShippingSettingsServiceTransport,Callable[..., ShippingSettingsServiceTransport]]]): + 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 ShippingSettingsServiceTransport 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 = ShippingSettingsServiceClient( + 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.accounts_v1beta.ShippingSettingsServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "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.accounts.v1beta.ShippingSettingsService", + "credentialsType": None, + } + ) + + async def get_shipping_settings(self, + request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Retrieve shipping setting information. + + .. 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_accounts_v1beta + + async def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest, dict]]): + The request object. Request message for the ``GetShippingSetting`` method. + name (:class:`str`): + Required. The name of the shipping setting to retrieve. + Format: ``accounts/{account}/shippingsetting`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.ShippingSettings: + The merchant account's [shipping + setting](\ https://support.google.com/merchants/answer/6069284). + + """ + # 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, shippingsettings.GetShippingSettingsRequest): + request = shippingsettings.GetShippingSettingsRequest(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.get_shipping_settings] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def insert_shipping_settings(self, + request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Replace the shipping setting of a merchant with the + request shipping setting. Executing this method requires + admin access. + + .. 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_accounts_v1beta + + async def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1beta.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1beta.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = await client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest, dict]]): + The request object. Request message for the ``InsertShippingSetting`` + 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_accounts_v1beta.types.ShippingSettings: + The merchant account's [shipping + setting](\ https://support.google.com/merchants/answer/6069284). + + """ + # 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, shippingsettings.InsertShippingSettingsRequest): + request = shippingsettings.InsertShippingSettingsRequest(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_shipping_settings] + + # 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 __aenter__(self) -> "ShippingSettingsServiceAsyncClient": + 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__ = ( + "ShippingSettingsServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py new file mode 100644 index 000000000000..b51db3bd4107 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py @@ -0,0 +1,821 @@ +# -*- 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_accounts_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_accounts_v1beta.types import shippingsettings +from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ShippingSettingsServiceGrpcTransport +from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport +from .transports.rest import ShippingSettingsServiceRestTransport + + +class ShippingSettingsServiceClientMeta(type): + """Metaclass for the ShippingSettingsService 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[ShippingSettingsServiceTransport]] + _transport_registry["grpc"] = ShippingSettingsServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ShippingSettingsServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ShippingSettingsServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ShippingSettingsServiceTransport]: + """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 ShippingSettingsServiceClient(metaclass=ShippingSettingsServiceClientMeta): + """Service to get method call shipping setting information per + Merchant API method. + """ + + @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: + ShippingSettingsServiceClient: 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: + ShippingSettingsServiceClient: 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) -> ShippingSettingsServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ShippingSettingsServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def shipping_settings_path(account: str,) -> str: + """Returns a fully-qualified shipping_settings string.""" + return "accounts/{account}/shippingSettings".format(account=account, ) + + @staticmethod + def parse_shipping_settings_path(path: str) -> Dict[str,str]: + """Parses a shipping_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/shippingSettings$", 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 = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient._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, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the shipping settings 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,ShippingSettingsServiceTransport,Callable[..., ShippingSettingsServiceTransport]]]): + 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 ShippingSettingsServiceTransport 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 = ShippingSettingsServiceClient._read_environment_variables() + self._client_cert_source = ShippingSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ShippingSettingsServiceClient._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, ShippingSettingsServiceTransport) + if transport_provided: + # transport is a ShippingSettingsServiceTransport 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(ShippingSettingsServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ShippingSettingsServiceClient._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[ShippingSettingsServiceTransport], Callable[..., ShippingSettingsServiceTransport]] = ( + ShippingSettingsServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ShippingSettingsServiceTransport], 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.accounts_v1beta.ShippingSettingsServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "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.accounts.v1beta.ShippingSettingsService", + "credentialsType": None, + } + ) + + def get_shipping_settings(self, + request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Retrieve shipping setting information. + + .. 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_accounts_v1beta + + def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest, dict]): + The request object. Request message for the ``GetShippingSetting`` method. + name (str): + Required. The name of the shipping setting to retrieve. + Format: ``accounts/{account}/shippingsetting`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.ShippingSettings: + The merchant account's [shipping + setting](\ https://support.google.com/merchants/answer/6069284). + + """ + # 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, shippingsettings.GetShippingSettingsRequest): + request = shippingsettings.GetShippingSettingsRequest(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.get_shipping_settings] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def insert_shipping_settings(self, + request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: + r"""Replace the shipping setting of a merchant with the + request shipping setting. Executing this method requires + admin access. + + .. 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_accounts_v1beta + + def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1beta.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1beta.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest, dict]): + The request object. Request message for the ``InsertShippingSetting`` + 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_accounts_v1beta.types.ShippingSettings: + The merchant account's [shipping + setting](\ https://support.google.com/merchants/answer/6069284). + + """ + # 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, shippingsettings.InsertShippingSettingsRequest): + request = shippingsettings.InsertShippingSettingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert_shipping_settings] + + # 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 __enter__(self) -> "ShippingSettingsServiceClient": + 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__ = ( + "ShippingSettingsServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst new file mode 100644 index 000000000000..a638b7b9035f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ShippingSettingsServiceTransport` is the ABC for all transports. +- public child `ShippingSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ShippingSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseShippingSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ShippingSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/__init__.py new file mode 100644 index 000000000000..cbb84e1b0a91 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_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 ShippingSettingsServiceTransport +from .grpc import ShippingSettingsServiceGrpcTransport +from .grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport +from .rest import ShippingSettingsServiceRestTransport +from .rest import ShippingSettingsServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ShippingSettingsServiceTransport]] +_transport_registry['grpc'] = ShippingSettingsServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ShippingSettingsServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ShippingSettingsServiceRestTransport + +__all__ = ( + 'ShippingSettingsServiceTransport', + 'ShippingSettingsServiceGrpcTransport', + 'ShippingSettingsServiceGrpcAsyncIOTransport', + 'ShippingSettingsServiceRestTransport', + 'ShippingSettingsServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py new file mode 100644 index 000000000000..f1317fbe2feb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import shippingsettings + +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 ShippingSettingsServiceTransport(abc.ABC): + """Abstract transport class for ShippingSettingsService.""" + + 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.get_shipping_settings: gapic_v1.method.wrap_method( + self.get_shipping_settings, + default_timeout=None, + client_info=client_info, + ), + self.insert_shipping_settings: gapic_v1.method.wrap_method( + self.insert_shipping_settings, + 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 get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + Union[ + shippingsettings.ShippingSettings, + Awaitable[shippingsettings.ShippingSettings] + ]]: + raise NotImplementedError() + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + Union[ + shippingsettings.ShippingSettings, + Awaitable[shippingsettings.ShippingSettings] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ShippingSettingsServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py new file mode 100644 index 000000000000..c33dd757a185 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py @@ -0,0 +1,375 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import shippingsettings +from .base import ShippingSettingsServiceTransport, 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.accounts.v1beta.ShippingSettingsService", + "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.accounts.v1beta.ShippingSettingsService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ShippingSettingsServiceGrpcTransport(ShippingSettingsServiceTransport): + """gRPC backend transport for ShippingSettingsService. + + Service to get method call shipping setting information per + Merchant API method. + + 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 get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + shippingsettings.ShippingSettings]: + r"""Return a callable for the get shipping settings method over gRPC. + + Retrieve shipping setting information. + + Returns: + Callable[[~.GetShippingSettingsRequest], + ~.ShippingSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_shipping_settings' not in self._stubs: + self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/GetShippingSettings', + request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['get_shipping_settings'] + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + shippingsettings.ShippingSettings]: + r"""Return a callable for the insert shipping settings method over gRPC. + + Replace the shipping setting of a merchant with the + request shipping setting. Executing this method requires + admin access. + + Returns: + Callable[[~.InsertShippingSettingsRequest], + ~.ShippingSettings]: + 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_shipping_settings' not in self._stubs: + self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/InsertShippingSettings', + request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['insert_shipping_settings'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ShippingSettingsServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..09d33b42d7bf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py @@ -0,0 +1,401 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import shippingsettings +from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ShippingSettingsServiceGrpcTransport + +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.accounts.v1beta.ShippingSettingsService", + "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.accounts.v1beta.ShippingSettingsService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ShippingSettingsServiceGrpcAsyncIOTransport(ShippingSettingsServiceTransport): + """gRPC AsyncIO backend transport for ShippingSettingsService. + + Service to get method call shipping setting information per + Merchant API method. + + 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 get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + Awaitable[shippingsettings.ShippingSettings]]: + r"""Return a callable for the get shipping settings method over gRPC. + + Retrieve shipping setting information. + + Returns: + Callable[[~.GetShippingSettingsRequest], + Awaitable[~.ShippingSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_shipping_settings' not in self._stubs: + self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/GetShippingSettings', + request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['get_shipping_settings'] + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + Awaitable[shippingsettings.ShippingSettings]]: + r"""Return a callable for the insert shipping settings method over gRPC. + + Replace the shipping setting of a merchant with the + request shipping setting. Executing this method requires + admin access. + + Returns: + Callable[[~.InsertShippingSettingsRequest], + Awaitable[~.ShippingSettings]]: + 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_shipping_settings' not in self._stubs: + self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/InsertShippingSettings', + request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, + response_deserializer=shippingsettings.ShippingSettings.deserialize, + ) + return self._stubs['insert_shipping_settings'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_shipping_settings: self._wrap_method( + self.get_shipping_settings, + default_timeout=None, + client_info=client_info, + ), + self.insert_shipping_settings: self._wrap_method( + self.insert_shipping_settings, + 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__ = ( + 'ShippingSettingsServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py new file mode 100644 index 000000000000..d35cf9ffb93c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py @@ -0,0 +1,531 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import shippingsettings + + +from .rest_base import _BaseShippingSettingsServiceRestTransport +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 ShippingSettingsServiceRestInterceptor: + """Interceptor for ShippingSettingsService. + + 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 ShippingSettingsServiceRestTransport. + + .. code-block:: python + class MyCustomShippingSettingsServiceInterceptor(ShippingSettingsServiceRestInterceptor): + def pre_get_shipping_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_shipping_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_insert_shipping_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert_shipping_settings(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ShippingSettingsServiceRestTransport(interceptor=MyCustomShippingSettingsServiceInterceptor()) + client = ShippingSettingsServiceClient(transport=transport) + + + """ + def pre_get_shipping_settings(self, request: shippingsettings.GetShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_shipping_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the ShippingSettingsService server. + """ + return request, metadata + + def post_get_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: + """Post-rpc interceptor for get_shipping_settings + + DEPRECATED. Please use the `post_get_shipping_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ShippingSettingsService server but before + it is returned to user code. This `post_get_shipping_settings` interceptor runs + before the `post_get_shipping_settings_with_metadata` interceptor. + """ + return response + + def post_get_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_shipping_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ShippingSettingsService server but before it is returned to user code. + + We recommend only using this `post_get_shipping_settings_with_metadata` + interceptor in new development instead of the `post_get_shipping_settings` interceptor. + When both interceptors are used, this `post_get_shipping_settings_with_metadata` interceptor runs after the + `post_get_shipping_settings` interceptor. The (possibly modified) response returned by + `post_get_shipping_settings` will be passed to + `post_get_shipping_settings_with_metadata`. + """ + return response, metadata + + def pre_insert_shipping_settings(self, request: shippingsettings.InsertShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for insert_shipping_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the ShippingSettingsService server. + """ + return request, metadata + + def post_insert_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: + """Post-rpc interceptor for insert_shipping_settings + + DEPRECATED. Please use the `post_insert_shipping_settings_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ShippingSettingsService server but before + it is returned to user code. This `post_insert_shipping_settings` interceptor runs + before the `post_insert_shipping_settings_with_metadata` interceptor. + """ + return response + + def post_insert_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert_shipping_settings + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ShippingSettingsService server but before it is returned to user code. + + We recommend only using this `post_insert_shipping_settings_with_metadata` + interceptor in new development instead of the `post_insert_shipping_settings` interceptor. + When both interceptors are used, this `post_insert_shipping_settings_with_metadata` interceptor runs after the + `post_insert_shipping_settings` interceptor. The (possibly modified) response returned by + `post_insert_shipping_settings` will be passed to + `post_insert_shipping_settings_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ShippingSettingsServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ShippingSettingsServiceRestInterceptor + + +class ShippingSettingsServiceRestTransport(_BaseShippingSettingsServiceRestTransport): + """REST backend synchronous transport for ShippingSettingsService. + + Service to get method call shipping setting information per + Merchant API method. + + 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[ShippingSettingsServiceRestInterceptor] = 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 ShippingSettingsServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings, ShippingSettingsServiceRestStub): + def __hash__(self): + return hash("ShippingSettingsServiceRestTransport.GetShippingSettings") + + @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: shippingsettings.GetShippingSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> shippingsettings.ShippingSettings: + r"""Call the get shipping settings method over HTTP. + + Args: + request (~.shippingsettings.GetShippingSettingsRequest): + The request object. Request message for the ``GetShippingSetting`` 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: + ~.shippingsettings.ShippingSettings: + The merchant account's `shipping + setting `__. + + """ + + http_options = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_http_options() + + request, metadata = self._interceptor.pre_get_shipping_settings(request, metadata) + transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ShippingSettingsServiceClient.GetShippingSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "rpcName": "GetShippingSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ShippingSettingsServiceRestTransport._GetShippingSettings._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 = shippingsettings.ShippingSettings() + pb_resp = shippingsettings.ShippingSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_shipping_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_shipping_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = shippingsettings.ShippingSettings.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.accounts_v1beta.ShippingSettingsServiceClient.get_shipping_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "rpcName": "GetShippingSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InsertShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings, ShippingSettingsServiceRestStub): + def __hash__(self): + return hash("ShippingSettingsServiceRestTransport.InsertShippingSettings") + + @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: shippingsettings.InsertShippingSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> shippingsettings.ShippingSettings: + r"""Call the insert shipping settings method over HTTP. + + Args: + request (~.shippingsettings.InsertShippingSettingsRequest): + The request object. Request message for the ``InsertShippingSetting`` + 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: + ~.shippingsettings.ShippingSettings: + The merchant account's `shipping + setting `__. + + """ + + http_options = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_http_options() + + request, metadata = self._interceptor.pre_insert_shipping_settings(request, metadata) + transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_transcoded_request(http_options, request) + + body = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ShippingSettingsServiceClient.InsertShippingSettings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "rpcName": "InsertShippingSettings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ShippingSettingsServiceRestTransport._InsertShippingSettings._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 = shippingsettings.ShippingSettings() + pb_resp = shippingsettings.ShippingSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert_shipping_settings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_shipping_settings_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = shippingsettings.ShippingSettings.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.accounts_v1beta.ShippingSettingsServiceClient.insert_shipping_settings", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "rpcName": "InsertShippingSettings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_shipping_settings(self) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + shippingsettings.ShippingSettings]: + # 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._GetShippingSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def insert_shipping_settings(self) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + shippingsettings.ShippingSettings]: + # 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._InsertShippingSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ShippingSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py new file mode 100644 index 000000000000..a8043324a71a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py @@ -0,0 +1,175 @@ +# -*- 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 ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import shippingsettings + + +class _BaseShippingSettingsServiceRestTransport(ShippingSettingsServiceTransport): + """Base REST backend transport for ShippingSettingsService. + + 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 _BaseGetShippingSettings: + 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': '/accounts/v1beta/{name=accounts/*/shippingSettings}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = shippingsettings.GetShippingSettingsRequest.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(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseInsertShippingSettings: + 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': '/accounts/v1beta/{parent=accounts/*}/shippingSettings:insert', + 'body': 'shipping_setting', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = shippingsettings.InsertShippingSettingsRequest.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(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseShippingSettingsServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/__init__.py new file mode 100644 index 000000000000..c0461009811b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_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 TermsOfServiceAgreementStateServiceClient +from .async_client import TermsOfServiceAgreementStateServiceAsyncClient + +__all__ = ( + 'TermsOfServiceAgreementStateServiceClient', + 'TermsOfServiceAgreementStateServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py new file mode 100644 index 000000000000..be1a95259efa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py @@ -0,0 +1,536 @@ +# -*- 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_accounts_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_accounts_v1beta.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1beta.types import termsofservicekind +from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .client import TermsOfServiceAgreementStateServiceClient + +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 TermsOfServiceAgreementStateServiceAsyncClient: + """Service to support ``TermsOfServiceAgreementState`` API.""" + + _client: TermsOfServiceAgreementStateServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.account_path) + parse_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_account_path) + terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_path) + parse_terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path) + terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path) + parse_terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path) + common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_organization_path) + common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_project_path) + parse_common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_project_path) + common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_location_path) + parse_common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.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: + TermsOfServiceAgreementStateServiceAsyncClient: The constructed client. + """ + return TermsOfServiceAgreementStateServiceClient.from_service_account_info.__func__(TermsOfServiceAgreementStateServiceAsyncClient, 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: + TermsOfServiceAgreementStateServiceAsyncClient: The constructed client. + """ + return TermsOfServiceAgreementStateServiceClient.from_service_account_file.__func__(TermsOfServiceAgreementStateServiceAsyncClient, 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 TermsOfServiceAgreementStateServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TermsOfServiceAgreementStateServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceAgreementStateServiceTransport: 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 = TermsOfServiceAgreementStateServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service agreement state 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,TermsOfServiceAgreementStateServiceTransport,Callable[..., TermsOfServiceAgreementStateServiceTransport]]]): + 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 TermsOfServiceAgreementStateServiceTransport 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 = TermsOfServiceAgreementStateServiceClient( + 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.accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "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.accounts.v1beta.TermsOfServiceAgreementStateService", + "credentialsType": None, + } + ) + + async def get_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Returns the state of a terms of service agreement. + + .. 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_accounts_v1beta + + async def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest, dict]]): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` method. + name (:class:`str`): + Required. The resource name of the terms of service + version. Format: + ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` + The identifier format is: + ``{TermsOfServiceKind}-{country}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the merchant has accepted a terms of service: + [accepted](TermsOfServiceAggrementState.accepted) + will be populated, otherwise it will be empty \* If + the merchant must sign a terms of service: + [required](TermsOfServiceAggrementState.required) + will be populated, otherwise it will be empty. + + Note that both + [required](TermsOfServiceAggrementState.required) and + [accepted](TermsOfServiceAggrementState.accepted) can + be present. In this case the accepted terms of + services will have an expiration date set in the + [valid_until](Accepted.valid_until) field. The + required terms of services need to be accepted before + valid_until in order for the account to continue + having a valid agreement. When accepting new terms of + services we expect 3Ps to display the text associated + with the given terms of service agreement (the url to + the file containing the text is added in the Required + message below as + [tos_file_uri](Accepted.tos_file_uri). The actual + acceptance of the terms of service is done by calling + accept on the [TermsOfService](TermsOfService) + resource. + + """ + # 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, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(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.get_terms_of_service_agreement_state] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retrieve_for_application_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Retrieves the state of the agreement for the + application terms of service. + + .. 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_accounts_v1beta + + async def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest, dict]]): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + method. + parent (:class:`str`): + Required. The account for which to get a + TermsOfServiceAgreementState Format: + ``accounts/{account}`` + + 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_accounts_v1beta.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the merchant has accepted a terms of service: + [accepted](TermsOfServiceAggrementState.accepted) + will be populated, otherwise it will be empty \* If + the merchant must sign a terms of service: + [required](TermsOfServiceAggrementState.required) + will be populated, otherwise it will be empty. + + Note that both + [required](TermsOfServiceAggrementState.required) and + [accepted](TermsOfServiceAggrementState.accepted) can + be present. In this case the accepted terms of + services will have an expiration date set in the + [valid_until](Accepted.valid_until) field. The + required terms of services need to be accepted before + valid_until in order for the account to continue + having a valid agreement. When accepting new terms of + services we expect 3Ps to display the text associated + with the given terms of service agreement (the url to + the file containing the text is added in the Required + message below as + [tos_file_uri](Accepted.tos_file_uri). The actual + acceptance of the terms of service is done by calling + accept on the [TermsOfService](TermsOfService) + resource. + + """ + # 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, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(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.retrieve_for_application_terms_of_service_agreement_state] + + # 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 __aenter__(self) -> "TermsOfServiceAgreementStateServiceAsyncClient": + 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__ = ( + "TermsOfServiceAgreementStateServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py new file mode 100644 index 000000000000..2addf61b12a1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py @@ -0,0 +1,913 @@ +# -*- 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_accounts_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_accounts_v1beta.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1beta.types import termsofservicekind +from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TermsOfServiceAgreementStateServiceGrpcTransport +from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .transports.rest import TermsOfServiceAgreementStateServiceRestTransport + + +class TermsOfServiceAgreementStateServiceClientMeta(type): + """Metaclass for the TermsOfServiceAgreementStateService 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[TermsOfServiceAgreementStateServiceTransport]] + _transport_registry["grpc"] = TermsOfServiceAgreementStateServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TermsOfServiceAgreementStateServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TermsOfServiceAgreementStateServiceTransport]: + """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 TermsOfServiceAgreementStateServiceClient(metaclass=TermsOfServiceAgreementStateServiceClientMeta): + """Service to support ``TermsOfServiceAgreementState`` API.""" + + @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: + TermsOfServiceAgreementStateServiceClient: 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: + TermsOfServiceAgreementStateServiceClient: 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) -> TermsOfServiceAgreementStateServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceAgreementStateServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_path(version: str,) -> str: + """Returns a fully-qualified terms_of_service string.""" + return "termsOfService/{version}".format(version=version, ) + + @staticmethod + def parse_terms_of_service_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service path into its component segments.""" + m = re.match(r"^termsOfService/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_agreement_state_path(account: str,identifier: str,) -> str: + """Returns a fully-qualified terms_of_service_agreement_state string.""" + return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + + @staticmethod + def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service_agreement_state path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?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 = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TermsOfServiceAgreementStateServiceClient._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 = TermsOfServiceAgreementStateServiceClient._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, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service agreement state 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,TermsOfServiceAgreementStateServiceTransport,Callable[..., TermsOfServiceAgreementStateServiceTransport]]]): + 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 TermsOfServiceAgreementStateServiceTransport 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 = TermsOfServiceAgreementStateServiceClient._read_environment_variables() + self._client_cert_source = TermsOfServiceAgreementStateServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = TermsOfServiceAgreementStateServiceClient._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, TermsOfServiceAgreementStateServiceTransport) + if transport_provided: + # transport is a TermsOfServiceAgreementStateServiceTransport 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(TermsOfServiceAgreementStateServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + TermsOfServiceAgreementStateServiceClient._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[TermsOfServiceAgreementStateServiceTransport], Callable[..., TermsOfServiceAgreementStateServiceTransport]] = ( + TermsOfServiceAgreementStateServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TermsOfServiceAgreementStateServiceTransport], 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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "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.accounts.v1beta.TermsOfServiceAgreementStateService", + "credentialsType": None, + } + ) + + def get_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Returns the state of a terms of service agreement. + + .. 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_accounts_v1beta + + def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest, dict]): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` method. + name (str): + Required. The resource name of the terms of service + version. Format: + ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` + The identifier format is: + ``{TermsOfServiceKind}-{country}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the merchant has accepted a terms of service: + [accepted](TermsOfServiceAggrementState.accepted) + will be populated, otherwise it will be empty \* If + the merchant must sign a terms of service: + [required](TermsOfServiceAggrementState.required) + will be populated, otherwise it will be empty. + + Note that both + [required](TermsOfServiceAggrementState.required) and + [accepted](TermsOfServiceAggrementState.accepted) can + be present. In this case the accepted terms of + services will have an expiration date set in the + [valid_until](Accepted.valid_until) field. The + required terms of services need to be accepted before + valid_until in order for the account to continue + having a valid agreement. When accepting new terms of + services we expect 3Ps to display the text associated + with the given terms of service agreement (the url to + the file containing the text is added in the Required + message below as + [tos_file_uri](Accepted.tos_file_uri). The actual + acceptance of the terms of service is done by calling + accept on the [TermsOfService](TermsOfService) + resource. + + """ + # 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, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(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.get_terms_of_service_agreement_state] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retrieve_for_application_terms_of_service_agreement_state(self, + request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Retrieves the state of the agreement for the + application terms of service. + + .. 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_accounts_v1beta + + def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest, dict]): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + method. + parent (str): + Required. The account for which to get a + TermsOfServiceAgreementState Format: + ``accounts/{account}`` + + 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_accounts_v1beta.types.TermsOfServiceAgreementState: + This resource represents the agreement state for a given account and terms of + service kind. The state is as follows: + + \* If the merchant has accepted a terms of service: + [accepted](TermsOfServiceAggrementState.accepted) + will be populated, otherwise it will be empty \* If + the merchant must sign a terms of service: + [required](TermsOfServiceAggrementState.required) + will be populated, otherwise it will be empty. + + Note that both + [required](TermsOfServiceAggrementState.required) and + [accepted](TermsOfServiceAggrementState.accepted) can + be present. In this case the accepted terms of + services will have an expiration date set in the + [valid_until](Accepted.valid_until) field. The + required terms of services need to be accepted before + valid_until in order for the account to continue + having a valid agreement. When accepting new terms of + services we expect 3Ps to display the text associated + with the given terms of service agreement (the url to + the file containing the text is added in the Required + message below as + [tos_file_uri](Accepted.tos_file_uri). The actual + acceptance of the terms of service is done by calling + accept on the [TermsOfService](TermsOfService) + resource. + + """ + # 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, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(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.retrieve_for_application_terms_of_service_agreement_state] + + # 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 __enter__(self) -> "TermsOfServiceAgreementStateServiceClient": + 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__ = ( + "TermsOfServiceAgreementStateServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst new file mode 100644 index 000000000000..344858fa2eb5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TermsOfServiceAgreementStateServiceTransport` is the ABC for all transports. +- public child `TermsOfServiceAgreementStateServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTermsOfServiceAgreementStateServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TermsOfServiceAgreementStateServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/__init__.py new file mode 100644 index 000000000000..3e5e8db05323 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_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 TermsOfServiceAgreementStateServiceTransport +from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport +from .grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .rest import TermsOfServiceAgreementStateServiceRestTransport +from .rest import TermsOfServiceAgreementStateServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] +_transport_registry['grpc'] = TermsOfServiceAgreementStateServiceGrpcTransport +_transport_registry['grpc_asyncio'] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +_transport_registry['rest'] = TermsOfServiceAgreementStateServiceRestTransport + +__all__ = ( + 'TermsOfServiceAgreementStateServiceTransport', + 'TermsOfServiceAgreementStateServiceGrpcTransport', + 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', + 'TermsOfServiceAgreementStateServiceRestTransport', + 'TermsOfServiceAgreementStateServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py new file mode 100644 index 000000000000..949759e97599 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py @@ -0,0 +1,173 @@ +# -*- 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_accounts_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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate + +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 TermsOfServiceAgreementStateServiceTransport(abc.ABC): + """Abstract transport class for TermsOfServiceAgreementStateService.""" + + 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.get_terms_of_service_agreement_state: gapic_v1.method.wrap_method( + self.get_terms_of_service_agreement_state, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_for_application_terms_of_service_agreement_state: gapic_v1.method.wrap_method( + self.retrieve_for_application_terms_of_service_agreement_state, + 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 get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + Union[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] + ]]: + raise NotImplementedError() + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + Union[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TermsOfServiceAgreementStateServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py new file mode 100644 index 000000000000..b8d2002a1084 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py @@ -0,0 +1,375 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate +from .base import TermsOfServiceAgreementStateServiceTransport, 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.accounts.v1beta.TermsOfServiceAgreementStateService", + "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.accounts.v1beta.TermsOfServiceAgreementStateService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceAgreementStateServiceGrpcTransport(TermsOfServiceAgreementStateServiceTransport): + """gRPC backend transport for TermsOfServiceAgreementStateService. + + Service to support ``TermsOfServiceAgreementState`` API. + + 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 get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + r"""Return a callable for the get terms of service agreement + state method over gRPC. + + Returns the state of a terms of service agreement. + + Returns: + Callable[[~.GetTermsOfServiceAgreementStateRequest], + ~.TermsOfServiceAgreementState]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service_agreement_state' not in self._stubs: + self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['get_terms_of_service_agreement_state'] + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + r"""Return a callable for the retrieve for application terms + of service agreement state method over gRPC. + + Retrieves the state of the agreement for the + application terms of service. + + Returns: + Callable[[~.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + ~.TermsOfServiceAgreementState]: + 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 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: + self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TermsOfServiceAgreementStateServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..bdab2aaec7b5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py @@ -0,0 +1,401 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate +from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport + +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.accounts.v1beta.TermsOfServiceAgreementStateService", + "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.accounts.v1beta.TermsOfServiceAgreementStateService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport(TermsOfServiceAgreementStateServiceTransport): + """gRPC AsyncIO backend transport for TermsOfServiceAgreementStateService. + + Service to support ``TermsOfServiceAgreementState`` API. + + 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 get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: + r"""Return a callable for the get terms of service agreement + state method over gRPC. + + Returns the state of a terms of service agreement. + + Returns: + Callable[[~.GetTermsOfServiceAgreementStateRequest], + Awaitable[~.TermsOfServiceAgreementState]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service_agreement_state' not in self._stubs: + self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['get_terms_of_service_agreement_state'] + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: + r"""Return a callable for the retrieve for application terms + of service agreement state method over gRPC. + + Retrieves the state of the agreement for the + application terms of service. + + Returns: + Callable[[~.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + Awaitable[~.TermsOfServiceAgreementState]]: + 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 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: + self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', + request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, + response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, + ) + return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_terms_of_service_agreement_state: self._wrap_method( + self.get_terms_of_service_agreement_state, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_for_application_terms_of_service_agreement_state: self._wrap_method( + self.retrieve_for_application_terms_of_service_agreement_state, + 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__ = ( + 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py new file mode 100644 index 000000000000..1f798438960a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py @@ -0,0 +1,583 @@ +# -*- 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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate + + +from .rest_base import _BaseTermsOfServiceAgreementStateServiceRestTransport +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 TermsOfServiceAgreementStateServiceRestInterceptor: + """Interceptor for TermsOfServiceAgreementStateService. + + 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 TermsOfServiceAgreementStateServiceRestTransport. + + .. code-block:: python + class MyCustomTermsOfServiceAgreementStateServiceInterceptor(TermsOfServiceAgreementStateServiceRestInterceptor): + def pre_get_terms_of_service_agreement_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_terms_of_service_agreement_state(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_for_application_terms_of_service_agreement_state(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_for_application_terms_of_service_agreement_state(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TermsOfServiceAgreementStateServiceRestTransport(interceptor=MyCustomTermsOfServiceAgreementStateServiceInterceptor()) + client = TermsOfServiceAgreementStateServiceClient(transport=transport) + + + """ + def pre_get_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_terms_of_service_agreement_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceAgreementStateService server. + """ + return request, metadata + + def post_get_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + """Post-rpc interceptor for get_terms_of_service_agreement_state + + DEPRECATED. Please use the `post_get_terms_of_service_agreement_state_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceAgreementStateService server but before + it is returned to user code. This `post_get_terms_of_service_agreement_state` interceptor runs + before the `post_get_terms_of_service_agreement_state_with_metadata` interceptor. + """ + return response + + def post_get_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_terms_of_service_agreement_state + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceAgreementStateService server but before it is returned to user code. + + We recommend only using this `post_get_terms_of_service_agreement_state_with_metadata` + interceptor in new development instead of the `post_get_terms_of_service_agreement_state` interceptor. + When both interceptors are used, this `post_get_terms_of_service_agreement_state_with_metadata` interceptor runs after the + `post_get_terms_of_service_agreement_state` interceptor. The (possibly modified) response returned by + `post_get_terms_of_service_agreement_state` will be passed to + `post_get_terms_of_service_agreement_state_with_metadata`. + """ + return response, metadata + + def pre_retrieve_for_application_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceAgreementStateService server. + """ + return request, metadata + + def post_retrieve_for_application_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state + + DEPRECATED. Please use the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceAgreementStateService server but before + it is returned to user code. This `post_retrieve_for_application_terms_of_service_agreement_state` interceptor runs + before the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` interceptor. + """ + return response + + def post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceAgreementStateService server but before it is returned to user code. + + We recommend only using this `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` + interceptor in new development instead of the `post_retrieve_for_application_terms_of_service_agreement_state` interceptor. + When both interceptors are used, this `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` interceptor runs after the + `post_retrieve_for_application_terms_of_service_agreement_state` interceptor. The (possibly modified) response returned by + `post_retrieve_for_application_terms_of_service_agreement_state` will be passed to + `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class TermsOfServiceAgreementStateServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TermsOfServiceAgreementStateServiceRestInterceptor + + +class TermsOfServiceAgreementStateServiceRestTransport(_BaseTermsOfServiceAgreementStateServiceRestTransport): + """REST backend synchronous transport for TermsOfServiceAgreementStateService. + + Service to support ``TermsOfServiceAgreementState`` API. + + 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[TermsOfServiceAgreementStateServiceRestInterceptor] = 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 TermsOfServiceAgreementStateServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceAgreementStateServiceRestTransport.GetTermsOfServiceAgreementState") + + @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: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Call the get terms of service + agreement state method over HTTP. + + Args: + request (~.termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` 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: + ~.termsofserviceagreementstate.TermsOfServiceAgreementState: + This resource represents the agreement state for a given + account and terms of service kind. The state is as + follows: + + - If the merchant has accepted a terms of service: + `accepted `__ + will be populated, otherwise it will be empty + - If the merchant must sign a terms of service: + `required `__ + will be populated, otherwise it will be empty. + + Note that both + `required `__ and + `accepted `__ can + be present. In this case the ``accepted`` terms of + services will have an expiration date set in the + `valid_until `__ field. The + ``required`` terms of services need to be accepted + before ``valid_until`` in order for the account to + continue having a valid agreement. When accepting new + terms of services we expect 3Ps to display the text + associated with the given terms of service agreement + (the url to the file containing the text is added in the + Required message below as + `tos_file_uri `__. The actual + acceptance of the terms of service is done by calling + accept on the `TermsOfService `__ + resource. + + """ + + http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_http_options() + + request, metadata = self._interceptor.pre_get_terms_of_service_agreement_state(request, metadata) + transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.GetTermsOfServiceAgreementState", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "rpcName": "GetTermsOfServiceAgreementState", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceAgreementStateServiceRestTransport._GetTermsOfServiceAgreementState._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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + pb_resp = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_terms_of_service_agreement_state(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_terms_of_service_agreement_state_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "rpcName": "GetTermsOfServiceAgreementState", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RetrieveForApplicationTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceAgreementStateServiceRestTransport.RetrieveForApplicationTermsOfServiceAgreementState") + + @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: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + r"""Call the retrieve for application + terms of service agreement state method over HTTP. + + Args: + request (~.termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + 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: + ~.termsofserviceagreementstate.TermsOfServiceAgreementState: + This resource represents the agreement state for a given + account and terms of service kind. The state is as + follows: + + - If the merchant has accepted a terms of service: + `accepted `__ + will be populated, otherwise it will be empty + - If the merchant must sign a terms of service: + `required `__ + will be populated, otherwise it will be empty. + + Note that both + `required `__ and + `accepted `__ can + be present. In this case the ``accepted`` terms of + services will have an expiration date set in the + `valid_until `__ field. The + ``required`` terms of services need to be accepted + before ``valid_until`` in order for the account to + continue having a valid agreement. When accepting new + terms of services we expect 3Ps to display the text + associated with the given terms of service agreement + (the url to the file containing the text is added in the + Required message below as + `tos_file_uri `__. The actual + acceptance of the terms of service is done by calling + accept on the `TermsOfService `__ + resource. + + """ + + http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_http_options() + + request, metadata = self._interceptor.pre_retrieve_for_application_terms_of_service_agreement_state(request, metadata) + transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.RetrieveForApplicationTermsOfServiceAgreementState", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceAgreementStateServiceRestTransport._RetrieveForApplicationTermsOfServiceAgreementState._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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + pb_resp = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + # 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._GetTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ + [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState]: + # 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._RetrieveForApplicationTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TermsOfServiceAgreementStateServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py new file mode 100644 index 000000000000..875305eb1d7c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py @@ -0,0 +1,165 @@ +# -*- 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 TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate + + +class _BaseTermsOfServiceAgreementStateServiceRestTransport(TermsOfServiceAgreementStateServiceTransport): + """Base REST backend transport for TermsOfServiceAgreementStateService. + + 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 _BaseGetTermsOfServiceAgreementState: + 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': '/accounts/v1beta/{name=accounts/*/termsOfServiceAgreementStates/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRetrieveForApplicationTermsOfServiceAgreementState: + 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': '/accounts/v1beta/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseTermsOfServiceAgreementStateServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/__init__.py new file mode 100644 index 000000000000..7bfe24f4bb51 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_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 TermsOfServiceServiceClient +from .async_client import TermsOfServiceServiceAsyncClient + +__all__ = ( + 'TermsOfServiceServiceClient', + 'TermsOfServiceServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py new file mode 100644 index 000000000000..cf45eb70297a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py @@ -0,0 +1,543 @@ +# -*- 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_accounts_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_accounts_v1beta.types import termsofservice +from google.shopping.merchant_accounts_v1beta.types import termsofservicekind +from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from .client import TermsOfServiceServiceClient + +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 TermsOfServiceServiceAsyncClient: + """Service to support ``TermsOfService`` API.""" + + _client: TermsOfServiceServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = TermsOfServiceServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(TermsOfServiceServiceClient.account_path) + parse_account_path = staticmethod(TermsOfServiceServiceClient.parse_account_path) + terms_of_service_path = staticmethod(TermsOfServiceServiceClient.terms_of_service_path) + parse_terms_of_service_path = staticmethod(TermsOfServiceServiceClient.parse_terms_of_service_path) + common_billing_account_path = staticmethod(TermsOfServiceServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(TermsOfServiceServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(TermsOfServiceServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(TermsOfServiceServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(TermsOfServiceServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(TermsOfServiceServiceClient.parse_common_organization_path) + common_project_path = staticmethod(TermsOfServiceServiceClient.common_project_path) + parse_common_project_path = staticmethod(TermsOfServiceServiceClient.parse_common_project_path) + common_location_path = staticmethod(TermsOfServiceServiceClient.common_location_path) + parse_common_location_path = staticmethod(TermsOfServiceServiceClient.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: + TermsOfServiceServiceAsyncClient: The constructed client. + """ + return TermsOfServiceServiceClient.from_service_account_info.__func__(TermsOfServiceServiceAsyncClient, 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: + TermsOfServiceServiceAsyncClient: The constructed client. + """ + return TermsOfServiceServiceClient.from_service_account_file.__func__(TermsOfServiceServiceAsyncClient, 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 TermsOfServiceServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> TermsOfServiceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceServiceTransport: 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 = TermsOfServiceServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service 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,TermsOfServiceServiceTransport,Callable[..., TermsOfServiceServiceTransport]]]): + 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 TermsOfServiceServiceTransport 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 = TermsOfServiceServiceClient( + 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.accounts_v1beta.TermsOfServiceServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "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.accounts.v1beta.TermsOfServiceService", + "credentialsType": None, + } + ) + + async def get_terms_of_service(self, + request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the ``TermsOfService`` associated with the provided + version. + + .. 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_accounts_v1beta + + async def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest, dict]]): + The request object. Request message for the ``GetTermsOfService`` method. + name (:class:`str`): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.TermsOfService: + A TermsOfService. + """ + # 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, termsofservice.GetTermsOfServiceRequest): + request = termsofservice.GetTermsOfServiceRequest(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.get_terms_of_service] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retrieve_latest_terms_of_service(self, + request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + .. 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_accounts_v1beta + + async def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = await client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest, dict]]): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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_accounts_v1beta.types.TermsOfService: + A TermsOfService. + """ + # 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, termsofservice.RetrieveLatestTermsOfServiceRequest): + request = termsofservice.RetrieveLatestTermsOfServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.retrieve_latest_terms_of_service] + + # 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 accept_terms_of_service(self, + request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, + *, + name: 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"""Accepts a ``TermsOfService``. Executing this method requires + admin access. + + .. 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_accounts_v1beta + + async def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + await client.accept_terms_of_service(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest, dict]]): + The request object. Request message for the ``AcceptTermsOfService`` method. + name (:class:`str`): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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, termsofservice.AcceptTermsOfServiceRequest): + request = termsofservice.AcceptTermsOfServiceRequest(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.accept_terms_of_service] + + # 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) -> "TermsOfServiceServiceAsyncClient": + 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__ = ( + "TermsOfServiceServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py new file mode 100644 index 000000000000..4df5b0c85e33 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py @@ -0,0 +1,911 @@ +# -*- 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_accounts_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_accounts_v1beta.types import termsofservice +from google.shopping.merchant_accounts_v1beta.types import termsofservicekind +from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import TermsOfServiceServiceGrpcTransport +from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from .transports.rest import TermsOfServiceServiceRestTransport + + +class TermsOfServiceServiceClientMeta(type): + """Metaclass for the TermsOfServiceService 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[TermsOfServiceServiceTransport]] + _transport_registry["grpc"] = TermsOfServiceServiceGrpcTransport + _transport_registry["grpc_asyncio"] = TermsOfServiceServiceGrpcAsyncIOTransport + _transport_registry["rest"] = TermsOfServiceServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[TermsOfServiceServiceTransport]: + """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 TermsOfServiceServiceClient(metaclass=TermsOfServiceServiceClientMeta): + """Service to support ``TermsOfService`` API.""" + + @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: + TermsOfServiceServiceClient: 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: + TermsOfServiceServiceClient: 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) -> TermsOfServiceServiceTransport: + """Returns the transport used by the client instance. + + Returns: + TermsOfServiceServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terms_of_service_path(version: str,) -> str: + """Returns a fully-qualified terms_of_service string.""" + return "termsOfService/{version}".format(version=version, ) + + @staticmethod + def parse_terms_of_service_path(path: str) -> Dict[str,str]: + """Parses a terms_of_service path into its component segments.""" + m = re.match(r"^termsOfService/(?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 = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient._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, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the terms of service 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,TermsOfServiceServiceTransport,Callable[..., TermsOfServiceServiceTransport]]]): + 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 TermsOfServiceServiceTransport 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 = TermsOfServiceServiceClient._read_environment_variables() + self._client_cert_source = TermsOfServiceServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = TermsOfServiceServiceClient._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, TermsOfServiceServiceTransport) + if transport_provided: + # transport is a TermsOfServiceServiceTransport 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(TermsOfServiceServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + TermsOfServiceServiceClient._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[TermsOfServiceServiceTransport], Callable[..., TermsOfServiceServiceTransport]] = ( + TermsOfServiceServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TermsOfServiceServiceTransport], 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.accounts_v1beta.TermsOfServiceServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "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.accounts.v1beta.TermsOfServiceService", + "credentialsType": None, + } + ) + + def get_terms_of_service(self, + request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the ``TermsOfService`` associated with the provided + version. + + .. 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_accounts_v1beta + + def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest, dict]): + The request object. Request message for the ``GetTermsOfService`` method. + name (str): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.TermsOfService: + A TermsOfService. + """ + # 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, termsofservice.GetTermsOfServiceRequest): + request = termsofservice.GetTermsOfServiceRequest(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.get_terms_of_service] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retrieve_latest_terms_of_service(self, + request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: + r"""Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + .. 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_accounts_v1beta + + def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest, dict]): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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_accounts_v1beta.types.TermsOfService: + A TermsOfService. + """ + # 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, termsofservice.RetrieveLatestTermsOfServiceRequest): + request = termsofservice.RetrieveLatestTermsOfServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.retrieve_latest_terms_of_service] + + # 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 accept_terms_of_service(self, + request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, + *, + name: 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"""Accepts a ``TermsOfService``. Executing this method requires + admin access. + + .. 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_accounts_v1beta + + def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + client.accept_terms_of_service(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest, dict]): + The request object. Request message for the ``AcceptTermsOfService`` method. + name (str): + Required. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + + 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, termsofservice.AcceptTermsOfServiceRequest): + request = termsofservice.AcceptTermsOfServiceRequest(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.accept_terms_of_service] + + # 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) -> "TermsOfServiceServiceClient": + 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__ = ( + "TermsOfServiceServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst new file mode 100644 index 000000000000..3a13382bc0d2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`TermsOfServiceServiceTransport` is the ABC for all transports. +- public child `TermsOfServiceServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `TermsOfServiceServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseTermsOfServiceServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `TermsOfServiceServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/__init__.py new file mode 100644 index 000000000000..04c865765be1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_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 TermsOfServiceServiceTransport +from .grpc import TermsOfServiceServiceGrpcTransport +from .grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from .rest import TermsOfServiceServiceRestTransport +from .rest import TermsOfServiceServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceServiceTransport]] +_transport_registry['grpc'] = TermsOfServiceServiceGrpcTransport +_transport_registry['grpc_asyncio'] = TermsOfServiceServiceGrpcAsyncIOTransport +_transport_registry['rest'] = TermsOfServiceServiceRestTransport + +__all__ = ( + 'TermsOfServiceServiceTransport', + 'TermsOfServiceServiceGrpcTransport', + 'TermsOfServiceServiceGrpcAsyncIOTransport', + 'TermsOfServiceServiceRestTransport', + 'TermsOfServiceServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/base.py new file mode 100644 index 000000000000..25ec7e23fc98 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_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_accounts_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_accounts_v1beta.types import termsofservice + +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 TermsOfServiceServiceTransport(abc.ABC): + """Abstract transport class for TermsOfServiceService.""" + + 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.get_terms_of_service: gapic_v1.method.wrap_method( + self.get_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_latest_terms_of_service: gapic_v1.method.wrap_method( + self.retrieve_latest_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.accept_terms_of_service: gapic_v1.method.wrap_method( + self.accept_terms_of_service, + 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 get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + Union[ + termsofservice.TermsOfService, + Awaitable[termsofservice.TermsOfService] + ]]: + raise NotImplementedError() + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + Union[ + termsofservice.TermsOfService, + Awaitable[termsofservice.TermsOfService] + ]]: + raise NotImplementedError() + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'TermsOfServiceServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py new file mode 100644 index 000000000000..3b06c226005b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py @@ -0,0 +1,403 @@ +# -*- 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_accounts_v1beta.types import termsofservice +from .base import TermsOfServiceServiceTransport, 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.accounts.v1beta.TermsOfServiceService", + "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.accounts.v1beta.TermsOfServiceService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceServiceGrpcTransport(TermsOfServiceServiceTransport): + """gRPC backend transport for TermsOfServiceService. + + Service to support ``TermsOfService`` API. + + 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 get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + termsofservice.TermsOfService]: + r"""Return a callable for the get terms of service method over gRPC. + + Retrieves the ``TermsOfService`` associated with the provided + version. + + Returns: + Callable[[~.GetTermsOfServiceRequest], + ~.TermsOfService]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service' not in self._stubs: + self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/GetTermsOfService', + request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['get_terms_of_service'] + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + termsofservice.TermsOfService]: + r"""Return a callable for the retrieve latest terms of + service method over gRPC. + + Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + Returns: + Callable[[~.RetrieveLatestTermsOfServiceRequest], + ~.TermsOfService]: + 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 'retrieve_latest_terms_of_service' not in self._stubs: + self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/RetrieveLatestTermsOfService', + request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['retrieve_latest_terms_of_service'] + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + empty_pb2.Empty]: + r"""Return a callable for the accept terms of service method over gRPC. + + Accepts a ``TermsOfService``. Executing this method requires + admin access. + + Returns: + Callable[[~.AcceptTermsOfServiceRequest], + ~.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 'accept_terms_of_service' not in self._stubs: + self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/AcceptTermsOfService', + request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['accept_terms_of_service'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'TermsOfServiceServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..553dc4234e16 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py @@ -0,0 +1,434 @@ +# -*- 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_accounts_v1beta.types import termsofservice +from .base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import TermsOfServiceServiceGrpcTransport + +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.accounts.v1beta.TermsOfServiceService", + "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.accounts.v1beta.TermsOfServiceService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class TermsOfServiceServiceGrpcAsyncIOTransport(TermsOfServiceServiceTransport): + """gRPC AsyncIO backend transport for TermsOfServiceService. + + Service to support ``TermsOfService`` API. + + 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 get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + Awaitable[termsofservice.TermsOfService]]: + r"""Return a callable for the get terms of service method over gRPC. + + Retrieves the ``TermsOfService`` associated with the provided + version. + + Returns: + Callable[[~.GetTermsOfServiceRequest], + Awaitable[~.TermsOfService]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_terms_of_service' not in self._stubs: + self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/GetTermsOfService', + request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['get_terms_of_service'] + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + Awaitable[termsofservice.TermsOfService]]: + r"""Return a callable for the retrieve latest terms of + service method over gRPC. + + Retrieves the latest version of the ``TermsOfService`` for a + given ``kind`` and ``region_code``. + + Returns: + Callable[[~.RetrieveLatestTermsOfServiceRequest], + Awaitable[~.TermsOfService]]: + 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 'retrieve_latest_terms_of_service' not in self._stubs: + self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/RetrieveLatestTermsOfService', + request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, + response_deserializer=termsofservice.TermsOfService.deserialize, + ) + return self._stubs['retrieve_latest_terms_of_service'] + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the accept terms of service method over gRPC. + + Accepts a ``TermsOfService``. Executing this method requires + admin access. + + Returns: + Callable[[~.AcceptTermsOfServiceRequest], + 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 'accept_terms_of_service' not in self._stubs: + self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/AcceptTermsOfService', + request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['accept_terms_of_service'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_terms_of_service: self._wrap_method( + self.get_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_latest_terms_of_service: self._wrap_method( + self.retrieve_latest_terms_of_service, + default_timeout=None, + client_info=client_info, + ), + self.accept_terms_of_service: self._wrap_method( + self.accept_terms_of_service, + 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__ = ( + 'TermsOfServiceServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py new file mode 100644 index 000000000000..6f19b49a6583 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py @@ -0,0 +1,630 @@ +# -*- 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_accounts_v1beta.types import termsofservice + + +from .rest_base import _BaseTermsOfServiceServiceRestTransport +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 TermsOfServiceServiceRestInterceptor: + """Interceptor for TermsOfServiceService. + + 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 TermsOfServiceServiceRestTransport. + + .. code-block:: python + class MyCustomTermsOfServiceServiceInterceptor(TermsOfServiceServiceRestInterceptor): + def pre_accept_terms_of_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_terms_of_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_terms_of_service(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_latest_terms_of_service(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_latest_terms_of_service(self, response): + logging.log(f"Received response: {response}") + return response + + transport = TermsOfServiceServiceRestTransport(interceptor=MyCustomTermsOfServiceServiceInterceptor()) + client = TermsOfServiceServiceClient(transport=transport) + + + """ + def pre_accept_terms_of_service(self, request: termsofservice.AcceptTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for accept_terms_of_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceService server. + """ + return request, metadata + + def pre_get_terms_of_service(self, request: termsofservice.GetTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_terms_of_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceService server. + """ + return request, metadata + + def post_get_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: + """Post-rpc interceptor for get_terms_of_service + + DEPRECATED. Please use the `post_get_terms_of_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. This `post_get_terms_of_service` interceptor runs + before the `post_get_terms_of_service_with_metadata` interceptor. + """ + return response + + def post_get_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_terms_of_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceService server but before it is returned to user code. + + We recommend only using this `post_get_terms_of_service_with_metadata` + interceptor in new development instead of the `post_get_terms_of_service` interceptor. + When both interceptors are used, this `post_get_terms_of_service_with_metadata` interceptor runs after the + `post_get_terms_of_service` interceptor. The (possibly modified) response returned by + `post_get_terms_of_service` will be passed to + `post_get_terms_of_service_with_metadata`. + """ + return response, metadata + + def pre_retrieve_latest_terms_of_service(self, request: termsofservice.RetrieveLatestTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for retrieve_latest_terms_of_service + + Override in a subclass to manipulate the request or metadata + before they are sent to the TermsOfServiceService server. + """ + return request, metadata + + def post_retrieve_latest_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: + """Post-rpc interceptor for retrieve_latest_terms_of_service + + DEPRECATED. Please use the `post_retrieve_latest_terms_of_service_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the TermsOfServiceService server but before + it is returned to user code. This `post_retrieve_latest_terms_of_service` interceptor runs + before the `post_retrieve_latest_terms_of_service_with_metadata` interceptor. + """ + return response + + def post_retrieve_latest_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for retrieve_latest_terms_of_service + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the TermsOfServiceService server but before it is returned to user code. + + We recommend only using this `post_retrieve_latest_terms_of_service_with_metadata` + interceptor in new development instead of the `post_retrieve_latest_terms_of_service` interceptor. + When both interceptors are used, this `post_retrieve_latest_terms_of_service_with_metadata` interceptor runs after the + `post_retrieve_latest_terms_of_service` interceptor. The (possibly modified) response returned by + `post_retrieve_latest_terms_of_service` will be passed to + `post_retrieve_latest_terms_of_service_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class TermsOfServiceServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: TermsOfServiceServiceRestInterceptor + + +class TermsOfServiceServiceRestTransport(_BaseTermsOfServiceServiceRestTransport): + """REST backend synchronous transport for TermsOfServiceService. + + Service to support ``TermsOfService`` API. + + 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[TermsOfServiceServiceRestInterceptor] = 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 TermsOfServiceServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AcceptTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService, TermsOfServiceServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceServiceRestTransport.AcceptTermsOfService") + + @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: termsofservice.AcceptTermsOfServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the accept terms of service method over HTTP. + + Args: + request (~.termsofservice.AcceptTermsOfServiceRequest): + The request object. Request message for the ``AcceptTermsOfService`` 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 = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_http_options() + + request, metadata = self._interceptor.pre_accept_terms_of_service(request, metadata) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceServiceClient.AcceptTermsOfService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "rpcName": "AcceptTermsOfService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceServiceRestTransport._AcceptTermsOfService._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 _GetTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService, TermsOfServiceServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceServiceRestTransport.GetTermsOfService") + + @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: termsofservice.GetTermsOfServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofservice.TermsOfService: + r"""Call the get terms of service method over HTTP. + + Args: + request (~.termsofservice.GetTermsOfServiceRequest): + The request object. Request message for the ``GetTermsOfService`` 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: + ~.termsofservice.TermsOfService: + A ``TermsOfService``. + """ + + http_options = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_http_options() + + request, metadata = self._interceptor.pre_get_terms_of_service(request, metadata) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceServiceClient.GetTermsOfService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "rpcName": "GetTermsOfService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceServiceRestTransport._GetTermsOfService._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 = termsofservice.TermsOfService() + pb_resp = termsofservice.TermsOfService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_terms_of_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_terms_of_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofservice.TermsOfService.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.accounts_v1beta.TermsOfServiceServiceClient.get_terms_of_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "rpcName": "GetTermsOfService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RetrieveLatestTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService, TermsOfServiceServiceRestStub): + def __hash__(self): + return hash("TermsOfServiceServiceRestTransport.RetrieveLatestTermsOfService") + + @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: termsofservice.RetrieveLatestTermsOfServiceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> termsofservice.TermsOfService: + r"""Call the retrieve latest terms of + service method over HTTP. + + Args: + request (~.termsofservice.RetrieveLatestTermsOfServiceRequest): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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: + ~.termsofservice.TermsOfService: + A ``TermsOfService``. + """ + + http_options = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_http_options() + + request, metadata = self._interceptor.pre_retrieve_latest_terms_of_service(request, metadata) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceServiceClient.RetrieveLatestTermsOfService", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "rpcName": "RetrieveLatestTermsOfService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = TermsOfServiceServiceRestTransport._RetrieveLatestTermsOfService._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 = termsofservice.TermsOfService() + pb_resp = termsofservice.TermsOfService.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_latest_terms_of_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_retrieve_latest_terms_of_service_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = termsofservice.TermsOfService.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.accounts_v1beta.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "rpcName": "RetrieveLatestTermsOfService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def accept_terms_of_service(self) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + 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._AcceptTermsOfService(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_terms_of_service(self) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + termsofservice.TermsOfService]: + # 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._GetTermsOfService(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_latest_terms_of_service(self) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + termsofservice.TermsOfService]: + # 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._RetrieveLatestTermsOfService(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'TermsOfServiceServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py new file mode 100644 index 000000000000..5e200fbf9992 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py @@ -0,0 +1,203 @@ +# -*- 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 TermsOfServiceServiceTransport, 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_accounts_v1beta.types import termsofservice + + +class _BaseTermsOfServiceServiceRestTransport(TermsOfServiceServiceTransport): + """Base REST backend transport for TermsOfServiceService. + + 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 _BaseAcceptTermsOfService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "account" : "", "regionCode" : "", } + + @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': '/accounts/v1beta/{name=termsOfService/*}:accept', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofservice.AcceptTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTermsOfService: + 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': '/accounts/v1beta/{name=termsOfService/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofservice.GetTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRetrieveLatestTermsOfService: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "regionCode" : "", "kind" : {}, } + + @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': '/accounts/v1beta/termsOfService:retrieveLatest', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = termsofservice.RetrieveLatestTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseTermsOfServiceServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/__init__.py new file mode 100644 index 000000000000..d60a27bcbaf8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_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 UserServiceClient +from .async_client import UserServiceAsyncClient + +__all__ = ( + 'UserServiceClient', + 'UserServiceAsyncClient', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py new file mode 100644 index 000000000000..48734d9b5d9d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py @@ -0,0 +1,827 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.user_service import pagers +from google.shopping.merchant_accounts_v1beta.types import accessright +from google.shopping.merchant_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user +from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport +from .client import UserServiceClient + +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 UserServiceAsyncClient: + """Service to support user API.""" + + _client: UserServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = UserServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = UserServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(UserServiceClient.account_path) + parse_account_path = staticmethod(UserServiceClient.parse_account_path) + user_path = staticmethod(UserServiceClient.user_path) + parse_user_path = staticmethod(UserServiceClient.parse_user_path) + common_billing_account_path = staticmethod(UserServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserServiceClient.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: + UserServiceAsyncClient: The constructed client. + """ + return UserServiceClient.from_service_account_info.__func__(UserServiceAsyncClient, 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: + UserServiceAsyncClient: The constructed client. + """ + return UserServiceClient.from_service_account_file.__func__(UserServiceAsyncClient, 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 UserServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserServiceTransport: 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 = UserServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, UserServiceTransport, Callable[..., UserServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user 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,UserServiceTransport,Callable[..., UserServiceTransport]]]): + 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 UserServiceTransport 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 = UserServiceClient( + 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.accounts_v1beta.UserServiceAsyncClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "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.accounts.v1beta.UserService", + "credentialsType": None, + } + ) + + async def get_user(self, + request: Optional[Union[user.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: + r"""Retrieves a Merchant Center account user. + + .. 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_accounts_v1beta + + async def sample_get_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetUserRequest, dict]]): + The request object. Request message for the ``GetUser`` method. + name (:class:`str`): + Required. The name of the user to retrieve. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to retrieve the user corresponding + to the caller by using ``me`` rather than an email + address as in ``accounts/{account}/users/me``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.User: + A + [user](https://support.google.com/merchants/answer/12160472). + + """ + # 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, user.GetUserRequest): + request = user.GetUserRequest(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.get_user] + + # 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. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_user(self, + request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[gsma_user.User] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Creates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_create_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateUserRequest, dict]]): + The request object. Request message for the ``CreateUser`` method. + parent (:class:`str`): + Required. The resource name of the account for which a + user will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`google.shopping.merchant_accounts_v1beta.types.User`): + Required. The user to create. + This corresponds to the ``user`` 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_accounts_v1beta.types.User: + A + [user](https://support.google.com/merchants/answer/12160472). + + """ + # 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, user] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.CreateUserRequest): + request = gsma_user.CreateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_user] + + # 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_user(self, + request: Optional[Union[user.DeleteUserRequest, dict]] = None, + *, + name: 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 a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_delete_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest, dict]]): + The request object. Request message for the ``DeleteUser`` method. + name (:class:`str`): + Required. The name of the user to delete. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to delete the user corresponding to + the caller by using ``me`` rather than an email address + as in ``accounts/{account}/users/me``. + + 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, user.DeleteUserRequest): + request = user.DeleteUserRequest(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_user] + + # 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 update_user(self, + request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, + *, + user: Optional[gsma_user.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Updates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + async def sample_update_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest, dict]]): + The request object. Request message for the ``UpdateUser`` method. + user (:class:`google.shopping.merchant_accounts_v1beta.types.User`): + Required. The new version of the user. + + Use ``me`` to refer to your own email address, for + example ``accounts/{account}/users/me``. + + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.User: + A + [user](https://support.google.com/merchants/answer/12160472). + + """ + # 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 = [user, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.UpdateUserRequest): + request = gsma_user.UpdateUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # 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 list_users(self, + request: Optional[Union[user.ListUsersRequest, 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.ListUsersAsyncPager: + r"""Lists all users of a Merchant Center 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_accounts_v1beta + + async def sample_list_users(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListUsersRequest, dict]]): + The request object. Request message for the ``ListUsers`` method. + parent (:class:`str`): + Required. The parent, which owns this collection of + users. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.user_service.pagers.ListUsersAsyncPager: + Response message for the ListUsers 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, user.ListUsersRequest): + request = user.ListUsersRequest(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_users] + + # 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.ListUsersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "UserServiceAsyncClient": + 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__ = ( + "UserServiceAsyncClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py new file mode 100644 index 000000000000..9756aa826c98 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py @@ -0,0 +1,1192 @@ +# -*- 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_accounts_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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.user_service import pagers +from google.shopping.merchant_accounts_v1beta.types import accessright +from google.shopping.merchant_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user +from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserServiceGrpcTransport +from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport +from .transports.rest import UserServiceRestTransport + + +class UserServiceClientMeta(type): + """Metaclass for the UserService 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[UserServiceTransport]] + _transport_registry["grpc"] = UserServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[UserServiceTransport]: + """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 UserServiceClient(metaclass=UserServiceClientMeta): + """Service to support user API.""" + + @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: + UserServiceClient: 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: + UserServiceClient: 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) -> UserServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def user_path(account: str,email: str,) -> str: + """Returns a fully-qualified user string.""" + return "accounts/{account}/users/{email}".format(account=account, email=email, ) + + @staticmethod + def parse_user_path(path: str) -> Dict[str,str]: + """Parses a user path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/users/(?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 = UserServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = UserServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = UserServiceClient._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 = UserServiceClient._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, UserServiceTransport, Callable[..., UserServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user 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,UserServiceTransport,Callable[..., UserServiceTransport]]]): + 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 UserServiceTransport 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 = UserServiceClient._read_environment_variables() + self._client_cert_source = UserServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = UserServiceClient._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, UserServiceTransport) + if transport_provided: + # transport is a UserServiceTransport 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(UserServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + UserServiceClient._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[UserServiceTransport], Callable[..., UserServiceTransport]] = ( + UserServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., UserServiceTransport], 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.accounts_v1beta.UserServiceClient`.", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "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.accounts.v1beta.UserService", + "credentialsType": None, + } + ) + + def get_user(self, + request: Optional[Union[user.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: + r"""Retrieves a Merchant Center account user. + + .. 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_accounts_v1beta + + def sample_get_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.GetUserRequest, dict]): + The request object. Request message for the ``GetUser`` method. + name (str): + Required. The name of the user to retrieve. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to retrieve the user corresponding + to the caller by using ``me`` rather than an email + address as in ``accounts/{account}/users/me``. + + 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`. + + Returns: + google.shopping.merchant_accounts_v1beta.types.User: + A + [user](https://support.google.com/merchants/answer/12160472). + + """ + # 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, user.GetUserRequest): + request = user.GetUserRequest(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.get_user] + + # 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. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_user(self, + request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[gsma_user.User] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Creates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + def sample_create_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.CreateUserRequest, dict]): + The request object. Request message for the ``CreateUser`` method. + parent (str): + Required. The resource name of the account for which a + user will be created. Format: ``accounts/{account}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (google.shopping.merchant_accounts_v1beta.types.User): + Required. The user to create. + This corresponds to the ``user`` 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_accounts_v1beta.types.User: + A + [user](https://support.google.com/merchants/answer/12160472). + + """ + # 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, user] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.CreateUserRequest): + request = gsma_user.CreateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if user is not None: + request.user = user + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_user] + + # 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_user(self, + request: Optional[Union[user.DeleteUserRequest, dict]] = None, + *, + name: 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 a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + def sample_delete_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest, dict]): + The request object. Request message for the ``DeleteUser`` method. + name (str): + Required. The name of the user to delete. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to delete the user corresponding to + the caller by using ``me`` rather than an email address + as in ``accounts/{account}/users/me``. + + 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, user.DeleteUserRequest): + request = user.DeleteUserRequest(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_user] + + # 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 update_user(self, + request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, + *, + user: Optional[gsma_user.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: + r"""Updates a Merchant Center account user. Executing + this method requires admin access. + + .. 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_accounts_v1beta + + def sample_update_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest, dict]): + The request object. Request message for the ``UpdateUser`` method. + user (google.shopping.merchant_accounts_v1beta.types.User): + Required. The new version of the user. + + Use ``me`` to refer to your own email address, for + example ``accounts/{account}/users/me``. + + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being + updated. + + This corresponds to the ``update_mask`` 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_accounts_v1beta.types.User: + A + [user](https://support.google.com/merchants/answer/12160472). + + """ + # 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 = [user, update_mask] + has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + if request is 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, gsma_user.UpdateUserRequest): + request = gsma_user.UpdateUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if user is not None: + request.user = user + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("user.name", request.user.name), + )), + ) + + # 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 list_users(self, + request: Optional[Union[user.ListUsersRequest, 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.ListUsersPager: + r"""Lists all users of a Merchant Center 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_accounts_v1beta + + def sample_list_users(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.shopping.merchant_accounts_v1beta.types.ListUsersRequest, dict]): + The request object. Request message for the ``ListUsers`` method. + parent (str): + Required. The parent, which owns this collection of + users. Format: ``accounts/{account}`` + + 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_accounts_v1beta.services.user_service.pagers.ListUsersPager: + Response message for the ListUsers 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, user.ListUsersRequest): + request = user.ListUsersRequest(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_users] + + # 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.ListUsersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserServiceClient": + 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__ = ( + "UserServiceClient", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py new file mode 100644 index 000000000000..8b1b771c7d7c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_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_accounts_v1beta.types import user + + +class ListUsersPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` + 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[..., user.ListUsersResponse], + request: user.ListUsersRequest, + response: user.ListUsersResponse, + *, + 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_accounts_v1beta.types.ListUsersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListUsersResponse): + 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 = user.ListUsersRequest(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[user.ListUsersResponse]: + 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[user.User]: + for page in self.pages: + yield from page.users + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListUsersAsyncPager: + """A pager for iterating through ``list_users`` requests. + + This class thinly wraps an initial + :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListUsers`` requests and continue to iterate + through the ``users`` field on the + corresponding responses. + + All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` + 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[user.ListUsersResponse]], + request: user.ListUsersRequest, + response: user.ListUsersResponse, + *, + 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_accounts_v1beta.types.ListUsersRequest): + The initial request object. + response (google.shopping.merchant_accounts_v1beta.types.ListUsersResponse): + 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 = user.ListUsersRequest(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[user.ListUsersResponse]: + 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[user.User]: + async def async_generator(): + async for page in self.pages: + for response in page.users: + 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst new file mode 100644 index 000000000000..815387def1a4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`UserServiceTransport` is the ABC for all transports. +- public child `UserServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `UserServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseUserServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `UserServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/__init__.py new file mode 100644 index 000000000000..b8429533bdc0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_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 UserServiceTransport +from .grpc import UserServiceGrpcTransport +from .grpc_asyncio import UserServiceGrpcAsyncIOTransport +from .rest import UserServiceRestTransport +from .rest import UserServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserServiceTransport]] +_transport_registry['grpc'] = UserServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserServiceGrpcAsyncIOTransport +_transport_registry['rest'] = UserServiceRestTransport + +__all__ = ( + 'UserServiceTransport', + 'UserServiceGrpcTransport', + 'UserServiceGrpcAsyncIOTransport', + 'UserServiceRestTransport', + 'UserServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py new file mode 100644 index 000000000000..ab10f30f7dc8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py @@ -0,0 +1,217 @@ +# -*- 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_accounts_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_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user + +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 UserServiceTransport(abc.ABC): + """Abstract transport class for UserService.""" + + 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.get_user: gapic_v1.method.wrap_method( + self.get_user, + default_timeout=None, + client_info=client_info, + ), + self.create_user: gapic_v1.method.wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: gapic_v1.method.wrap_method( + self.delete_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: gapic_v1.method.wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.list_users: gapic_v1.method.wrap_method( + self.list_users, + 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 get_user(self) -> Callable[ + [user.GetUserRequest], + Union[ + user.User, + Awaitable[user.User] + ]]: + raise NotImplementedError() + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + Union[ + gsma_user.User, + Awaitable[gsma_user.User] + ]]: + raise NotImplementedError() + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + Union[ + gsma_user.User, + Awaitable[gsma_user.User] + ]]: + raise NotImplementedError() + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + Union[ + user.ListUsersResponse, + Awaitable[user.ListUsersResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserServiceTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py new file mode 100644 index 000000000000..e71109e7ff7c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py @@ -0,0 +1,455 @@ +# -*- 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_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user +from .base import UserServiceTransport, 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.accounts.v1beta.UserService", + "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.accounts.v1beta.UserService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class UserServiceGrpcTransport(UserServiceTransport): + """gRPC backend transport for UserService. + + Service to support user API. + + 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 get_user(self) -> Callable[ + [user.GetUserRequest], + user.User]: + r"""Return a callable for the get user method over gRPC. + + Retrieves a Merchant Center account user. + + Returns: + Callable[[~.GetUserRequest], + ~.User]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_user' not in self._stubs: + self._stubs['get_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/GetUser', + request_serializer=user.GetUserRequest.serialize, + response_deserializer=user.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + gsma_user.User]: + r"""Return a callable for the create user method over gRPC. + + Creates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.CreateUserRequest], + ~.User]: + 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 'create_user' not in self._stubs: + self._stubs['create_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/CreateUser', + request_serializer=gsma_user.CreateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.DeleteUserRequest], + ~.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_user' not in self._stubs: + self._stubs['delete_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/DeleteUser', + request_serializer=user.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + gsma_user.User]: + r"""Return a callable for the update user method over gRPC. + + Updates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateUserRequest], + ~.User]: + 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 'update_user' not in self._stubs: + self._stubs['update_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/UpdateUser', + request_serializer=gsma_user.UpdateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + user.ListUsersResponse]: + r"""Return a callable for the list users method over gRPC. + + Lists all users of a Merchant Center account. + + Returns: + Callable[[~.ListUsersRequest], + ~.ListUsersResponse]: + 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_users' not in self._stubs: + self._stubs['list_users'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/ListUsers', + request_serializer=user.ListUsersRequest.serialize, + response_deserializer=user.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..de69a24dbbf8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py @@ -0,0 +1,496 @@ +# -*- 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_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user +from .base import UserServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserServiceGrpcTransport + +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.accounts.v1beta.UserService", + "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.accounts.v1beta.UserService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class UserServiceGrpcAsyncIOTransport(UserServiceTransport): + """gRPC AsyncIO backend transport for UserService. + + Service to support user API. + + 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 get_user(self) -> Callable[ + [user.GetUserRequest], + Awaitable[user.User]]: + r"""Return a callable for the get user method over gRPC. + + Retrieves a Merchant Center account user. + + Returns: + Callable[[~.GetUserRequest], + Awaitable[~.User]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_user' not in self._stubs: + self._stubs['get_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/GetUser', + request_serializer=user.GetUserRequest.serialize, + response_deserializer=user.User.deserialize, + ) + return self._stubs['get_user'] + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + Awaitable[gsma_user.User]]: + r"""Return a callable for the create user method over gRPC. + + Creates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.CreateUserRequest], + Awaitable[~.User]]: + 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 'create_user' not in self._stubs: + self._stubs['create_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/CreateUser', + request_serializer=gsma_user.CreateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['create_user'] + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete user method over gRPC. + + Deletes a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.DeleteUserRequest], + 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_user' not in self._stubs: + self._stubs['delete_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/DeleteUser', + request_serializer=user.DeleteUserRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_user'] + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + Awaitable[gsma_user.User]]: + r"""Return a callable for the update user method over gRPC. + + Updates a Merchant Center account user. Executing + this method requires admin access. + + Returns: + Callable[[~.UpdateUserRequest], + Awaitable[~.User]]: + 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 'update_user' not in self._stubs: + self._stubs['update_user'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/UpdateUser', + request_serializer=gsma_user.UpdateUserRequest.serialize, + response_deserializer=gsma_user.User.deserialize, + ) + return self._stubs['update_user'] + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + Awaitable[user.ListUsersResponse]]: + r"""Return a callable for the list users method over gRPC. + + Lists all users of a Merchant Center account. + + Returns: + Callable[[~.ListUsersRequest], + Awaitable[~.ListUsersResponse]]: + 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_users' not in self._stubs: + self._stubs['list_users'] = self._logged_channel.unary_unary( + '/google.shopping.merchant.accounts.v1beta.UserService/ListUsers', + request_serializer=user.ListUsersRequest.serialize, + response_deserializer=user.ListUsersResponse.deserialize, + ) + return self._stubs['list_users'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_user: self._wrap_method( + self.get_user, + default_timeout=None, + client_info=client_info, + ), + self.create_user: self._wrap_method( + self.create_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_user: self._wrap_method( + self.delete_user, + default_timeout=None, + client_info=client_info, + ), + self.update_user: self._wrap_method( + self.update_user, + default_timeout=None, + client_info=client_info, + ), + self.list_users: self._wrap_method( + self.list_users, + 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__ = ( + 'UserServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py new file mode 100644 index 000000000000..822c4b850064 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py @@ -0,0 +1,983 @@ +# -*- 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_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user + + +from .rest_base import _BaseUserServiceRestTransport +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 UserServiceRestInterceptor: + """Interceptor for UserService. + + 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 UserServiceRestTransport. + + .. code-block:: python + class MyCustomUserServiceInterceptor(UserServiceRestInterceptor): + def pre_create_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_user(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserServiceRestTransport(interceptor=MyCustomUserServiceInterceptor()) + client = UserServiceClient(transport=transport) + + + """ + def pre_create_user(self, request: gsma_user.CreateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_create_user(self, response: gsma_user.User) -> gsma_user.User: + """Post-rpc interceptor for create_user + + DEPRECATED. Please use the `post_create_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_create_user` interceptor runs + before the `post_create_user_with_metadata` interceptor. + """ + return response + + def post_create_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_create_user_with_metadata` + interceptor in new development instead of the `post_create_user` interceptor. + When both interceptors are used, this `post_create_user_with_metadata` interceptor runs after the + `post_create_user` interceptor. The (possibly modified) response returned by + `post_create_user` will be passed to + `post_create_user_with_metadata`. + """ + return response, metadata + + def pre_delete_user(self, request: user.DeleteUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def pre_get_user(self, request: user.GetUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_get_user(self, response: user.User) -> user.User: + """Post-rpc interceptor for get_user + + DEPRECATED. Please use the `post_get_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_get_user` interceptor runs + before the `post_get_user_with_metadata` interceptor. + """ + return response + + def post_get_user_with_metadata(self, response: user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_get_user_with_metadata` + interceptor in new development instead of the `post_get_user` interceptor. + When both interceptors are used, this `post_get_user_with_metadata` interceptor runs after the + `post_get_user` interceptor. The (possibly modified) response returned by + `post_get_user` will be passed to + `post_get_user_with_metadata`. + """ + return response, metadata + + def pre_list_users(self, request: user.ListUsersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_list_users(self, response: user.ListUsersResponse) -> user.ListUsersResponse: + """Post-rpc interceptor for list_users + + DEPRECATED. Please use the `post_list_users_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_list_users` interceptor runs + before the `post_list_users_with_metadata` interceptor. + """ + return response + + def post_list_users_with_metadata(self, response: user.ListUsersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_users + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_list_users_with_metadata` + interceptor in new development instead of the `post_list_users` interceptor. + When both interceptors are used, this `post_list_users_with_metadata` interceptor runs after the + `post_list_users` interceptor. The (possibly modified) response returned by + `post_list_users` will be passed to + `post_list_users_with_metadata`. + """ + return response, metadata + + def pre_update_user(self, request: gsma_user.UpdateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserService server. + """ + return request, metadata + + def post_update_user(self, response: gsma_user.User) -> gsma_user.User: + """Post-rpc interceptor for update_user + + DEPRECATED. Please use the `post_update_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the UserService server but before + it is returned to user code. This `post_update_user` interceptor runs + before the `post_update_user_with_metadata` interceptor. + """ + return response + + def post_update_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the UserService server but before it is returned to user code. + + We recommend only using this `post_update_user_with_metadata` + interceptor in new development instead of the `post_update_user` interceptor. + When both interceptors are used, this `post_update_user_with_metadata` interceptor runs after the + `post_update_user` interceptor. The (possibly modified) response returned by + `post_update_user` will be passed to + `post_update_user_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class UserServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserServiceRestInterceptor + + +class UserServiceRestTransport(_BaseUserServiceRestTransport): + """REST backend synchronous transport for UserService. + + Service to support user API. + + 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[UserServiceRestInterceptor] = 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 UserServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateUser(_BaseUserServiceRestTransport._BaseCreateUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.CreateUser") + + @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: gsma_user.CreateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_user.User: + r"""Call the create user method over HTTP. + + Args: + request (~.gsma_user.CreateUserRequest): + The request object. Request message for the ``CreateUser`` 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: + ~.gsma_user.User: + A + `user `__. + + """ + + http_options = _BaseUserServiceRestTransport._BaseCreateUser._get_http_options() + + request, metadata = self._interceptor.pre_create_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseCreateUser._get_transcoded_request(http_options, request) + + body = _BaseUserServiceRestTransport._BaseCreateUser._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseCreateUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.CreateUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "CreateUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._CreateUser._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 = gsma_user.User() + pb_resp = gsma_user.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_user.User.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.accounts_v1beta.UserServiceClient.create_user", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "CreateUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteUser(_BaseUserServiceRestTransport._BaseDeleteUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.DeleteUser") + + @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: user.DeleteUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete user method over HTTP. + + Args: + request (~.user.DeleteUserRequest): + The request object. Request message for the ``DeleteUser`` 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 = _BaseUserServiceRestTransport._BaseDeleteUser._get_http_options() + + request, metadata = self._interceptor.pre_delete_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseDeleteUser._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseDeleteUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.DeleteUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "DeleteUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._DeleteUser._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 _GetUser(_BaseUserServiceRestTransport._BaseGetUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.GetUser") + + @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: user.GetUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> user.User: + r"""Call the get user method over HTTP. + + Args: + request (~.user.GetUserRequest): + The request object. Request message for the ``GetUser`` 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: + ~.user.User: + A + `user `__. + + """ + + http_options = _BaseUserServiceRestTransport._BaseGetUser._get_http_options() + + request, metadata = self._interceptor.pre_get_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseGetUser._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseGetUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.GetUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "GetUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._GetUser._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 = user.User() + pb_resp = user.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = user.User.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.accounts_v1beta.UserServiceClient.get_user", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "GetUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListUsers(_BaseUserServiceRestTransport._BaseListUsers, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.ListUsers") + + @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: user.ListUsersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> user.ListUsersResponse: + r"""Call the list users method over HTTP. + + Args: + request (~.user.ListUsersRequest): + The request object. Request message for the ``ListUsers`` 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: + ~.user.ListUsersResponse: + Response message for the ``ListUsers`` method. + """ + + http_options = _BaseUserServiceRestTransport._BaseListUsers._get_http_options() + + request, metadata = self._interceptor.pre_list_users(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseListUsers._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseListUsers._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.ListUsers", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "ListUsers", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._ListUsers._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 = user.ListUsersResponse() + pb_resp = user.ListUsersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_users(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_users_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = user.ListUsersResponse.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.accounts_v1beta.UserServiceClient.list_users", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "ListUsers", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateUser(_BaseUserServiceRestTransport._BaseUpdateUser, UserServiceRestStub): + def __hash__(self): + return hash("UserServiceRestTransport.UpdateUser") + + @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: gsma_user.UpdateUserRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> gsma_user.User: + r"""Call the update user method over HTTP. + + Args: + request (~.gsma_user.UpdateUserRequest): + The request object. Request message for the ``UpdateUser`` 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: + ~.gsma_user.User: + A + `user `__. + + """ + + http_options = _BaseUserServiceRestTransport._BaseUpdateUser._get_http_options() + + request, metadata = self._interceptor.pre_update_user(request, metadata) + transcoded_request = _BaseUserServiceRestTransport._BaseUpdateUser._get_transcoded_request(http_options, request) + + body = _BaseUserServiceRestTransport._BaseUpdateUser._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseUserServiceRestTransport._BaseUpdateUser._get_query_params_json(transcoded_request) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.UpdateUser", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "UpdateUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = UserServiceRestTransport._UpdateUser._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 = gsma_user.User() + pb_resp = gsma_user.User.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_user_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = gsma_user.User.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.accounts_v1beta.UserServiceClient.update_user", + extra = { + "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", + "rpcName": "UpdateUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_user(self) -> Callable[ + [gsma_user.CreateUserRequest], + gsma_user.User]: + # 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._CreateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_user(self) -> Callable[ + [user.DeleteUserRequest], + 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._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_user(self) -> Callable[ + [user.GetUserRequest], + user.User]: + # 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._GetUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_users(self) -> Callable[ + [user.ListUsersRequest], + user.ListUsersResponse]: + # 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._ListUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_user(self) -> Callable[ + [gsma_user.UpdateUserRequest], + gsma_user.User]: + # 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._UpdateUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'UserServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py new file mode 100644 index 000000000000..e015cbbed371 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py @@ -0,0 +1,298 @@ +# -*- 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 UserServiceTransport, 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_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user + + +class _BaseUserServiceRestTransport(UserServiceTransport): + """Base REST backend transport for UserService. + + 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 _BaseCreateUser: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userId" : "", } + + @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': '/accounts/v1beta/{parent=accounts/*}/users', + 'body': 'user', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_user.CreateUserRequest.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(_BaseUserServiceRestTransport._BaseCreateUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteUser: + 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': '/accounts/v1beta/{name=accounts/*/users/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user.DeleteUserRequest.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(_BaseUserServiceRestTransport._BaseDeleteUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetUser: + 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': '/accounts/v1beta/{name=accounts/*/users/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user.GetUserRequest.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(_BaseUserServiceRestTransport._BaseGetUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListUsers: + 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': '/accounts/v1beta/{parent=accounts/*}/users', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = user.ListUsersRequest.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(_BaseUserServiceRestTransport._BaseListUsers._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateUser: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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': 'patch', + 'uri': '/accounts/v1beta/{user.name=accounts/*/users/*}', + 'body': 'user', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gsma_user.UpdateUserRequest.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(_BaseUserServiceRestTransport._BaseUpdateUser._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__=( + '_BaseUserServiceRestTransport', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py new file mode 100644 index 000000000000..79ebdd0dd449 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py @@ -0,0 +1,338 @@ +# -*- 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 .accessright import ( + AccessRight, +) +from .account_tax import ( + AccountTax, + GetAccountTaxRequest, + ListAccountTaxRequest, + ListAccountTaxResponse, + UpdateAccountTaxRequest, +) +from .accountissue import ( + AccountIssue, + ListAccountIssuesRequest, + ListAccountIssuesResponse, +) +from .accounts import ( + Account, + CreateAndConfigureAccountRequest, + DeleteAccountRequest, + GetAccountRequest, + ListAccountsRequest, + ListAccountsResponse, + ListSubAccountsRequest, + ListSubAccountsResponse, + UpdateAccountRequest, +) +from .accountservices import ( + AccountAggregation, +) +from .autofeedsettings import ( + AutofeedSettings, + GetAutofeedSettingsRequest, + UpdateAutofeedSettingsRequest, +) +from .automaticimprovements import ( + AutomaticImageImprovements, + AutomaticImprovements, + AutomaticItemUpdates, + AutomaticShippingImprovements, + GetAutomaticImprovementsRequest, + UpdateAutomaticImprovementsRequest, +) +from .businessidentity import ( + BusinessIdentity, + GetBusinessIdentityRequest, + UpdateBusinessIdentityRequest, +) +from .businessinfo import ( + BusinessInfo, + GetBusinessInfoRequest, + UpdateBusinessInfoRequest, +) +from .checkoutsettings import ( + CheckoutSettings, + CreateCheckoutSettingsRequest, + DeleteCheckoutSettingsRequest, + GetCheckoutSettingsRequest, + UpdateCheckoutSettingsRequest, + UriSettings, +) +from .customerservice import ( + CustomerService, +) +from .emailpreferences import ( + EmailPreferences, + GetEmailPreferencesRequest, + UpdateEmailPreferencesRequest, +) +from .gbpaccounts import ( + GbpAccount, + LinkGbpAccountRequest, + LinkGbpAccountResponse, + ListGbpAccountsRequest, + ListGbpAccountsResponse, +) +from .homepage import ( + ClaimHomepageRequest, + GetHomepageRequest, + Homepage, + UnclaimHomepageRequest, + UpdateHomepageRequest, +) +from .lfpproviders import ( + FindLfpProvidersRequest, + FindLfpProvidersResponse, + LfpProvider, + LinkLfpProviderRequest, + LinkLfpProviderResponse, +) +from .omnichannelsettings import ( + About, + CreateOmnichannelSettingRequest, + GetOmnichannelSettingRequest, + InStock, + InventoryVerification, + LfpLink, + ListOmnichannelSettingsRequest, + ListOmnichannelSettingsResponse, + OmnichannelSetting, + OnDisplayToOrder, + Pickup, + RequestInventoryVerificationRequest, + RequestInventoryVerificationResponse, + ReviewState, + UpdateOmnichannelSettingRequest, +) +from .online_return_policy import ( + CreateOnlineReturnPolicyRequest, + DeleteOnlineReturnPolicyRequest, + GetOnlineReturnPolicyRequest, + ListOnlineReturnPoliciesRequest, + ListOnlineReturnPoliciesResponse, + OnlineReturnPolicy, + UpdateOnlineReturnPolicyRequest, +) +from .phoneverificationstate import ( + PhoneVerificationState, +) +from .programs import ( + DisableProgramRequest, + EnableProgramRequest, + GetProgramRequest, + ListProgramsRequest, + ListProgramsResponse, + Program, +) +from .regions import ( + CreateRegionRequest, + DeleteRegionRequest, + GetRegionRequest, + ListRegionsRequest, + ListRegionsResponse, + Region, + UpdateRegionRequest, +) +from .shippingsettings import ( + Address, + BusinessDayConfig, + CarrierRate, + CutoffTime, + DeliveryTime, + Distance, + GetShippingSettingsRequest, + Headers, + InsertShippingSettingsRequest, + LocationIdSet, + MinimumOrderValueTable, + RateGroup, + Row, + Service, + ShippingSettings, + Table, + TransitTable, + Value, + Warehouse, + WarehouseBasedDeliveryTime, + WarehouseCutoffTime, +) +from .tax_rule import ( + TaxRule, +) +from .termsofservice import ( + AcceptTermsOfServiceRequest, + GetTermsOfServiceRequest, + RetrieveLatestTermsOfServiceRequest, + TermsOfService, +) +from .termsofserviceagreementstate import ( + Accepted, + GetTermsOfServiceAgreementStateRequest, + Required, + RetrieveForApplicationTermsOfServiceAgreementStateRequest, + TermsOfServiceAgreementState, +) +from .termsofservicekind import ( + TermsOfServiceKind, +) +from .user import ( + CreateUserRequest, + DeleteUserRequest, + GetUserRequest, + ListUsersRequest, + ListUsersResponse, + UpdateUserRequest, + User, +) + +__all__ = ( + 'AccessRight', + 'AccountTax', + 'GetAccountTaxRequest', + 'ListAccountTaxRequest', + 'ListAccountTaxResponse', + 'UpdateAccountTaxRequest', + 'AccountIssue', + 'ListAccountIssuesRequest', + 'ListAccountIssuesResponse', + 'Account', + 'CreateAndConfigureAccountRequest', + 'DeleteAccountRequest', + 'GetAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListSubAccountsRequest', + 'ListSubAccountsResponse', + 'UpdateAccountRequest', + 'AccountAggregation', + 'AutofeedSettings', + 'GetAutofeedSettingsRequest', + 'UpdateAutofeedSettingsRequest', + 'AutomaticImageImprovements', + 'AutomaticImprovements', + 'AutomaticItemUpdates', + 'AutomaticShippingImprovements', + 'GetAutomaticImprovementsRequest', + 'UpdateAutomaticImprovementsRequest', + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + 'CheckoutSettings', + 'CreateCheckoutSettingsRequest', + 'DeleteCheckoutSettingsRequest', + 'GetCheckoutSettingsRequest', + 'UpdateCheckoutSettingsRequest', + 'UriSettings', + 'CustomerService', + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + 'GbpAccount', + 'LinkGbpAccountRequest', + 'LinkGbpAccountResponse', + 'ListGbpAccountsRequest', + 'ListGbpAccountsResponse', + 'ClaimHomepageRequest', + 'GetHomepageRequest', + 'Homepage', + 'UnclaimHomepageRequest', + 'UpdateHomepageRequest', + 'FindLfpProvidersRequest', + 'FindLfpProvidersResponse', + 'LfpProvider', + 'LinkLfpProviderRequest', + 'LinkLfpProviderResponse', + 'About', + 'CreateOmnichannelSettingRequest', + 'GetOmnichannelSettingRequest', + 'InStock', + 'InventoryVerification', + 'LfpLink', + 'ListOmnichannelSettingsRequest', + 'ListOmnichannelSettingsResponse', + 'OmnichannelSetting', + 'OnDisplayToOrder', + 'Pickup', + 'RequestInventoryVerificationRequest', + 'RequestInventoryVerificationResponse', + 'ReviewState', + 'UpdateOmnichannelSettingRequest', + 'CreateOnlineReturnPolicyRequest', + 'DeleteOnlineReturnPolicyRequest', + 'GetOnlineReturnPolicyRequest', + 'ListOnlineReturnPoliciesRequest', + 'ListOnlineReturnPoliciesResponse', + 'OnlineReturnPolicy', + 'UpdateOnlineReturnPolicyRequest', + 'PhoneVerificationState', + 'DisableProgramRequest', + 'EnableProgramRequest', + 'GetProgramRequest', + 'ListProgramsRequest', + 'ListProgramsResponse', + 'Program', + 'CreateRegionRequest', + 'DeleteRegionRequest', + 'GetRegionRequest', + 'ListRegionsRequest', + 'ListRegionsResponse', + 'Region', + 'UpdateRegionRequest', + 'Address', + 'BusinessDayConfig', + 'CarrierRate', + 'CutoffTime', + 'DeliveryTime', + 'Distance', + 'GetShippingSettingsRequest', + 'Headers', + 'InsertShippingSettingsRequest', + 'LocationIdSet', + 'MinimumOrderValueTable', + 'RateGroup', + 'Row', + 'Service', + 'ShippingSettings', + 'Table', + 'TransitTable', + 'Value', + 'Warehouse', + 'WarehouseBasedDeliveryTime', + 'WarehouseCutoffTime', + 'TaxRule', + 'AcceptTermsOfServiceRequest', + 'GetTermsOfServiceRequest', + 'RetrieveLatestTermsOfServiceRequest', + 'TermsOfService', + 'Accepted', + 'GetTermsOfServiceAgreementStateRequest', + 'Required', + 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + 'TermsOfServiceAgreementState', + 'TermsOfServiceKind', + 'CreateUserRequest', + 'DeleteUserRequest', + 'GetUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + 'UpdateUserRequest', + 'User', +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.py new file mode 100644 index 000000000000..c3620ee9ff75 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.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 __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'AccessRight', + }, +) + + +class AccessRight(proto.Enum): + r"""The access right. + + Values: + ACCESS_RIGHT_UNSPECIFIED (0): + Default value. This value is unused. + STANDARD (1): + Standard access rights. + ADMIN (2): + Admin access rights. + PERFORMANCE_REPORTING (3): + Users with this right have access to + performance and insights. + """ + ACCESS_RIGHT_UNSPECIFIED = 0 + STANDARD = 1 + ADMIN = 2 + PERFORMANCE_REPORTING = 3 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py new file mode 100644 index 000000000000..57bd399773f3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py @@ -0,0 +1,167 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import tax_rule + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'AccountTax', + 'GetAccountTaxRequest', + 'UpdateAccountTaxRequest', + 'ListAccountTaxRequest', + 'ListAccountTaxResponse', + }, +) + + +class AccountTax(proto.Message): + r"""The tax settings of a merchant account. All methods require + the admin role. + + Attributes: + name (str): + Identifier. The name of the tax setting. Format: + "{account_tax.name=accounts/{account}}". + account (int): + Output only. The ID of the account to which + these account tax settings belong. + tax_rules (MutableSequence[google.shopping.merchant_accounts_v1beta.types.TaxRule]): + Tax rules. "Define the tax rules in each + region. No tax will be presented if a region has + no rule.". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: int = proto.Field( + proto.INT64, + number=2, + ) + tax_rules: MutableSequence[tax_rule.TaxRule] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=tax_rule.TaxRule, + ) + + +class GetAccountTaxRequest(proto.Message): + r"""Request to get tax settings + + Attributes: + name (str): + Required. The name from which tax settings + will be retrieved + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAccountTaxRequest(proto.Message): + r"""Request to update the tax settings + + Attributes: + account_tax (google.shopping.merchant_accounts_v1beta.types.AccountTax): + Required. The tax setting that will be + updated + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated + """ + + account_tax: 'AccountTax' = proto.Field( + proto.MESSAGE, + number=1, + message='AccountTax', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListAccountTaxRequest(proto.Message): + r"""Request to list all sub-account tax settings only for the + requesting merchant This method can only be called on a + multi-client account, otherwise it'll return an error. + + Attributes: + parent (str): + Required. The parent, which owns this + collection of account tax. Format: + accounts/{account} + page_size (int): + The maximum number of tax settings to return + in the response, used for paging. + page_token (str): + The token returned by 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 ListAccountTaxResponse(proto.Message): + r"""Response to account tax list request + This method can only be called on a multi-client account, + otherwise it'll return an error. + + Attributes: + account_taxes (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountTax]): + Page of accounttax settings + next_page_token (str): + The token for the retrieval of the next page + of account tax settings. + """ + + @property + def raw_page(self): + return self + + account_taxes: MutableSequence['AccountTax'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccountTax', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.py new file mode 100644 index 000000000000..5cbd1eb246d3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'AccountIssue', + 'ListAccountIssuesRequest', + 'ListAccountIssuesResponse', + }, +) + + +class AccountIssue(proto.Message): + r"""An + ```AccountIssue`` `__. + + Attributes: + name (str): + Identifier. The resource name of the account issue. Format: + ``accounts/{account}/issues/{id}`` + title (str): + The localized title of the issue. + severity (google.shopping.merchant_accounts_v1beta.types.AccountIssue.Severity): + The overall severity of the issue. + impacted_destinations (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountIssue.ImpactedDestination]): + The impact this issue has on various + destinations. + detail (str): + Further localized details about the issue. + documentation_uri (str): + Link to Merchant Center Help Center providing + further information about the issue and how to + fix it. + """ + class Severity(proto.Enum): + r"""All possible issue severities. + + Values: + SEVERITY_UNSPECIFIED (0): + The severity is unknown. + CRITICAL (1): + The issue causes offers to not serve. + ERROR (2): + The issue might affect offers (in the future) + or might be an indicator of issues with offers. + SUGGESTION (3): + The issue is a suggestion for improvement. + """ + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + ERROR = 2 + SUGGESTION = 3 + + class ImpactedDestination(proto.Message): + r"""The impact of the issue on a destination. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): + The impacted reporting context. + + This field is a member of `oneof`_ ``_reporting_context``. + impacts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountIssue.ImpactedDestination.Impact]): + The (negative) impact for various regions on + the given destination. + """ + + class Impact(proto.Message): + r"""The impact of the issue on a region. + + Attributes: + region_code (str): + The `CLDR region code `__ where + this issue applies. + severity (google.shopping.merchant_accounts_v1beta.types.AccountIssue.Severity): + The severity of the issue on the destination + and region. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + severity: 'AccountIssue.Severity' = proto.Field( + proto.ENUM, + number=2, + enum='AccountIssue.Severity', + ) + + reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=types.ReportingContext.ReportingContextEnum, + ) + impacts: MutableSequence['AccountIssue.ImpactedDestination.Impact'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AccountIssue.ImpactedDestination.Impact', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + severity: Severity = proto.Field( + proto.ENUM, + number=3, + enum=Severity, + ) + impacted_destinations: MutableSequence[ImpactedDestination] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=ImpactedDestination, + ) + detail: str = proto.Field( + proto.STRING, + number=5, + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListAccountIssuesRequest(proto.Message): + r"""Request message for the ``ListAccountIssues`` method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of issues. + Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of issues to + return. The service may return fewer than this + value. If unspecified, at most 50 users will be + returned. The maximum value is 100; values above + 100 will be coerced to 100 + page_token (str): + Optional. A page token, received from a previous + ``ListAccountIssues`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListAccountIssues`` must match the call that provided the + page token. + language_code (str): + Optional. The issues in the response will have + human-readable fields in the given language. The format is + `BCP-47 `__, such as + ``en-US`` or ``sr-Latn``. If not value is provided, + ``en-US`` will be used. + time_zone (str): + Optional. The `IANA `__ + timezone used to localize times in human-readable fields. + For example 'America/Los_Angeles'. If not set, + 'America/Los_Angeles' will be used. + """ + + 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, + ) + language_code: str = proto.Field( + proto.STRING, + number=4, + ) + time_zone: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAccountIssuesResponse(proto.Message): + r"""Response message for the ``ListAccountIssues`` method. + + Attributes: + account_issues (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountIssue]): + The issues from the specified account. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + account_issues: MutableSequence['AccountIssue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccountIssue', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py new file mode 100644 index 000000000000..1e367e052f02 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py @@ -0,0 +1,408 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import accountservices +from google.shopping.merchant_accounts_v1beta.types import user +from google.type import datetime_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'Account', + 'GetAccountRequest', + 'CreateAndConfigureAccountRequest', + 'DeleteAccountRequest', + 'UpdateAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListSubAccountsRequest', + 'ListSubAccountsResponse', + }, +) + + +class Account(proto.Message): + r"""An account. + + Attributes: + name (str): + Identifier. The resource name of the account. Format: + ``accounts/{account}`` + account_id (int): + Output only. The ID of the account. + account_name (str): + Required. A human-readable name of the account. See `store + name `__ + and `business + name `__ + for more information. + adult_content (bool): + Whether this account contains adult content. + test_account (bool): + Output only. Whether this is a test account. + time_zone (google.type.datetime_pb2.TimeZone): + Required. The time zone of the account. + + On writes, ``time_zone`` sets both the + ``reporting_time_zone`` and the ``display_time_zone``. + + For reads, ``time_zone`` always returns the + ``display_time_zone``. If ``display_time_zone`` doesn't + exist for your account, ``time_zone`` is empty. + language_code (str): + Required. The account's `BCP-47 language + code `__, such as + ``en-US`` or ``sr-Latn``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account_id: int = proto.Field( + proto.INT64, + number=2, + ) + account_name: str = proto.Field( + proto.STRING, + number=3, + ) + adult_content: bool = proto.Field( + proto.BOOL, + number=4, + ) + test_account: bool = proto.Field( + proto.BOOL, + number=5, + ) + time_zone: datetime_pb2.TimeZone = proto.Field( + proto.MESSAGE, + number=6, + message=datetime_pb2.TimeZone, + ) + language_code: str = proto.Field( + proto.STRING, + number=7, + ) + + +class GetAccountRequest(proto.Message): + r"""Request message for the ``GetAccount`` method. + + Attributes: + name (str): + Required. The name of the account to retrieve. Format: + ``accounts/{account}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAndConfigureAccountRequest(proto.Message): + r"""Request message for the ``CreateAndConfigureAccount`` method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + account (google.shopping.merchant_accounts_v1beta.types.Account): + Required. The account to be created. + users (MutableSequence[google.shopping.merchant_accounts_v1beta.types.CreateUserRequest]): + Optional. Users to be added to the account. + accept_terms_of_service (google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest.AcceptTermsOfService): + Optional. The Terms of Service (ToS) to be + accepted immediately upon account creation. + + This field is a member of `oneof`_ ``_accept_terms_of_service``. + service (MutableSequence[google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest.AddAccountService]): + Required. An account service between the account to be + created and the provider account is initialized as part of + the creation. At least one such service needs to be + provided. Currently exactly one of these needs to be + ``account_aggregation``, which means you can only create sub + accounts, not standalone account through this method. + Additional ``account_management`` or ``product_management`` + services may be provided. + """ + + class AcceptTermsOfService(proto.Message): + r"""Reference to a Terms of Service resource. + + Attributes: + name (str): + Required. The resource name of the terms of service version + in the format ``termsOfService/{version}``. To retrieve the + latest version, use the + `termsOfService.retrieveLatest `__ + method. + region_code (str): + Required. Region code as defined by + `CLDR `__. This is either a + country when the ToS applies specifically to that country or + ``001`` when it applies globally. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + + class AddAccountService(proto.Message): + r"""Additional instructions to add account services during + creation of the account. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + account_aggregation (google.shopping.merchant_accounts_v1beta.types.AccountAggregation): + The provider is an + `aggregator `__ + for the account. Payload for service type Account + Aggregation. + + This field is a member of `oneof`_ ``service_type``. + provider (str): + Optional. The provider of the service. Format: + ``accounts/{account}`` + + This field is a member of `oneof`_ ``_provider``. + """ + + account_aggregation: accountservices.AccountAggregation = proto.Field( + proto.MESSAGE, + number=103, + oneof='service_type', + message=accountservices.AccountAggregation, + ) + provider: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + account: 'Account' = proto.Field( + proto.MESSAGE, + number=1, + message='Account', + ) + users: MutableSequence[user.CreateUserRequest] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=user.CreateUserRequest, + ) + accept_terms_of_service: AcceptTermsOfService = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=AcceptTermsOfService, + ) + service: MutableSequence[AddAccountService] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=AddAccountService, + ) + + +class DeleteAccountRequest(proto.Message): + r"""Request message for the ``DeleteAccount`` method. + + Attributes: + name (str): + Required. The name of the account to delete. Format: + ``accounts/{account}`` + force (bool): + Optional. If set to ``true``, the account is deleted even if + it provides services to other accounts or has processed + offers. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class UpdateAccountRequest(proto.Message): + r"""Request message for the ``UpdateAccount`` method. + + Attributes: + account (google.shopping.merchant_accounts_v1beta.types.Account): + Required. The new version of the account. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + account: 'Account' = proto.Field( + proto.MESSAGE, + number=1, + message='Account', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListAccountsRequest(proto.Message): + r"""Request message for the ``ListAccounts`` method. + + Attributes: + page_size (int): + Optional. The maximum number of accounts to + return. The service may return fewer than this + value. If unspecified, at most 250 accounts are + returned. The maximum value is 500; values above + 500 are coerced to 500. + page_token (str): + Optional. A page token, received from a previous + ``ListAccounts`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListAccounts`` must match the call that provided the page + token. + filter (str): + Optional. Returns only accounts that match the + `filter `__. For more + details, see the `filter syntax + reference `__. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAccountsResponse(proto.Message): + r"""Response message for the ``ListAccounts`` method. + + Attributes: + accounts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Account]): + The accounts matching the ``ListAccountsRequest``. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence['Account'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Account', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSubAccountsRequest(proto.Message): + r"""Request message for the ``ListSubAccounts`` method. + + Attributes: + provider (str): + Required. The parent account. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of accounts to + return. The service may return fewer than this + value. If unspecified, at most 250 accounts are + returned. The maximum value is 500; values above + 500 are coerced to 500. + page_token (str): + Optional. A page token, received from a previous + ``ListAccounts`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListAccounts`` must match the call that provided the page + token. + """ + + provider: 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 ListSubAccountsResponse(proto.Message): + r"""Response message for the ``ListSubAccounts`` method. + + Attributes: + accounts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Account]): + The accounts for which the given parent + account is an aggregator. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence['Account'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Account', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py new file mode 100644 index 000000000000..a3173fe74b97 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py @@ -0,0 +1,36 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'AccountAggregation', + }, +) + + +class AccountAggregation(proto.Message): + r"""``AccountAggregation`` payload. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py new file mode 100644 index 000000000000..a9a0952a44bf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py @@ -0,0 +1,111 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'AutofeedSettings', + 'GetAutofeedSettingsRequest', + 'UpdateAutofeedSettingsRequest', + }, +) + + +class AutofeedSettings(proto.Message): + r"""Collection of information related to the + `autofeed `__ + settings. + + Attributes: + name (str): + Identifier. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings``. + enable_products (bool): + Required. Enables or disables product crawling through the + autofeed for the given account. Autofeed accounts must meet + `certain + conditions `__, + which can be checked through the ``eligible`` field. The + account must **not** be a marketplace. When the autofeed is + enabled for the first time, the products usually appear + instantly. When re-enabling, it might take up to 24 hours + for products to appear. + eligible (bool): + Output only. Determines whether merchant is + eligible for being enrolled into an autofeed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + enable_products: bool = proto.Field( + proto.BOOL, + number=2, + ) + eligible: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetAutofeedSettingsRequest(proto.Message): + r"""Request message for the ``GetAutofeedSettings`` method. + + Attributes: + name (str): + Required. The resource name of the autofeed settings. + Format: ``accounts/{account}/autofeedSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAutofeedSettingsRequest(proto.Message): + r"""Request message for the ``UpdateAutofeedSettings`` method. + + Attributes: + autofeed_settings (google.shopping.merchant_accounts_v1beta.types.AutofeedSettings): + Required. The new version of the autofeed + setting. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + autofeed_settings: 'AutofeedSettings' = proto.Field( + proto.MESSAGE, + number=1, + message='AutofeedSettings', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py new file mode 100644 index 000000000000..c4d67cbfcd3b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py @@ -0,0 +1,386 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'AutomaticImprovements', + 'AutomaticItemUpdates', + 'AutomaticImageImprovements', + 'AutomaticShippingImprovements', + 'GetAutomaticImprovementsRequest', + 'UpdateAutomaticImprovementsRequest', + }, +) + + +class AutomaticImprovements(proto.Message): + r"""Collection of information related to the `automatic + improvements `__ + of an account. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the automatic improvements. + Format: ``accounts/{account}/automaticImprovements``. + item_updates (google.shopping.merchant_accounts_v1beta.types.AutomaticItemUpdates): + Turning on `item + updates `__ + allows Google to automatically update items for you. When + item updates are on, Google uses the structured data markup + on the website and advanced data extractors to update the + price and availability of the items. When the item updates + are off, items with mismatched data aren't shown. This field + is only updated (cleared) if provided in the update mask. + + This field is a member of `oneof`_ ``_item_updates``. + image_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticImageImprovements): + This improvement will attempt to automatically correct + submitted images if they don't meet the `image + requirements `__, + for example, removing overlays. If successful, the image + will be replaced and approved. This improvement is only + applied to images of disapproved offers. For more + information see: `Automatic image + improvements `__ + This field is only updated (cleared) if provided in the + update mask. + + This field is a member of `oneof`_ ``_image_improvements``. + shipping_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticShippingImprovements): + Not available for MCAs + `accounts `__. + By turning on `automatic shipping + improvements `__, + you are allowing Google to improve the accuracy of your + delivery times shown to shoppers using Google. More accurate + delivery times, especially when faster, typically lead to + better conversion rates. Google will improve your estimated + delivery times based on various factors: + + - Delivery address of an order + - Current handling time and shipping time settings + - Estimated weekdays or business days + - Parcel tracking data This field is only updated (cleared) + if provided in the update mask. + + This field is a member of `oneof`_ ``_shipping_improvements``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + item_updates: 'AutomaticItemUpdates' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='AutomaticItemUpdates', + ) + image_improvements: 'AutomaticImageImprovements' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='AutomaticImageImprovements', + ) + shipping_improvements: 'AutomaticShippingImprovements' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='AutomaticShippingImprovements', + ) + + +class AutomaticItemUpdates(proto.Message): + r"""Turning on `item + updates `__ + allows Google to automatically update items for you. When item + updates are on, Google uses the structured data markup on the + website and advanced data extractors to update the price and + availability of the items. When the item updates are off, items with + mismatched data aren't shown. + + Attributes: + account_item_updates_settings (google.shopping.merchant_accounts_v1beta.types.AutomaticItemUpdates.ItemUpdatesAccountLevelSettings): + Optional. Determines which attributes of the + items should be automatically updated. If this + field is not present and provided in the update + mask, then the settings will be deleted. If + there are no settings for subaccount, they are + inherited from aggregator. + effective_allow_price_updates (bool): + Output only. The effective value of allow_price_updates. If + account_item_updates_settings is present, then this value is + the same. Otherwise, it represents the inherited value of + the parent account. The default value is true if no settings + are present. Read-only. + effective_allow_availability_updates (bool): + Output only. The effective value of + allow_availability_updates. If account_item_updates_settings + is present, then this value is the same. Otherwise, it + represents the inherited value of the parent account. The + default value is true if no settings are present. Read-only. + effective_allow_strict_availability_updates (bool): + Output only. The effective value of + allow_strict_availability_updates. If + account_item_updates_settings is present, then this value is + the same. Otherwise, it represents the inherited value of + the parent account. The default value is true if no settings + are present. Read-only. + effective_allow_condition_updates (bool): + Output only. The effective value of allow_condition_updates. + If account_item_updates_settings is present, then this value + is the same. Otherwise, it represents the inherited value of + the parent account. The default value is true if no settings + are present. Read-only. + """ + + class ItemUpdatesAccountLevelSettings(proto.Message): + r"""Settings for the Automatic Item Updates. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_price_updates (bool): + If price updates are enabled, Google always + updates the active price with the crawled + information. + + This field is a member of `oneof`_ ``_allow_price_updates``. + allow_availability_updates (bool): + If availability updates are enabled, any previous + availability values get overwritten if Google finds an + out-of-stock annotation on the offer's page. If additionally + ``allow_strict_availability_updates`` field is set to true, + values get overwritten if Google finds an in-stock + annotation on the offer’s page. + + This field is a member of `oneof`_ ``_allow_availability_updates``. + allow_strict_availability_updates (bool): + If ``allow_availability_updates`` is enabled, items are + automatically updated in all your Shopping target countries. + By default, availability updates will only be applied to + items that are 'out of stock' on your website but 'in stock' + on Shopping. Set this to true to also update items that are + 'in stock' on your website, but 'out of stock' on Google + Shopping. In order for this field to have an effect, you + must also set ``allow_availability_updates``. + + This field is a member of `oneof`_ ``_allow_strict_availability_updates``. + allow_condition_updates (bool): + If condition updates are enabled, Google + always updates item condition with the condition + detected from the details of your product. + + This field is a member of `oneof`_ ``_allow_condition_updates``. + """ + + allow_price_updates: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + allow_availability_updates: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + allow_strict_availability_updates: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + allow_condition_updates: bool = proto.Field( + proto.BOOL, + number=4, + optional=True, + ) + + account_item_updates_settings: ItemUpdatesAccountLevelSettings = proto.Field( + proto.MESSAGE, + number=1, + message=ItemUpdatesAccountLevelSettings, + ) + effective_allow_price_updates: bool = proto.Field( + proto.BOOL, + number=2, + ) + effective_allow_availability_updates: bool = proto.Field( + proto.BOOL, + number=3, + ) + effective_allow_strict_availability_updates: bool = proto.Field( + proto.BOOL, + number=4, + ) + effective_allow_condition_updates: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class AutomaticImageImprovements(proto.Message): + r"""This improvement will attempt to automatically correct submitted + images if they don't meet the `image + requirements `__, + for example, removing overlays. If successful, the image will be + replaced and approved. This improvement is only applied to images of + disapproved offers. For more information see: `Automatic image + improvements `__ + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + account_image_improvements_settings (google.shopping.merchant_accounts_v1beta.types.AutomaticImageImprovements.ImageImprovementsAccountLevelSettings): + Optional. Determines how the images should be + automatically updated. If this field is not + present and provided in the update mask, then + the settings will be deleted. If there are no + settings for subaccount, they are inherited from + aggregator. + + This field is a member of `oneof`_ ``_account_image_improvements_settings``. + effective_allow_automatic_image_improvements (bool): + Output only. The effective value of + allow_automatic_image_improvements. If + account_image_improvements_settings is present, then this + value is the same. Otherwise, it represents the inherited + value of the parent account. Read-only. + """ + + class ImageImprovementsAccountLevelSettings(proto.Message): + r"""Settings for the Automatic Image Improvements. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_automatic_image_improvements (bool): + Enables automatic image improvements. + + This field is a member of `oneof`_ ``_allow_automatic_image_improvements``. + """ + + allow_automatic_image_improvements: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + account_image_improvements_settings: ImageImprovementsAccountLevelSettings = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=ImageImprovementsAccountLevelSettings, + ) + effective_allow_automatic_image_improvements: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class AutomaticShippingImprovements(proto.Message): + r"""Not available for MCAs + `accounts `__. + By turning on `automatic shipping + improvements `__, + you are allowing Google to improve the accuracy of your delivery + times shown to shoppers using Google. More accurate delivery times, + especially when faster, typically lead to better conversion rates. + Google will improve your estimated delivery times based on various + factors: + + - Delivery address of an order + - Current handling time and shipping time settings + - Estimated weekdays or business days + - Parcel tracking data + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_shipping_improvements (bool): + Enables automatic shipping improvements. + + This field is a member of `oneof`_ ``_allow_shipping_improvements``. + """ + + allow_shipping_improvements: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + + +class GetAutomaticImprovementsRequest(proto.Message): + r"""Request message for the ``GetAutomaticImprovements`` method. + + Attributes: + name (str): + Required. The resource name of the automatic improvements. + Format: ``accounts/{account}/automaticImprovements`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAutomaticImprovementsRequest(proto.Message): + r"""Request message for the ``UpdateAutomaticImprovements`` method. + + Attributes: + automatic_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements): + Required. The new version of the automatic + imrovements. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following fields + are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``item_updates`` + - ``item_updates.account_level_settings`` + - ``image_improvements`` + - ``image_improvements.account_level_settings`` + - ``shipping_improvements`` + - ``shipping_improvements.allow_shipping_improvements`` + """ + + automatic_improvements: 'AutomaticImprovements' = proto.Field( + proto.MESSAGE, + number=1, + message='AutomaticImprovements', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py new file mode 100644 index 000000000000..c17161fc7d74 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py @@ -0,0 +1,204 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'BusinessIdentity', + 'GetBusinessIdentityRequest', + 'UpdateBusinessIdentityRequest', + }, +) + + +class BusinessIdentity(proto.Message): + r"""Collection of information related to the `identity of a + business `__. + + Attributes: + name (str): + Identifier. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity`` + promotions_consent (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.PromotionsConsent): + Optional. Whether the identity attributes may + be used for promotions. + black_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being black-owned. This optional field will only be + available for merchants with a business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + women_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being women-owned. This optional field will only be + available for merchants with a business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + veteran_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being veteran-owned. This optional field will only be + available for merchants with a business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + latino_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as being latino-owned. This optional field will only be + available for merchants with a business country set to + ``US``. It is also not applicable for marketplaces or + marketplace sellers. + small_business (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): + Optional. Specifies whether the business identifies itself + as a small business. This optional field will only be + available for merchants with a business country set to + ``US``. It is also not applicable for marketplaces. + """ + class PromotionsConsent(proto.Enum): + r"""All possible settings regarding promotions related to the + business identity. + + Values: + PROMOTIONS_CONSENT_UNSPECIFIED (0): + Default value indicating that no selection + was made. + PROMOTIONS_CONSENT_GIVEN (1): + Indicates that the account consented to + having their business identity used for + promotions. + PROMOTIONS_CONSENT_DENIED (2): + Indicates that the account did not consent to + having their business identity used for + promotions. + """ + PROMOTIONS_CONSENT_UNSPECIFIED = 0 + PROMOTIONS_CONSENT_GIVEN = 1 + PROMOTIONS_CONSENT_DENIED = 2 + + class IdentityAttribute(proto.Message): + r"""All information related to an identity attribute. + + Attributes: + identity_declaration (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute.IdentityDeclaration): + Required. The declaration of identity for + this attribute. + """ + class IdentityDeclaration(proto.Enum): + r"""All possible settings regarding the declaration of an + identity. + + Values: + IDENTITY_DECLARATION_UNSPECIFIED (0): + Default value indicating that no selection + was made. + SELF_IDENTIFIES_AS (1): + Indicates that the account identifies with + the attribute. + DOES_NOT_SELF_IDENTIFY_AS (2): + Indicates that the account does not identify + with the attribute. + """ + IDENTITY_DECLARATION_UNSPECIFIED = 0 + SELF_IDENTIFIES_AS = 1 + DOES_NOT_SELF_IDENTIFY_AS = 2 + + identity_declaration: 'BusinessIdentity.IdentityAttribute.IdentityDeclaration' = proto.Field( + proto.ENUM, + number=1, + enum='BusinessIdentity.IdentityAttribute.IdentityDeclaration', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + promotions_consent: PromotionsConsent = proto.Field( + proto.ENUM, + number=2, + enum=PromotionsConsent, + ) + black_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=3, + message=IdentityAttribute, + ) + women_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=4, + message=IdentityAttribute, + ) + veteran_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=5, + message=IdentityAttribute, + ) + latino_owned: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=6, + message=IdentityAttribute, + ) + small_business: IdentityAttribute = proto.Field( + proto.MESSAGE, + number=7, + message=IdentityAttribute, + ) + + +class GetBusinessIdentityRequest(proto.Message): + r"""Request message for the ``GetBusinessIdentity`` method. + + Attributes: + name (str): + Required. The resource name of the business identity. + Format: ``accounts/{account}/businessIdentity`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateBusinessIdentityRequest(proto.Message): + r"""Request message for the ``UpdateBusinessIdentity`` method. + + Attributes: + business_identity (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity): + Required. The new version of the business + identity. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + business_identity: 'BusinessIdentity' = proto.Field( + proto.MESSAGE, + number=1, + message='BusinessIdentity', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py new file mode 100644 index 000000000000..a92014b2ae3a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py @@ -0,0 +1,148 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import customerservice +from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'BusinessInfo', + 'GetBusinessInfoRequest', + 'UpdateBusinessInfoRequest', + }, +) + + +class BusinessInfo(proto.Message): + r"""Collection of information related to a business. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the business info. Format: + ``accounts/{account}/businessInfo`` + address (google.type.postal_address_pb2.PostalAddress): + Optional. The address of the business. + + This field is a member of `oneof`_ ``_address``. + phone (google.type.phone_number_pb2.PhoneNumber): + Output only. The phone number of the + business. + + This field is a member of `oneof`_ ``_phone``. + phone_verification_state (google.shopping.merchant_accounts_v1beta.types.PhoneVerificationState): + Output only. The phone verification state of + the business. + + This field is a member of `oneof`_ ``_phone_verification_state``. + customer_service (google.shopping.merchant_accounts_v1beta.types.CustomerService): + Optional. The customer service of the + business. + + This field is a member of `oneof`_ ``_customer_service``. + korean_business_registration_number (str): + Optional. The 10-digit `Korean business registration + number `__ + separated with dashes in the format: XXX-XX-XXXXX. + + This field is a member of `oneof`_ ``_korean_business_registration_number``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + address: postal_address_pb2.PostalAddress = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=postal_address_pb2.PostalAddress, + ) + phone: phone_number_pb2.PhoneNumber = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=phone_number_pb2.PhoneNumber, + ) + phone_verification_state: phoneverificationstate.PhoneVerificationState = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=phoneverificationstate.PhoneVerificationState, + ) + customer_service: customerservice.CustomerService = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message=customerservice.CustomerService, + ) + korean_business_registration_number: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + +class GetBusinessInfoRequest(proto.Message): + r"""Request message for the ``GetBusinessInfo`` method. + + Attributes: + name (str): + Required. The resource name of the business info. Format: + ``accounts/{account}/businessInfo`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateBusinessInfoRequest(proto.Message): + r"""Request message for the ``UpdateBusinessInfo`` method. + + Attributes: + business_info (google.shopping.merchant_accounts_v1beta.types.BusinessInfo): + Required. The new version of the business + info. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + business_info: 'BusinessInfo' = proto.Field( + proto.MESSAGE, + number=1, + message='BusinessInfo', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py new file mode 100644 index 000000000000..88e49becac97 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py @@ -0,0 +1,316 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.type.types import types + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'GetCheckoutSettingsRequest', + 'CreateCheckoutSettingsRequest', + 'UpdateCheckoutSettingsRequest', + 'DeleteCheckoutSettingsRequest', + 'CheckoutSettings', + 'UriSettings', + }, +) + + +class GetCheckoutSettingsRequest(proto.Message): + r"""Request message for ``GetCheckoutSettings`` method. + + Attributes: + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateCheckoutSettingsRequest(proto.Message): + r"""Request message for the ``CreateCheckoutSettings`` method. + + Attributes: + parent (str): + Required. The merchant account for which the + ``CheckoutSettings`` will be created. + checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): + Required. The ``CheckoutSettings`` object to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + checkout_settings: 'CheckoutSettings' = proto.Field( + proto.MESSAGE, + number=2, + message='CheckoutSettings', + ) + + +class UpdateCheckoutSettingsRequest(proto.Message): + r"""Request message for the ``UpdateCheckoutSettings`` method. + + Attributes: + checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): + Required. The updated version of the ``CheckoutSettings``. + The ``name`` field is used to identify the + ``CheckoutSettings``. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. The following fields + are supported (in both ``snake_case`` and + ``lowerCamelCase``): + + - ``eligible_destinations`` + - ``uri_settings`` + """ + + checkout_settings: 'CheckoutSettings' = proto.Field( + proto.MESSAGE, + number=1, + message='CheckoutSettings', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteCheckoutSettingsRequest(proto.Message): + r"""Request message for the ``DeleteCheckoutSettings`` method. + + Attributes: + name (str): + Required. The name/identifier of the merchant account. + Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CheckoutSettings(proto.Message): + r"""`CheckoutSettings `__ + for a specific merchant. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the program configuration + settings. Format: + ``accounts/{account}/programs/{program}/checkoutSettings`` + uri_settings (google.shopping.merchant_accounts_v1beta.types.UriSettings): + URI settings for cart or checkout URL. + + This field is a member of `oneof`_ ``_uri_settings``. + eligible_destinations (MutableSequence[google.shopping.type.types.Destination.DestinationEnum]): + Optional. The destinations to which the checkout program + applies, valid destination values are ``SHOPPING_ADS``, + ``FREE_LISTINGS`` + enrollment_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutEnrollmentState): + Output only. Reflects the merchant enrollment state in + ``Checkout`` program. + + This field is a member of `oneof`_ ``_enrollment_state``. + review_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutReviewState): + Output only. Reflects the merchant review state in + ``Checkout`` program. This is set based on the data quality + reviews of the URL provided by the merchant. A merchant with + enrollment state as ``ENROLLED`` can be in the following + review states: ``IN_REVIEW``, ``APPROVED`` or + ``DISAPPROVED``. A merchant must be in an + ``enrollment_state`` of ``ENROLLED`` before a review can + begin for the merchant.For more details, check the help + center doc. + + This field is a member of `oneof`_ ``_review_state``. + effective_uri_settings (google.shopping.merchant_accounts_v1beta.types.UriSettings): + Output only. The effective value of ``uri_settings`` for a + given merchant. If account level settings are present then + this value will be a copy of url settings. Otherwise, it + will have the value of the parent account (for only + marketplace sellers). + effective_enrollment_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutEnrollmentState): + Output only. The effective value of enrollment_state for a + given merchant ID. If account level settings are present + then this value will be a copy of the account level + settings. Otherwise, it will have the value of the parent + account (for only marketplace sellers). + + This field is a member of `oneof`_ ``_effective_enrollment_state``. + effective_review_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutReviewState): + Output only. The effective value of ``review_state`` for a + given merchant ID. If account level settings are present + then this value will be a copy of the account level + settings. Otherwise, it will have the value of the parent + account (for only marketplace sellers). + + This field is a member of `oneof`_ ``_effective_review_state``. + """ + class CheckoutEnrollmentState(proto.Enum): + r"""Enum indicating the enrollment state of merchant in ``Checkout`` + program. + + Values: + CHECKOUT_ENROLLMENT_STATE_UNSPECIFIED (0): + Default enrollment state when enrollment + state is not specified. + INACTIVE (1): + Merchant has not enrolled into the program. + ENROLLED (2): + Merchant has enrolled into the program by + providing either an account level URL or + checkout URLs as part of their feed. + OPTED_OUT (3): + Merchant has previously enrolled but opted + out of the program. + """ + CHECKOUT_ENROLLMENT_STATE_UNSPECIFIED = 0 + INACTIVE = 1 + ENROLLED = 2 + OPTED_OUT = 3 + + class CheckoutReviewState(proto.Enum): + r"""Enum indicating the review state of merchant in ``Checkout`` + program. + + Values: + CHECKOUT_REVIEW_STATE_UNSPECIFIED (0): + Default review state when review state is not + specified. + IN_REVIEW (1): + Merchant provided URLs are being reviewed for + data quality issues. + APPROVED (2): + Merchant account has been approved. Indicates + the data quality checks have passed. + DISAPPROVED (3): + Merchant account has been disapproved due to + data quality issues. + """ + CHECKOUT_REVIEW_STATE_UNSPECIFIED = 0 + IN_REVIEW = 1 + APPROVED = 2 + DISAPPROVED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri_settings: 'UriSettings' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='UriSettings', + ) + eligible_destinations: MutableSequence[types.Destination.DestinationEnum] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=types.Destination.DestinationEnum, + ) + enrollment_state: CheckoutEnrollmentState = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum=CheckoutEnrollmentState, + ) + review_state: CheckoutReviewState = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=CheckoutReviewState, + ) + effective_uri_settings: 'UriSettings' = proto.Field( + proto.MESSAGE, + number=5, + message='UriSettings', + ) + effective_enrollment_state: CheckoutEnrollmentState = proto.Field( + proto.ENUM, + number=6, + optional=True, + enum=CheckoutEnrollmentState, + ) + effective_review_state: CheckoutReviewState = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=CheckoutReviewState, + ) + + +class UriSettings(proto.Message): + r"""URL settings for cart or checkout URL. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + checkout_uri_template (str): + Checkout URL template. When the placeholders are expanded + will redirect the buyer to the merchant checkout page with + the item in the cart. For more details, check the `help + center + doc `__ + + This field is a member of `oneof`_ ``uri_template``. + cart_uri_template (str): + Cart URL template. When the placeholders are expanded will + redirect the buyer to the cart page on the merchant website + with the selected item in cart. For more details, check the + `help center + doc `__ + + This field is a member of `oneof`_ ``uri_template``. + """ + + checkout_uri_template: str = proto.Field( + proto.STRING, + number=1, + oneof='uri_template', + ) + cart_uri_template: str = proto.Field( + proto.STRING, + number=2, + oneof='uri_template', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py new file mode 100644 index 000000000000..a314f422c53b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py @@ -0,0 +1,74 @@ +# -*- 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.type import phone_number_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'CustomerService', + }, +) + + +class CustomerService(proto.Message): + r"""Customer service information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Optional. The URI where customer service may + be found. + + This field is a member of `oneof`_ ``_uri``. + email (str): + Optional. The email address where customer + service may be reached. + + This field is a member of `oneof`_ ``_email``. + phone (google.type.phone_number_pb2.PhoneNumber): + Optional. The phone number where customer + service may be called. + + This field is a member of `oneof`_ ``_phone``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + email: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + phone: phone_number_pb2.PhoneNumber = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=phone_number_pb2.PhoneNumber, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py new file mode 100644 index 000000000000..cf0589a015b8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py @@ -0,0 +1,121 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'EmailPreferences', + 'GetEmailPreferencesRequest', + 'UpdateEmailPreferencesRequest', + }, +) + + +class EmailPreferences(proto.Message): + r"""The categories of notifications the user opted into / opted + out of. The email preferences do not include mandatory + announcements as users can't opt out of them. + + Attributes: + name (str): + Identifier. The name of the EmailPreferences. + The endpoint is only supported for the + authenticated user. + news_and_tips (google.shopping.merchant_accounts_v1beta.types.EmailPreferences.OptInState): + Optional. Updates on new features, tips and + best practices. + """ + class OptInState(proto.Enum): + r"""Opt in state of the email preference. + + Values: + OPT_IN_STATE_UNSPECIFIED (0): + Opt-in status is not specified. + OPTED_OUT (1): + User has opted out of receiving this type of + email. + OPTED_IN (2): + User has opted in to receiving this type of + email. + UNCONFIRMED (3): + User has opted in to receiving this type of + email and the confirmation email has been sent, + but user has not yet confirmed the opt in + (applies only to certain countries). + """ + OPT_IN_STATE_UNSPECIFIED = 0 + OPTED_OUT = 1 + OPTED_IN = 2 + UNCONFIRMED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + news_and_tips: OptInState = proto.Field( + proto.ENUM, + number=2, + enum=OptInState, + ) + + +class GetEmailPreferencesRequest(proto.Message): + r"""Request message for GetEmailPreferences method. + + Attributes: + name (str): + Required. The name of the ``EmailPreferences`` resource. + Format: + ``accounts/{account}/users/{email}/emailPreferences`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEmailPreferencesRequest(proto.Message): + r"""Request message for UpdateEmailPreferences method. + + Attributes: + email_preferences (google.shopping.merchant_accounts_v1beta.types.EmailPreferences): + Required. Email Preferences to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + email_preferences: 'EmailPreferences' = proto.Field( + proto.MESSAGE, + number=1, + message='EmailPreferences', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py new file mode 100644 index 000000000000..1f95aae295de --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py @@ -0,0 +1,198 @@ +# -*- 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.protobuf import empty_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'GbpAccount', + 'ListGbpAccountsRequest', + 'ListGbpAccountsResponse', + 'LinkGbpAccountRequest', + 'LinkGbpAccountResponse', + }, +) + + +class GbpAccount(proto.Message): + r"""Collection of information related to a Google Business + Profile (GBP) account. + + Attributes: + name (str): + Identifier. The resource name of the GBP account. Format: + ``accounts/{account}/gbpAccount/{gbp_account}`` + gbp_account_id (str): + The id of the GBP account. + type_ (google.shopping.merchant_accounts_v1beta.types.GbpAccount.Type): + The type of the Business Profile. + gbp_account_name (str): + The name of the Business Profile. + For personal accounts: Email id of the owner. + For Business accounts: Name of the Business + Account. + listing_count (int): + Number of listings under this account. + """ + class Type(proto.Enum): + r"""The type of the GBP account. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + USER (1): + The GBP account is a user account. + BUSINESS_ACCOUNT (2): + The GBP account is a business account. + """ + TYPE_UNSPECIFIED = 0 + USER = 1 + BUSINESS_ACCOUNT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + gbp_account_id: str = proto.Field( + proto.STRING, + number=2, + ) + type_: Type = proto.Field( + proto.ENUM, + number=3, + enum=Type, + ) + gbp_account_name: str = proto.Field( + proto.STRING, + number=5, + ) + listing_count: int = proto.Field( + proto.INT64, + number=6, + ) + + +class ListGbpAccountsRequest(proto.Message): + r"""Request message for the ListGbpAccounts method. + + Attributes: + parent (str): + Required. The name of the parent resource under which the + GBP accounts are listed. Format: ``accounts/{account}``. + page_size (int): + Optional. The maximum number of ``GbpAccount`` resources to + return. The service returns fewer than this value if the + number of gbp accounts is less that than the ``pageSize``. + The default value is 50. The maximum value is 1000; If a + value higher than the maximum is specified, then the + ``pageSize`` will default to the maximum. + page_token (str): + Optional. A page token, received from a previous + ``ListGbpAccounts`` call. Provide the page token to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListGbpAccounts`` must match the call that provided the + page token. + """ + + 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 ListGbpAccountsResponse(proto.Message): + r"""Response message for the ListGbpAccounts method. + + Attributes: + gbp_accounts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.GbpAccount]): + The GBP accounts from the specified merchant + in the specified country. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + gbp_accounts: MutableSequence['GbpAccount'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='GbpAccount', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkGbpAccountRequest(proto.Message): + r"""Request message for the LinkGbpAccount method. + + Attributes: + parent (str): + Required. The name of the parent resource to which the GBP + account is linked. Format: ``accounts/{account}``. + gbp_email (str): + Required. The email address of the Business + Profile account. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + gbp_email: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkGbpAccountResponse(proto.Message): + r"""Response message for the LinkGbpAccount method. + + Attributes: + response (google.protobuf.empty_pb2.Empty): + Empty response. + """ + + response: empty_pb2.Empty = proto.Field( + proto.MESSAGE, + number=1, + message=empty_pb2.Empty, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py new file mode 100644 index 000000000000..45384433e2f9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py @@ -0,0 +1,139 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'Homepage', + 'GetHomepageRequest', + 'UpdateHomepageRequest', + 'ClaimHomepageRequest', + 'UnclaimHomepageRequest', + }, +) + + +class Homepage(proto.Message): + r"""A store's homepage. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the store's homepage. + Format: ``accounts/{account}/homepage`` + uri (str): + Required. The URI (typically a URL) of the + store's homepage. + + This field is a member of `oneof`_ ``_uri``. + claimed (bool): + Output only. Whether the homepage is claimed. + See + https://support.google.com/merchants/answer/176793. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + claimed: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class GetHomepageRequest(proto.Message): + r"""Request message for the ``GetHomepage`` method. + + Attributes: + name (str): + Required. The name of the homepage to retrieve. Format: + ``accounts/{account}/homepage`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateHomepageRequest(proto.Message): + r"""Request message for the ``UpdateHomepage`` method. + + Attributes: + homepage (google.shopping.merchant_accounts_v1beta.types.Homepage): + Required. The new version of the homepage. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + homepage: 'Homepage' = proto.Field( + proto.MESSAGE, + number=1, + message='Homepage', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ClaimHomepageRequest(proto.Message): + r"""Request message for the ``ClaimHomepage`` method. + + Attributes: + name (str): + Required. The name of the homepage to claim. Format: + ``accounts/{account}/homepage`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UnclaimHomepageRequest(proto.Message): + r"""Request message for the ``UnclaimHomepage`` method. + + Attributes: + name (str): + Required. The name of the homepage to unclaim. Format: + ``accounts/{account}/homepage`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py new file mode 100644 index 000000000000..564ef8dd933a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py @@ -0,0 +1,172 @@ +# -*- 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.protobuf import empty_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'LfpProvider', + 'FindLfpProvidersRequest', + 'FindLfpProvidersResponse', + 'LinkLfpProviderRequest', + 'LinkLfpProviderResponse', + }, +) + + +class LfpProvider(proto.Message): + r"""Collection of information related to a Local Feed Partnership + (LFP) provider. + + Attributes: + name (str): + Identifier. The resource name of the LFP provider. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}`` + region_code (str): + Output only. Region code defined by + `CLDR `__. + display_name (str): + The display name of the LFP provider. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + + +class FindLfpProvidersRequest(proto.Message): + r"""Request message for the FindLfpProviders method. + + Attributes: + parent (str): + Required. The name of the parent resource under which the + LFP providers are found. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. + page_size (int): + Optional. The maximum number of ``LfpProvider`` resources to + return. The service returns fewer than this value if the + number of lfp providers is less that than the ``pageSize``. + The default value is 50. The maximum value is 1000; If a + value higher than the maximum is specified, then the + ``pageSize`` will default to the maximum. + page_token (str): + Optional. A page token, received from a previous + ``FindLfpProviders`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``FindLfpProviders`` must match the call that provided the + page token. + """ + + 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 FindLfpProvidersResponse(proto.Message): + r"""Response message for the FindLfpProviders method. + + Attributes: + lfp_providers (MutableSequence[google.shopping.merchant_accounts_v1beta.types.LfpProvider]): + The LFP providers from the specified merchant + in the specified country. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + lfp_providers: MutableSequence['LfpProvider'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='LfpProvider', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkLfpProviderRequest(proto.Message): + r"""Request message for the LinkLfpProvider method. + + Attributes: + name (str): + Required. The name of the LFP provider resource to link. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. + The ``lfp_provider`` is the LFP provider ID. + external_account_id (str): + Required. The external account ID by which + this merchant is known to the LFP provider. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + external_account_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class LinkLfpProviderResponse(proto.Message): + r"""Response message for the LinkLfpProvider method. + + Attributes: + response (google.protobuf.empty_pb2.Empty): + Empty response. + """ + + response: empty_pb2.Empty = proto.Field( + proto.MESSAGE, + number=1, + message=empty_pb2.Empty, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py new file mode 100644 index 000000000000..07e6f2a3c1f5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py @@ -0,0 +1,548 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'OmnichannelSetting', + 'ReviewState', + 'InStock', + 'Pickup', + 'LfpLink', + 'OnDisplayToOrder', + 'About', + 'InventoryVerification', + 'GetOmnichannelSettingRequest', + 'ListOmnichannelSettingsRequest', + 'ListOmnichannelSettingsResponse', + 'CreateOmnichannelSettingRequest', + 'UpdateOmnichannelSettingRequest', + 'RequestInventoryVerificationRequest', + 'RequestInventoryVerificationResponse', + }, +) + + +class OmnichannelSetting(proto.Message): + r"""Collection of information related to the omnichannel settings + of a merchant. + + Attributes: + name (str): + Identifier. The resource name of the omnichannel setting. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + region_code (str): + Required. Immutable. Region code defined by + `CLDR `__. Must be provided in + the Create method, and is immutable. + lsf_type (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting.LsfType): + Required. The Local Store Front type for this + country. + in_stock (google.shopping.merchant_accounts_v1beta.types.InStock): + Optional. The InStock URI and state for this + country. + pickup (google.shopping.merchant_accounts_v1beta.types.Pickup): + Optional. The Pickup URI and state for this + country. + lfp_link (google.shopping.merchant_accounts_v1beta.types.LfpLink): + Output only. The established link to a LFP + provider. + odo (google.shopping.merchant_accounts_v1beta.types.OnDisplayToOrder): + Optional. The On Display to Order (ODO) + policy URI and state for this country. + about (google.shopping.merchant_accounts_v1beta.types.About): + Optional. The about page URI and state for + this country. + inventory_verification (google.shopping.merchant_accounts_v1beta.types.InventoryVerification): + Optional. The inventory verification contact + and state for this country. + """ + class LsfType(proto.Enum): + r"""The product page experience type, which is also called the Local + Store Front (LSF) type. Check the `HC + article `__ for + more details. + + Values: + LSF_TYPE_UNSPECIFIED (0): + Default value. This value is unused. + GHLSF (1): + Google-Hosted Local Store Front. Check the `HC + article `__ + for more details. + MHLSF_BASIC (2): + Merchant-Hosted Local Store Front Basic. Check the `HC + article `__ + for more details. + MHLSF_FULL (3): + Merchant-Hosted Local Store Front Full. Check the `HC + article `__ + for more details. + """ + LSF_TYPE_UNSPECIFIED = 0 + GHLSF = 1 + MHLSF_BASIC = 2 + MHLSF_FULL = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + lsf_type: LsfType = proto.Field( + proto.ENUM, + number=12, + enum=LsfType, + ) + in_stock: 'InStock' = proto.Field( + proto.MESSAGE, + number=13, + message='InStock', + ) + pickup: 'Pickup' = proto.Field( + proto.MESSAGE, + number=14, + message='Pickup', + ) + lfp_link: 'LfpLink' = proto.Field( + proto.MESSAGE, + number=5, + message='LfpLink', + ) + odo: 'OnDisplayToOrder' = proto.Field( + proto.MESSAGE, + number=6, + message='OnDisplayToOrder', + ) + about: 'About' = proto.Field( + proto.MESSAGE, + number=7, + message='About', + ) + inventory_verification: 'InventoryVerification' = proto.Field( + proto.MESSAGE, + number=8, + message='InventoryVerification', + ) + + +class ReviewState(proto.Message): + r"""The state of a omnichannel setting related review process. + """ + class State(proto.Enum): + r"""The state of the review process. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The review process has concluded + successfully. The reviewed item is active. + FAILED (2): + The review process failed. + RUNNING (3): + The review process is running. + ACTION_REQUIRED (4): + The review process is waiting for the + merchant to take action. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + FAILED = 2 + RUNNING = 3 + ACTION_REQUIRED = 4 + + +class InStock(proto.Message): + r"""Collection of information related to InStock. + + Attributes: + uri (str): + Optional. Product landing page URI. It is only used for the + review of MHLSF in-stock serving. This URI domain should + match with the business's homepage. Required to be empty if + the lsf_type is GHLSF, and required when the lsf_type is + MHLSF_FULL or MHLSF_BASIC. + state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): + Output only. The state of the in-stock + serving. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class Pickup(proto.Message): + r"""Collection of information related to Pickup. + + Attributes: + uri (str): + Required. Pickup product page URI. It is only + used for the review of pickup serving. This URI + domain should match with the business's + homepage. + state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): + Output only. The state of the pickup serving. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class LfpLink(proto.Message): + r"""Collection of information related to the LFP link. + + Attributes: + lfp_provider (str): + Required. The resource name of the LFP provider. Format: + ``lfpProviders/{lfp_provider}`` + external_account_id (str): + Required. The account ID by which this + merchant is known to the LFP provider. + state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): + Output only. The state of the LFP link. + """ + + lfp_provider: str = proto.Field( + proto.STRING, + number=1, + ) + external_account_id: str = proto.Field( + proto.STRING, + number=2, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=3, + enum='ReviewState.State', + ) + + +class OnDisplayToOrder(proto.Message): + r"""Collection of information related to the on display to order + (`ODO `__). + + Attributes: + uri (str): + Required. The on display to order (ODO) + policy URI. + state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): + Output only. The state of the URI. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class About(proto.Message): + r"""Collection of information related to the about page + (`impressum `__). + + Attributes: + uri (str): + Required. The about page URI. + state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): + Output only. The state of the URI. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=2, + enum='ReviewState.State', + ) + + +class InventoryVerification(proto.Message): + r"""Collection of information related to `inventory + verification `__. + + Attributes: + state (google.shopping.merchant_accounts_v1beta.types.InventoryVerification.State): + Output only. The state of the inventory + verification process. + contact (str): + Required. The name of the contact for the + inventory verification process. + contact_email (str): + Required. The email address of the contact + for the inventory verification process. + contact_state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): + Output only. The state of the contact + verification. + """ + class State(proto.Enum): + r"""The state of the `inventory + verification `__ + process. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTION_REQUIRED (1): + When the merchant needs to initiate the + inventory verification process. The next state + is INACTIVE. + INACTIVE (5): + When the merchant is ready to request + inventory verification. + RUNNING (2): + The inventory verification process is + running. If the merchant is rejected, the next + state is INACTIVE. + SUCCEEDED (3): + The inventory verification process succeeded. + SUSPENDED (4): + When merchant fails the inventory + verification process and all attempts are + exhausted. + """ + STATE_UNSPECIFIED = 0 + ACTION_REQUIRED = 1 + INACTIVE = 5 + RUNNING = 2 + SUCCEEDED = 3 + SUSPENDED = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + contact: str = proto.Field( + proto.STRING, + number=2, + ) + contact_email: str = proto.Field( + proto.STRING, + number=3, + ) + contact_state: 'ReviewState.State' = proto.Field( + proto.ENUM, + number=4, + enum='ReviewState.State', + ) + + +class GetOmnichannelSettingRequest(proto.Message): + r"""Request message for the GetOmnichannelSettings method. + + Attributes: + name (str): + Required. The name of the omnichannel setting to retrieve. + Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOmnichannelSettingsRequest(proto.Message): + r"""Request message for the ListOmnichannelSettings method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + omnichannel settings. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of omnichannel + settings to return. The service may return fewer + than this value. If unspecified, at most 50 + omnichannel settings will be returned. The + maximum value is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListOmnichannelSettings`` call. Provide this to retrieve + the subsequent page. + + When paginating, all other parameters provided to + ``ListOmnichannelSettings`` must match the call that + provided the page token. + """ + + 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 ListOmnichannelSettingsResponse(proto.Message): + r"""Response message for the ListOmnichannelSettings method. + + Attributes: + omnichannel_settings (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting]): + The omnichannel settings from the specified + merchant. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + omnichannel_settings: MutableSequence['OmnichannelSetting'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OmnichannelSetting', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateOmnichannelSettingRequest(proto.Message): + r"""Request message for the CreateOmnichannelSetting method. + + Attributes: + parent (str): + Required. The parent resource where this omnichannel setting + will be created. Format: ``accounts/{account}`` + omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): + Required. The omnichannel setting to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + omnichannel_setting: 'OmnichannelSetting' = proto.Field( + proto.MESSAGE, + number=2, + message='OmnichannelSetting', + ) + + +class UpdateOmnichannelSettingRequest(proto.Message): + r"""Request message for the UpdateOmnichannelSetting method. + + Attributes: + omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): + Required. The omnichannel setting to update. + + The omnichannel setting's ``name`` field is used to identify + the omnichannel setting to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + + The following fields are supported in snake_case only: + + - ``lsf_type`` + - ``in_stock`` + - ``pickup`` + - ``odo`` + - ``about`` + - ``inventory_verification`` + + Full replacement with wildcard ``*``\ is supported, while + empty/implied update mask is not. + """ + + omnichannel_setting: 'OmnichannelSetting' = proto.Field( + proto.MESSAGE, + number=1, + message='OmnichannelSetting', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class RequestInventoryVerificationRequest(proto.Message): + r"""Request message for the RequestInventoryVerification method. + + Attributes: + name (str): + Required. The name of the omnichannel setting to request + inventory verification. Format: + ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RequestInventoryVerificationResponse(proto.Message): + r"""Response message for the RequestInventoryVerification method. + + Attributes: + omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): + The omnichannel setting that was updated. + """ + + omnichannel_setting: 'OmnichannelSetting' = proto.Field( + proto.MESSAGE, + number=1, + message='OmnichannelSetting', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py new file mode 100644 index 000000000000..fa93dab9ca27 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py @@ -0,0 +1,581 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.type.types import types +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'GetOnlineReturnPolicyRequest', + 'CreateOnlineReturnPolicyRequest', + 'UpdateOnlineReturnPolicyRequest', + 'DeleteOnlineReturnPolicyRequest', + 'ListOnlineReturnPoliciesRequest', + 'ListOnlineReturnPoliciesResponse', + 'OnlineReturnPolicy', + }, +) + + +class GetOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``GetOnlineReturnPolicy`` method. + + Attributes: + name (str): + Required. The name of the return policy to retrieve. Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``CreateOnlineReturnPolicy`` method. + + Attributes: + parent (str): + Required. The merchant account for which the return policy + will be created. Format: ``accounts/{account}`` + online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): + Required. The return policy object to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + online_return_policy: 'OnlineReturnPolicy' = proto.Field( + proto.MESSAGE, + number=2, + message='OnlineReturnPolicy', + ) + + +class UpdateOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``UpdateOnlineReturnPolicy`` method. The + method supports field masks and when the mask is provided, only the + fields specified in the mask are updated. + + Attributes: + online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): + Required. The online return policy to update. The online + return policy's ``name`` field is used to identify the + online return policy to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. List of fields being updated. + + The following fields are supported (in both ``snake_case`` + and ``lowerCamelCase``): + + - ``accept_defective_only`` + - ``accept_exchange`` + - ``item_conditions`` + - ``policy`` + - ``process_refund_days`` + - ``restocking_fee`` + - ``return_methods`` + - ``return_policy_uri`` + - ``return_shipping_fee`` + """ + + online_return_policy: 'OnlineReturnPolicy' = proto.Field( + proto.MESSAGE, + number=1, + message='OnlineReturnPolicy', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteOnlineReturnPolicyRequest(proto.Message): + r"""Request message for the ``DeleteOnlineReturnPolicy`` method. + + Attributes: + name (str): + Required. The name of the return policy to delete. Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListOnlineReturnPoliciesRequest(proto.Message): + r"""Request message for the ``ListOnlineReturnPolicies`` method. + + Attributes: + parent (str): + Required. The merchant account for which to list return + policies. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of ``OnlineReturnPolicy`` + resources to return. The service returns fewer than this + value if the number of return policies for the given + merchant is less that than the ``pageSize``. The default + value is 10. The maximum value is 100; If a value higher + than the maximum is specified, then the ``pageSize`` will + default to the maximum + page_token (str): + Optional. A page token, received from a previous + ``ListOnlineReturnPolicies`` call. Provide the page token to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListOnlineReturnPolicies`` must match the call that + provided the page token. The token returned as + [nextPageToken][google.shopping.merchant.accounts.v1beta.ListOnlineReturnPoliciesResponse.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 ListOnlineReturnPoliciesResponse(proto.Message): + r"""Response message for the ``ListOnlineReturnPolicies`` method. + + Attributes: + online_return_policies (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy]): + The retrieved return policies. + 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 + + online_return_policies: MutableSequence['OnlineReturnPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='OnlineReturnPolicy', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class OnlineReturnPolicy(proto.Message): + r"""`Online return + policy `__ + object. This is currently used to represent return policies for ads + and free listings programs. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The name of the ``OnlineReturnPolicy`` resource. + Format: + ``accounts/{account}/onlineReturnPolicies/{return_policy}`` + return_policy_id (str): + Output only. Return policy ID generated by + Google. + label (str): + Required. Immutable. This field represents the unique + user-defined label of the return policy. It is important to + note that the same label cannot be used in different return + policies for the same country. Unless a product specifies a + specific label attribute, policies will be automatically + labeled as 'default'. To assign a custom return policy to + certain product groups, follow the instructions provided in + the [Return policy label] + (https://support.google.com/merchants/answer/9445425). The + label can contain up to 50 characters. + countries (MutableSequence[str]): + Required. Immutable. The countries of sale + where the return policy applies. The values must + be a valid 2 letter ISO 3166 code. + policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.Policy): + Optional. The return policy. + seasonal_overrides (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.SeasonalOverride]): + Optional. Overrides to the general policy for + orders placed during a specific set of time + intervals. + restocking_fee (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.RestockingFee): + Optional. The restocking fee that applies to + all return reason categories. This would be + treated as a free restocking fee if the value is + not set. + return_methods (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnMethod]): + Optional. The return methods of how customers + can return an item. This value is required to + not be empty unless the type of return policy is + noReturns. + item_conditions (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ItemCondition]): + Optional. The item conditions accepted for + returns must not be empty unless the type of + return policy is 'noReturns'. + return_shipping_fee (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnShippingFee): + Optional. The return shipping fee. Should be + set only when customer need to download and + print the return label. + return_policy_uri (str): + Required. The return policy uri. This can + used by Google to do a sanity check for the + policy. It must be a valid URL. + accept_defective_only (bool): + Optional. This field specifies if merchant + only accepts defective products for returns. + + This field is a member of `oneof`_ ``_accept_defective_only``. + process_refund_days (int): + Optional. The field specifies the number of + days it takes for merchants to process refunds. + + This field is a member of `oneof`_ ``_process_refund_days``. + accept_exchange (bool): + Optional. This field specifies if merchant + allows customers to exchange products. + + This field is a member of `oneof`_ ``_accept_exchange``. + return_label_source (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnLabelSource): + Optional. The field specifies the return + label source. + + This field is a member of `oneof`_ ``_return_label_source``. + """ + class ReturnMethod(proto.Enum): + r"""The available return methods. + + Values: + RETURN_METHOD_UNSPECIFIED (0): + Default value. This value is unused. + BY_MAIL (1): + Return by mail. + IN_STORE (2): + Return in store. + AT_A_KIOSK (3): + Return at a kiosk. + """ + RETURN_METHOD_UNSPECIFIED = 0 + BY_MAIL = 1 + IN_STORE = 2 + AT_A_KIOSK = 3 + + class ItemCondition(proto.Enum): + r"""The available item conditions. + + Values: + ITEM_CONDITION_UNSPECIFIED (0): + Default value. This value is unused. + NEW (1): + New. + USED (2): + Used. + """ + ITEM_CONDITION_UNSPECIFIED = 0 + NEW = 1 + USED = 2 + + class ReturnLabelSource(proto.Enum): + r"""The available return label sources. + + Values: + RETURN_LABEL_SOURCE_UNSPECIFIED (0): + Default value. This value is unused. + DOWNLOAD_AND_PRINT (1): + Download and print. + IN_THE_PACKAGE (2): + Label include in the package. + CUSTOMER_RESPONSIBILITY (3): + Customer to provide. + """ + RETURN_LABEL_SOURCE_UNSPECIFIED = 0 + DOWNLOAD_AND_PRINT = 1 + IN_THE_PACKAGE = 2 + CUSTOMER_RESPONSIBILITY = 3 + + class ReturnShippingFee(proto.Message): + r"""The return shipping fee. This can either be a fixed fee or a + boolean to indicate that the customer pays the actual shipping + cost. + + Attributes: + type_ (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnShippingFee.Type): + Required. Type of return shipping fee. + fixed_fee (google.shopping.type.types.Price): + Fixed return shipping fee amount. This value is only + applicable when type is ``FIXED``. We will treat the return + shipping fee as free if type is ``FIXED`` and this value is + not set. + """ + class Type(proto.Enum): + r"""Return shipping fee types. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + FIXED (1): + The return shipping fee is a fixed value. + CUSTOMER_PAYING_ACTUAL_FEE (2): + Customers will pay the actual return shipping + fee. + """ + TYPE_UNSPECIFIED = 0 + FIXED = 1 + CUSTOMER_PAYING_ACTUAL_FEE = 2 + + type_: 'OnlineReturnPolicy.ReturnShippingFee.Type' = proto.Field( + proto.ENUM, + number=1, + enum='OnlineReturnPolicy.ReturnShippingFee.Type', + ) + fixed_fee: types.Price = proto.Field( + proto.MESSAGE, + number=2, + message=types.Price, + ) + + class RestockingFee(proto.Message): + r"""The restocking fee. This can be a flat fee or a micro + percent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + fixed_fee (google.shopping.type.types.Price): + Fixed restocking fee. + + This field is a member of `oneof`_ ``type``. + micro_percent (int): + Percent of total price in micros. 15,000,000 + means 15% of the total price would be charged. + + This field is a member of `oneof`_ ``type``. + """ + + fixed_fee: types.Price = proto.Field( + proto.MESSAGE, + number=1, + oneof='type', + message=types.Price, + ) + micro_percent: int = proto.Field( + proto.INT32, + number=2, + oneof='type', + ) + + class Policy(proto.Message): + r"""The available policies. + + Attributes: + type_ (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.Policy.Type): + Policy type. + days (int): + The number of days items can be returned after delivery, + where one day is defined as 24 hours after the delivery + timestamp. Required for ``NUMBER_OF_DAYS_AFTER_DELIVERY`` + returns. + """ + class Type(proto.Enum): + r"""Return policy types. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + NUMBER_OF_DAYS_AFTER_DELIVERY (1): + The number of days within which a return is + valid after delivery. + NO_RETURNS (2): + No returns. + LIFETIME_RETURNS (3): + Life time returns. + """ + TYPE_UNSPECIFIED = 0 + NUMBER_OF_DAYS_AFTER_DELIVERY = 1 + NO_RETURNS = 2 + LIFETIME_RETURNS = 3 + + type_: 'OnlineReturnPolicy.Policy.Type' = proto.Field( + proto.ENUM, + number=1, + enum='OnlineReturnPolicy.Policy.Type', + ) + days: int = proto.Field( + proto.INT64, + number=2, + ) + + class SeasonalOverride(proto.Message): + r""" + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + return_days (int): + Number of days (from the delivery date) that + the product can be returned. + + This field is a member of `oneof`_ ``return_window``. + return_until_date (google.type.date_pb2.Date): + Fixed end date until which the product can be + returned. + + This field is a member of `oneof`_ ``return_window``. + label (str): + Required. Display name of this seasonal + override in Merchant Center. + start_date (google.type.date_pb2.Date): + Required. Defines the date range when this seasonal override + applies. Both start_date and end_date are inclusive. The + dates of the seasonal overrides should not overlap. + end_date (google.type.date_pb2.Date): + Required. seasonal override end date + (inclusive). + """ + + return_days: int = proto.Field( + proto.INT32, + number=5, + oneof='return_window', + ) + return_until_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=6, + oneof='return_window', + message=date_pb2.Date, + ) + label: str = proto.Field( + proto.STRING, + number=1, + ) + start_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=2, + message=date_pb2.Date, + ) + end_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + message=date_pb2.Date, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + return_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + label: str = proto.Field( + proto.STRING, + number=3, + ) + countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + policy: Policy = proto.Field( + proto.MESSAGE, + number=5, + message=Policy, + ) + seasonal_overrides: MutableSequence[SeasonalOverride] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=SeasonalOverride, + ) + restocking_fee: RestockingFee = proto.Field( + proto.MESSAGE, + number=6, + message=RestockingFee, + ) + return_methods: MutableSequence[ReturnMethod] = proto.RepeatedField( + proto.ENUM, + number=7, + enum=ReturnMethod, + ) + item_conditions: MutableSequence[ItemCondition] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=ItemCondition, + ) + return_shipping_fee: ReturnShippingFee = proto.Field( + proto.MESSAGE, + number=9, + message=ReturnShippingFee, + ) + return_policy_uri: str = proto.Field( + proto.STRING, + number=10, + ) + accept_defective_only: bool = proto.Field( + proto.BOOL, + number=11, + optional=True, + ) + process_refund_days: int = proto.Field( + proto.INT32, + number=12, + optional=True, + ) + accept_exchange: bool = proto.Field( + proto.BOOL, + number=13, + optional=True, + ) + return_label_source: ReturnLabelSource = proto.Field( + proto.ENUM, + number=15, + optional=True, + enum=ReturnLabelSource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py new file mode 100644 index 000000000000..3400b5c96854 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py @@ -0,0 +1,47 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'PhoneVerificationState', + }, +) + + +class PhoneVerificationState(proto.Enum): + r"""The phone verification state. + + Values: + PHONE_VERIFICATION_STATE_UNSPECIFIED (0): + Default value. This value is unused. + PHONE_VERIFICATION_STATE_VERIFIED (1): + The phone is verified. + PHONE_VERIFICATION_STATE_UNVERIFIED (2): + The phone is unverified + """ + PHONE_VERIFICATION_STATE_UNSPECIFIED = 0 + PHONE_VERIFICATION_STATE_VERIFIED = 1 + PHONE_VERIFICATION_STATE_UNVERIFIED = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py new file mode 100644 index 000000000000..aa2de4c33766 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py @@ -0,0 +1,254 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'Program', + 'GetProgramRequest', + 'ListProgramsRequest', + 'ListProgramsResponse', + 'EnableProgramRequest', + 'DisableProgramRequest', + }, +) + + +class Program(proto.Message): + r"""Defines participation in a given program for the specified account. + + Programs provide a mechanism for adding functionality to merchant + accounts. A typical example of this is the `Free product + listings `__ + program, which enables products from a merchant's store to be shown + across Google for free. + + Attributes: + name (str): + Identifier. The resource name of the program. Format: + ``accounts/{account}/programs/{program}`` + documentation_uri (str): + Output only. The URL of a Merchant Center + help page describing the program. + state (google.shopping.merchant_accounts_v1beta.types.Program.State): + Output only. The participation state of the + account in the program. + active_region_codes (MutableSequence[str]): + Output only. The regions in which the account is actively + participating in the program. Active regions are defined as + those where all program requirements affecting the regions + have been met. + + Region codes are defined by + `CLDR `__. This is either a + country where the program applies specifically to that + country or ``001`` when the program applies globally. + unmet_requirements (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Program.Requirement]): + Output only. The requirements that the + account has not yet satisfied that are affecting + participation in the program. + """ + class State(proto.Enum): + r"""Possible program participation states for the account. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + NOT_ELIGIBLE (1): + The account is not eligible to participate in + the program. + ELIGIBLE (2): + The account is eligible to participate in the + program. + ENABLED (3): + The program is enabled for the account. + """ + STATE_UNSPECIFIED = 0 + NOT_ELIGIBLE = 1 + ELIGIBLE = 2 + ENABLED = 3 + + class Requirement(proto.Message): + r"""Defines a requirement specified for participation in the + program. + + Attributes: + title (str): + Output only. Name of the requirement. + documentation_uri (str): + Output only. The URL of a help page + describing the requirement. + affected_region_codes (MutableSequence[str]): + Output only. The regions that are currently affected by this + requirement not being met. + + Region codes are defined by + `CLDR `__. This is either a + country where the program applies specifically to that + country or ``001`` when the program applies globally. + """ + + title: str = proto.Field( + proto.STRING, + number=1, + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=2, + ) + affected_region_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + documentation_uri: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + active_region_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + unmet_requirements: MutableSequence[Requirement] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=Requirement, + ) + + +class GetProgramRequest(proto.Message): + r"""Request message for the GetProgram method. + + Attributes: + name (str): + Required. The name of the program to retrieve. Format: + ``accounts/{account}/programs/{program}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListProgramsRequest(proto.Message): + r"""Request message for the ListPrograms method. + + Attributes: + parent (str): + Required. The name of the account for which to retrieve all + programs. Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of programs to + return in a single response. If unspecified (or + 0), a default size of 1000 is used. The maximum + value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + Optional. A continuation token, received from a previous + ``ListPrograms`` call. Provide this to retrieve the next + page. + """ + + 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 ListProgramsResponse(proto.Message): + r"""Response message for the ListPrograms method. + + Attributes: + programs (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Program]): + The programs for the given account. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + programs: MutableSequence['Program'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Program', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class EnableProgramRequest(proto.Message): + r"""Request message for the EnableProgram method. + + Attributes: + name (str): + Required. The name of the program for which to enable + participation for the given account. Format: + ``accounts/{account}/programs/{program}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DisableProgramRequest(proto.Message): + r"""Request message for the DisableProgram method. + + Attributes: + name (str): + Required. The name of the program for which to disable + participation for the given account. Format: + ``accounts/{account}/programs/{program}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py new file mode 100644 index 000000000000..1bbb36f4bb73 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py @@ -0,0 +1,323 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'GetRegionRequest', + 'CreateRegionRequest', + 'UpdateRegionRequest', + 'DeleteRegionRequest', + 'ListRegionsRequest', + 'ListRegionsResponse', + 'Region', + }, +) + + +class GetRegionRequest(proto.Message): + r"""Request message for the ``GetRegion`` method. + + Attributes: + name (str): + Required. The name of the region to retrieve. Format: + ``accounts/{account}/regions/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateRegionRequest(proto.Message): + r"""Request message for the ``CreateRegion`` method. + + Attributes: + parent (str): + Required. The account to create a region for. Format: + ``accounts/{account}`` + region_id (str): + Required. The identifier for the region, + unique over all regions of the same account. + region (google.shopping.merchant_accounts_v1beta.types.Region): + Required. The region to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + region_id: str = proto.Field( + proto.STRING, + number=2, + ) + region: 'Region' = proto.Field( + proto.MESSAGE, + number=3, + message='Region', + ) + + +class UpdateRegionRequest(proto.Message): + r"""Request message for the ``UpdateRegion`` method. + + Attributes: + region (google.shopping.merchant_accounts_v1beta.types.Region): + Required. The updated region. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The comma-separated field mask indicating the + fields to update. Example: + ``"displayName,postalCodeArea.regionCode"``. + """ + + region: 'Region' = proto.Field( + proto.MESSAGE, + number=1, + message='Region', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteRegionRequest(proto.Message): + r"""Request message for the ``DeleteRegion`` method. + + Attributes: + name (str): + Required. The name of the region to delete. Format: + ``accounts/{account}/regions/{region}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRegionsRequest(proto.Message): + r"""Request message for the ``ListRegions`` method. + + Attributes: + parent (str): + Required. The account to list regions for. Format: + ``accounts/{account}`` + page_size (int): + Optional. The maximum number of regions to + return. The service may return fewer than this + value. If unspecified, at most 50 regions will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListRegions`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListRegions`` must match the call that provided the page + token. + """ + + 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 ListRegionsResponse(proto.Message): + r"""Response message for the ``ListRegions`` method. + + Attributes: + regions (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Region]): + The regions from the specified merchant. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + regions: MutableSequence['Region'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Region', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Region(proto.Message): + r"""Represents a geographic region that you can use as a target with + both the ``RegionalInventory`` and ``ShippingSettings`` services. + You can define regions as collections of either postal codes or, in + some countries, using predefined geotargets. For more information, + see `Set up + regions `__ + for more information. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the region. Format: + ``accounts/{account}/regions/{region}`` + display_name (str): + Optional. The display name of the region. + + This field is a member of `oneof`_ ``_display_name``. + postal_code_area (google.shopping.merchant_accounts_v1beta.types.Region.PostalCodeArea): + Optional. A list of postal codes that defines + the region area. + geotarget_area (google.shopping.merchant_accounts_v1beta.types.Region.GeoTargetArea): + Optional. A list of geotargets that defines + the region area. + regional_inventory_eligible (google.protobuf.wrappers_pb2.BoolValue): + Output only. Indicates if the region is + eligible for use in the Regional Inventory + configuration. + shipping_eligible (google.protobuf.wrappers_pb2.BoolValue): + Output only. Indicates if the region is + eligible for use in the Shipping Services + configuration. + """ + + class PostalCodeArea(proto.Message): + r"""A list of postal codes that defines the region area. Note: All + regions defined using postal codes are accessible through the + account's ``ShippingSettings.postalCodeGroups`` resource. + + Attributes: + region_code (str): + Required. `CLDR territory + code `__ + or the country the postal code group applies to. + postal_codes (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Region.PostalCodeArea.PostalCodeRange]): + Required. A range of postal codes. + """ + + class PostalCodeRange(proto.Message): + r"""A range of postal codes that defines the region area. + + Attributes: + begin (str): + Required. A postal code or a pattern of the form prefix\* + denoting the inclusive lower bound of the range defining the + area. Examples values: ``94108``, ``9410*``, ``9*``. + end (str): + Optional. A postal code or a pattern of the form ``prefix*`` + denoting the inclusive upper bound of the range defining the + area. It must have the same length as postalCodeRangeBegin: + if postalCodeRangeBegin is a postal code then + postalCodeRangeEnd must be a postal code too; if + postalCodeRangeBegin is a pattern then postalCodeRangeEnd + must be a pattern with the same prefix length. Optional: if + not set, then the area is defined as being all the postal + codes matching postalCodeRangeBegin. + """ + + begin: str = proto.Field( + proto.STRING, + number=1, + ) + end: str = proto.Field( + proto.STRING, + number=2, + ) + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + postal_codes: MutableSequence['Region.PostalCodeArea.PostalCodeRange'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Region.PostalCodeArea.PostalCodeRange', + ) + + class GeoTargetArea(proto.Message): + r"""A list of geotargets that defines the region area. + + Attributes: + geotarget_criteria_ids (MutableSequence[int]): + Required. A non-empty list of `location + IDs `__. + They must all be of the same location type (for example, + state). + """ + + geotarget_criteria_ids: MutableSequence[int] = proto.RepeatedField( + proto.INT64, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + postal_code_area: PostalCodeArea = proto.Field( + proto.MESSAGE, + number=3, + message=PostalCodeArea, + ) + geotarget_area: GeoTargetArea = proto.Field( + proto.MESSAGE, + number=4, + message=GeoTargetArea, + ) + regional_inventory_eligible: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.BoolValue, + ) + shipping_eligible: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.BoolValue, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py new file mode 100644 index 000000000000..2fc37070a317 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py @@ -0,0 +1,1489 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'ShippingSettings', + 'Service', + 'Distance', + 'Warehouse', + 'WarehouseCutoffTime', + 'Address', + 'DeliveryTime', + 'CutoffTime', + 'BusinessDayConfig', + 'WarehouseBasedDeliveryTime', + 'RateGroup', + 'Table', + 'TransitTable', + 'MinimumOrderValueTable', + 'Headers', + 'LocationIdSet', + 'Row', + 'Value', + 'CarrierRate', + 'GetShippingSettingsRequest', + 'InsertShippingSettingsRequest', + }, +) + + +class ShippingSettings(proto.Message): + r"""The merchant account's `shipping + setting `__. + + Attributes: + name (str): + Identifier. The resource name of the shipping setting. + Format: ``accounts/{account}/shippingSetting`` + services (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Service]): + Optional. The target account's list of + services. + warehouses (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Warehouse]): + Optional. A list of warehouses which can be referred to in + ``services``. + etag (str): + Required. This field is used for avoid async + issue. Make sure shipping setting data + didn't change between get call and insert call. + The user should do following steps: + + 1. Set etag field as empty string for initial + shipping setting creation. + + 2. After initial creation, call get method to + obtain an etag and current shipping setting + data before call insert. + + 3. Modify to wanted shipping setting + information. + + 4. Call insert method with the wanted shipping + setting information with the etag obtained + from step 2. + + 5. If shipping setting data changed between step + 2 and step 4. Insert request will fail + because the etag changes every time the + shipping setting data changes. User should + repeate step 2-4 with the new etag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + services: MutableSequence['Service'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Service', + ) + warehouses: MutableSequence['Warehouse'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='Warehouse', + ) + etag: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Service(proto.Message): + r"""Shipping service. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + service_name (str): + Required. Free-form name of the service. Must + be unique within target account. + + This field is a member of `oneof`_ ``_service_name``. + active (bool): + Required. A boolean exposing the active + status of the shipping service. + + This field is a member of `oneof`_ ``_active``. + delivery_countries (MutableSequence[str]): + Required. The CLDR territory code of the + countries to which the service applies. + currency_code (str): + The CLDR code of the currency to which this + service applies. Must match that of the prices + in rate groups. + + This field is a member of `oneof`_ ``_currency_code``. + delivery_time (google.shopping.merchant_accounts_v1beta.types.DeliveryTime): + Required. Time spent in various aspects from + order to the delivery of the product. + + This field is a member of `oneof`_ ``_delivery_time``. + rate_groups (MutableSequence[google.shopping.merchant_accounts_v1beta.types.RateGroup]): + Optional. Shipping rate group definitions. Only the last one + is allowed to have an empty ``applicable_shipping_labels``, + which means "everything else". The other + ``applicable_shipping_labels`` must not overlap. + shipment_type (google.shopping.merchant_accounts_v1beta.types.Service.ShipmentType): + Type of locations this service ships orders + to. + + This field is a member of `oneof`_ ``_shipment_type``. + minimum_order_value (google.shopping.type.types.Price): + Minimum order value for this service. If set, indicates that + customers will have to spend at least this amount. All + prices within a service must have the same currency. Cannot + be set together with minimum_order_value_table. + + This field is a member of `oneof`_ ``_minimum_order_value``. + minimum_order_value_table (google.shopping.merchant_accounts_v1beta.types.MinimumOrderValueTable): + Table of per store minimum order values for the pickup + fulfillment type. Cannot be set together with + minimum_order_value. + + This field is a member of `oneof`_ ``_minimum_order_value_table``. + store_config (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig): + A list of stores your products are delivered + from. This is only valid for the local delivery + shipment type. + + This field is a member of `oneof`_ ``_store_config``. + loyalty_programs (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Service.LoyaltyProgram]): + Optional. Loyalty programs that this shipping + service is limited to. + """ + class ShipmentType(proto.Enum): + r"""Shipment type of shipping service. + + Values: + SHIPMENT_TYPE_UNSPECIFIED (0): + This service did not specify shipment type. + DELIVERY (1): + This service ships orders to an address + chosen by the customer. + LOCAL_DELIVERY (2): + This service ships orders to an address + chosen by the customer. The order is shipped + from a local store near by. + COLLECTION_POINT (3): + This service ships orders to an address + chosen by the customer. The order is shipped + from a collection point. + """ + SHIPMENT_TYPE_UNSPECIFIED = 0 + DELIVERY = 1 + LOCAL_DELIVERY = 2 + COLLECTION_POINT = 3 + + class StoreConfig(proto.Message): + r"""A list of stores your products are delivered from. + This is only valid for the local delivery shipment type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + store_service_type (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig.StoreServiceType): + Indicates whether all stores, or selected + stores, listed by this merchant provide local + delivery. + + This field is a member of `oneof`_ ``_store_service_type``. + store_codes (MutableSequence[str]): + Optional. A list of store codes that provide local delivery. + If empty, then ``all_stores`` must be true. + cutoff_config (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig.CutoffConfig): + Configs related to local delivery ends for + the day. + + This field is a member of `oneof`_ ``_cutoff_config``. + service_radius (google.shopping.merchant_accounts_v1beta.types.Distance): + Maximum delivery radius. + This is only required for the local delivery + shipment type. + + This field is a member of `oneof`_ ``_service_radius``. + """ + class StoreServiceType(proto.Enum): + r"""Indicates whether all stores, or selected stores, listed by + the merchant provide local delivery. + + Values: + STORE_SERVICE_TYPE_UNSPECIFIED (0): + Did not specify store service type. + ALL_STORES (1): + Indicates whether all stores, current and + future, listed by this merchant provide local + delivery. + SELECTED_STORES (2): + Indicates that only the stores listed in ``store_codes`` are + eligible for local delivery. + """ + STORE_SERVICE_TYPE_UNSPECIFIED = 0 + ALL_STORES = 1 + SELECTED_STORES = 2 + + class CutoffConfig(proto.Message): + r"""Configs related to local delivery ends for the day. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + local_cutoff_time (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig.CutoffConfig.LocalCutoffTime): + Time that local delivery ends for the day. + + This field is a member of `oneof`_ ``_local_cutoff_time``. + store_close_offset_hours (int): + Only valid with local delivery fulfillment. Represents + cutoff time as the number of hours before store closing. + Mutually exclusive with ``local_cutoff_time``. + + This field is a member of `oneof`_ ``_store_close_offset_hours``. + no_delivery_post_cutoff (bool): + Merchants can opt-out of showing n+1 day local delivery when + they have a shipping service configured to n day local + delivery. For example, if the shipping service defines + same-day delivery, and it's past the cut-off, setting this + field to ``true`` results in the calculated shipping service + rate returning ``NO_DELIVERY_POST_CUTOFF``. In the same + example, setting this field to ``false`` results in the + calculated shipping time being one day. This is only for + local delivery. + + This field is a member of `oneof`_ ``_no_delivery_post_cutoff``. + """ + + class LocalCutoffTime(proto.Message): + r"""Time that local delivery ends for the day. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hour (int): + Hour local delivery orders must be placed by + to process the same day. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + Minute local delivery orders must be placed + by to process the same day. + + This field is a member of `oneof`_ ``_minute``. + """ + + hour: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + minute: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + local_cutoff_time: 'Service.StoreConfig.CutoffConfig.LocalCutoffTime' = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message='Service.StoreConfig.CutoffConfig.LocalCutoffTime', + ) + store_close_offset_hours: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + no_delivery_post_cutoff: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + + store_service_type: 'Service.StoreConfig.StoreServiceType' = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum='Service.StoreConfig.StoreServiceType', + ) + store_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + cutoff_config: 'Service.StoreConfig.CutoffConfig' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Service.StoreConfig.CutoffConfig', + ) + service_radius: 'Distance' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='Distance', + ) + + class LoyaltyProgram(proto.Message): + r"""`Loyalty + program `__ + provided by a merchant. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + program_label (str): + This is the loyalty program label set in your + loyalty program settings in Merchant Center. + This sub-attribute allows Google to map your + loyalty program to eligible offers. + + This field is a member of `oneof`_ ``_program_label``. + loyalty_program_tiers (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Service.LoyaltyProgram.LoyaltyProgramTiers]): + Optional. Loyalty program tier of this + shipping service. + """ + + class LoyaltyProgramTiers(proto.Message): + r"""Subset of a merchants loyalty program. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tier_label (str): + The tier label [tier_label] sub-attribute differentiates + offer level benefits between each tier. This value is also + set in your program settings in Merchant Center, and is + required for data source changes even if your loyalty + program only has 1 tier. + + This field is a member of `oneof`_ ``_tier_label``. + """ + + tier_label: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + program_label: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + loyalty_program_tiers: MutableSequence['Service.LoyaltyProgram.LoyaltyProgramTiers'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Service.LoyaltyProgram.LoyaltyProgramTiers', + ) + + service_name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + active: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + delivery_countries: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + currency_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + delivery_time: 'DeliveryTime' = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message='DeliveryTime', + ) + rate_groups: MutableSequence['RateGroup'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='RateGroup', + ) + shipment_type: ShipmentType = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum=ShipmentType, + ) + minimum_order_value: types.Price = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message=types.Price, + ) + minimum_order_value_table: 'MinimumOrderValueTable' = proto.Field( + proto.MESSAGE, + number=9, + optional=True, + message='MinimumOrderValueTable', + ) + store_config: StoreConfig = proto.Field( + proto.MESSAGE, + number=10, + optional=True, + message=StoreConfig, + ) + loyalty_programs: MutableSequence[LoyaltyProgram] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=LoyaltyProgram, + ) + + +class Distance(proto.Message): + r"""Maximum delivery radius. + This is only required for the local delivery shipment type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (int): + Integer value of distance. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_accounts_v1beta.types.Distance.Unit): + Unit can differ based on country, it is + parameterized to include miles and kilometers. + + This field is a member of `oneof`_ ``_unit``. + """ + class Unit(proto.Enum): + r"""Unit can differ based on country, it is parameterized to + include miles and kilometers. + + Values: + UNIT_UNSPECIFIED (0): + Unit unspecified + MILES (1): + Unit in miles + KILOMETERS (2): + Unit in kilometers + """ + UNIT_UNSPECIFIED = 0 + MILES = 1 + KILOMETERS = 2 + + value: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + unit: Unit = proto.Field( + proto.ENUM, + number=2, + optional=True, + enum=Unit, + ) + + +class Warehouse(proto.Message): + r"""A fulfillment warehouse, which stores and handles inventory. + Next tag: 7 + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. The name of the warehouse. Must be + unique within account. + + This field is a member of `oneof`_ ``_name``. + shipping_address (google.shopping.merchant_accounts_v1beta.types.Address): + Required. Shipping address of the warehouse. + + This field is a member of `oneof`_ ``_shipping_address``. + cutoff_time (google.shopping.merchant_accounts_v1beta.types.WarehouseCutoffTime): + Required. The latest time of day that an + order can be accepted and begin processing. + Later orders will be processed in the next day. + The time is based on the warehouse postal code. + + This field is a member of `oneof`_ ``_cutoff_time``. + handling_days (int): + Required. The number of days it takes for + this warehouse to pack up and ship an item. This + is on the warehouse level, but can be overridden + on the offer level based on the attributes of an + item. + + This field is a member of `oneof`_ ``_handling_days``. + business_day_config (google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig): + Business days of the warehouse. + If not set, will be Monday to Friday by default. + + This field is a member of `oneof`_ ``_business_day_config``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + shipping_address: 'Address' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='Address', + ) + cutoff_time: 'WarehouseCutoffTime' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='WarehouseCutoffTime', + ) + handling_days: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + business_day_config: 'BusinessDayConfig' = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message='BusinessDayConfig', + ) + + +class WarehouseCutoffTime(proto.Message): + r"""The latest time of day that an order can be accepted and + begin processing. Later orders will be processed in the next + day. The time is based on the warehouse postal code. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hour (int): + Required. Hour of the cutoff time until which + an order has to be placed to be processed in the + same day by the warehouse. Hour is based on the + timezone of warehouse. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + Required. Minute of the cutoff time until + which an order has to be placed to be processed + in the same day by the warehouse. Minute is + based on the timezone of warehouse. + + This field is a member of `oneof`_ ``_minute``. + """ + + hour: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + minute: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class Address(proto.Message): + r"""Shipping address of the warehouse. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + street_address (str): + Street-level part of the address. For example: + ``111w 31st Street``. + + This field is a member of `oneof`_ ``_street_address``. + city (str): + Required. City, town or commune. May also + include dependent localities or sublocalities + (For example neighborhoods or suburbs). + + This field is a member of `oneof`_ ``_city``. + administrative_area (str): + Required. Top-level administrative + subdivision of the country. For example, a state + like California ("CA") or a province like Quebec + ("QC"). + + This field is a member of `oneof`_ ``_administrative_area``. + postal_code (str): + Required. Postal code or ZIP (For example + "94043"). + + This field is a member of `oneof`_ ``_postal_code``. + region_code (str): + Required. `CLDR country + code `__ + (For example "US"). + + This field is a member of `oneof`_ ``_region_code``. + """ + + street_address: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + city: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + administrative_area: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + postal_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + region_code: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + +class DeliveryTime(proto.Message): + r"""Time spent in various aspects from order to the delivery of + the product. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_transit_days (int): + Minimum number of business days that is spent in transit. 0 + means same day delivery, 1 means next day delivery. Either + ``min_transit_days``, ``max_transit_days`` or + ``transit_time_table`` must be set, but not both. + + This field is a member of `oneof`_ ``_min_transit_days``. + max_transit_days (int): + Maximum number of business days that is spent in transit. 0 + means same day delivery, 1 means next day delivery. Must be + greater than or equal to ``min_transit_days``. + + This field is a member of `oneof`_ ``_max_transit_days``. + cutoff_time (google.shopping.merchant_accounts_v1beta.types.CutoffTime): + Business days cutoff time definition. + If not configured the cutoff time will be + defaulted to 8AM PST. + + This field is a member of `oneof`_ ``_cutoff_time``. + min_handling_days (int): + Minimum number of business days spent before an order is + shipped. 0 means same day shipped, 1 means next day shipped. + 'min_handling_days' and 'max_handling_days' should be either + set or not set at the same time. + + This field is a member of `oneof`_ ``_min_handling_days``. + max_handling_days (int): + Maximum number of business days spent before an order is + shipped. 0 means same day shipped, 1 means next day shipped. + Must be greater than or equal to ``min_handling_days``. + 'min_handling_days' and 'max_handling_days' should be either + set or not set at the same time. + + This field is a member of `oneof`_ ``_max_handling_days``. + transit_time_table (google.shopping.merchant_accounts_v1beta.types.TransitTable): + Transit time table, number of business days spent in transit + based on row and column dimensions. Either + ``min_transit_days``, ``max_transit_days`` or + ``transit_time_table`` can be set, but not both. + + This field is a member of `oneof`_ ``_transit_time_table``. + handling_business_day_config (google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig): + The business days during which orders can be + handled. If not provided, Monday to Friday + business days will be assumed. + + This field is a member of `oneof`_ ``_handling_business_day_config``. + transit_business_day_config (google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig): + The business days during which orders can be + in-transit. If not provided, Monday to Friday + business days will be assumed. + + This field is a member of `oneof`_ ``_transit_business_day_config``. + warehouse_based_delivery_times (MutableSequence[google.shopping.merchant_accounts_v1beta.types.WarehouseBasedDeliveryTime]): + Optional. Indicates that the delivery time should be + calculated per warehouse (shipping origin location) based on + the settings of the selected carrier. When set, no other + transit time related field in [delivery + time][[google.shopping.content.bundles.ShippingSetting.DeliveryTime] + should be set. + """ + + min_transit_days: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + max_transit_days: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + cutoff_time: 'CutoffTime' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='CutoffTime', + ) + min_handling_days: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + max_handling_days: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + transit_time_table: 'TransitTable' = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message='TransitTable', + ) + handling_business_day_config: 'BusinessDayConfig' = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message='BusinessDayConfig', + ) + transit_business_day_config: 'BusinessDayConfig' = proto.Field( + proto.MESSAGE, + number=8, + optional=True, + message='BusinessDayConfig', + ) + warehouse_based_delivery_times: MutableSequence['WarehouseBasedDeliveryTime'] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message='WarehouseBasedDeliveryTime', + ) + + +class CutoffTime(proto.Message): + r"""Business days cutoff time definition. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + hour (int): + Required. Hour of the cutoff time until which + an order has to be placed to be processed in the + same day. + + This field is a member of `oneof`_ ``_hour``. + minute (int): + Required. Minute of the cutoff time until + which an order has to be placed to be processed + in the same day. + + This field is a member of `oneof`_ ``_minute``. + time_zone (str): + Required. `Timezone + identifier `__ + For example "Europe/Zurich". + + This field is a member of `oneof`_ ``_time_zone``. + """ + + hour: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + minute: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + time_zone: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class BusinessDayConfig(proto.Message): + r"""Business days of the warehouse. + + Attributes: + business_days (MutableSequence[google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig.Weekday]): + Required. Regular business days. + May not be empty. + """ + class Weekday(proto.Enum): + r""" + + Values: + WEEKDAY_UNSPECIFIED (0): + No description available. + MONDAY (1): + No description available. + TUESDAY (2): + No description available. + WEDNESDAY (3): + No description available. + THURSDAY (4): + No description available. + FRIDAY (5): + No description available. + SATURDAY (6): + No description available. + SUNDAY (7): + No description available. + """ + WEEKDAY_UNSPECIFIED = 0 + MONDAY = 1 + TUESDAY = 2 + WEDNESDAY = 3 + THURSDAY = 4 + FRIDAY = 5 + SATURDAY = 6 + SUNDAY = 7 + + business_days: MutableSequence[Weekday] = proto.RepeatedField( + proto.ENUM, + number=1, + enum=Weekday, + ) + + +class WarehouseBasedDeliveryTime(proto.Message): + r"""Indicates that the delivery time should be calculated per warehouse + (shipping origin location) based on the settings of the selected + carrier. When set, no other transit time related field in + ``delivery_time`` should be set. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + carrier (str): + Required. Carrier, such as ``"UPS"`` or ``"Fedex"``. + + This field is a member of `oneof`_ ``_carrier``. + carrier_service (str): + Required. Carrier service, such as ``"ground"`` or + ``"2 days"``. The name of the service must be in the + eddSupportedServices list. + + This field is a member of `oneof`_ ``_carrier_service``. + warehouse (str): + Required. Warehouse name. This should match + [warehouse][ShippingSetting.warehouses.name] + + This field is a member of `oneof`_ ``_warehouse``. + """ + + carrier: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + carrier_service: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + warehouse: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class RateGroup(proto.Message): + r"""Shipping rate group definitions. Only the last one is allowed to + have an empty ``applicable_shipping_labels``, which means + "everything else". The other ``applicable_shipping_labels`` must not + overlap. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + applicable_shipping_labels (MutableSequence[str]): + Required. A list of `shipping + labels `__ + defining the products to which this rate group applies to. + This is a disjunction: only one of the labels has to match + for the rate group to apply. May only be empty for the last + rate group of a service. + single_value (google.shopping.merchant_accounts_v1beta.types.Value): + The value of the rate group (For example flat rate $10). Can + only be set if ``main_table`` and ``subtables`` are not set. + + This field is a member of `oneof`_ ``_single_value``. + main_table (google.shopping.merchant_accounts_v1beta.types.Table): + A table defining the rate group, when ``single_value`` is + not expressive enough. Can only be set if ``single_value`` + is not set. + + This field is a member of `oneof`_ ``_main_table``. + subtables (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Table]): + Optional. A list of subtables referred to by ``main_table``. + Can only be set if ``main_table`` is set. + carrier_rates (MutableSequence[google.shopping.merchant_accounts_v1beta.types.CarrierRate]): + Optional. A list of carrier rates that can be referred to by + ``main_table`` or ``single_value``. + name (str): + Optional. Name of the rate group. + If set has to be unique within shipping service. + + This field is a member of `oneof`_ ``_name``. + """ + + applicable_shipping_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + single_value: 'Value' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='Value', + ) + main_table: 'Table' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Table', + ) + subtables: MutableSequence['Table'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Table', + ) + carrier_rates: MutableSequence['CarrierRate'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='CarrierRate', + ) + name: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + +class Table(proto.Message): + r"""A table defining the rate group, when ``single_value`` is not + expressive enough. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the table. Required for subtables, + ignored for the main table. + + This field is a member of `oneof`_ ``_name``. + row_headers (google.shopping.merchant_accounts_v1beta.types.Headers): + Required. Headers of the table's rows. + + This field is a member of `oneof`_ ``_row_headers``. + column_headers (google.shopping.merchant_accounts_v1beta.types.Headers): + Headers of the table's columns. Optional: if + not set then the table has only one dimension. + + This field is a member of `oneof`_ ``_column_headers``. + rows (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Row]): + Required. The list of rows that constitute the table. Must + have the same length as ``row_headers``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + row_headers: 'Headers' = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message='Headers', + ) + column_headers: 'Headers' = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message='Headers', + ) + rows: MutableSequence['Row'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Row', + ) + + +class TransitTable(proto.Message): + r"""Transit time table, number of business days spent in transit based + on row and column dimensions. Either ``min_transit_days``, + ``max_transit_days`` or ``transit_time_table`` can be set, but not + both. + + Attributes: + postal_code_group_names (MutableSequence[str]): + Required. A list of region names + [Region.name][google.shopping.merchant.accounts.v1beta.Region.name] + . The last value can be ``"all other locations"``. Example: + ``["zone 1", "zone 2", "all other locations"]``. The + referred postal code groups must match the delivery country + of the service. + transit_time_labels (MutableSequence[str]): + Required. A list of transit time labels. The last value can + be ``"all other labels"``. Example: + ``["food", "electronics", "all other labels"]``. + rows (MutableSequence[google.shopping.merchant_accounts_v1beta.types.TransitTable.TransitTimeRow]): + Required. If there's only one dimension set of + ``postal_code_group_names`` or ``transit_time_labels``, + there are multiple rows each with one value for that + dimension. If there are two dimensions, each row corresponds + to a ``postal_code_group_names``, and columns (values) to a + ``transit_time_labels``. + """ + + class TransitTimeRow(proto.Message): + r"""If there's only one dimension set of ``postal_code_group_names`` or + ``transit_time_labels``, there are multiple rows each with one value + for that dimension. If there are two dimensions, each row + corresponds to a ``postal_code_group_names``, and columns (values) + to a ``transit_time_labels``. + + Attributes: + values (MutableSequence[google.shopping.merchant_accounts_v1beta.types.TransitTable.TransitTimeRow.TransitTimeValue]): + Required. Transit time range (min-max) in + business days. + """ + + class TransitTimeValue(proto.Message): + r"""Transit time range (min-max) in business days. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_transit_days (int): + Minimum transit time range in business days. + 0 means same day delivery, 1 means next day + delivery. + + This field is a member of `oneof`_ ``_min_transit_days``. + max_transit_days (int): + Must be greater than or equal to ``min_transit_days``. + + This field is a member of `oneof`_ ``_max_transit_days``. + """ + + min_transit_days: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + max_transit_days: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + values: MutableSequence['TransitTable.TransitTimeRow.TransitTimeValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TransitTable.TransitTimeRow.TransitTimeValue', + ) + + postal_code_group_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + transit_time_labels: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + rows: MutableSequence[TransitTimeRow] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=TransitTimeRow, + ) + + +class MinimumOrderValueTable(proto.Message): + r"""Table of per store minimum order values for the pickup + fulfillment type. + + Attributes: + store_code_set_with_movs (MutableSequence[google.shopping.merchant_accounts_v1beta.types.MinimumOrderValueTable.StoreCodeSetWithMov]): + Required. A list of store code sets sharing + the same minimum order value (MOV). At least two + sets are required and the last one must be + empty, which signifies 'MOV for all other + stores'. Each store code can only appear once + across all the sets. All prices within a service + must have the same currency. + """ + + class StoreCodeSetWithMov(proto.Message): + r"""A list of store code sets sharing the same minimum order + value. At least two sets are required and the last one must be + empty, which signifies 'MOV for all other stores'. + Each store code can only appear once across all the sets. All + prices within a service must have the same currency. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + store_codes (MutableSequence[str]): + Optional. A list of unique store codes or + empty for the catch all. + value (google.shopping.type.types.Price): + The minimum order value for the given stores. + + This field is a member of `oneof`_ ``_value``. + """ + + store_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + value: types.Price = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=types.Price, + ) + + store_code_set_with_movs: MutableSequence[StoreCodeSetWithMov] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=StoreCodeSetWithMov, + ) + + +class Headers(proto.Message): + r"""A non-empty list of row or column headers for a table. Exactly one + of ``prices``, ``weights``, ``num_items``, + ``postal_code_group_names``, or ``location`` must be set. + + Attributes: + prices (MutableSequence[google.shopping.type.types.Price]): + Required. A list of inclusive order price upper bounds. The + last price's value can be infinity by setting price + amount_micros = -1. For example + ``[{"amount_micros": 10000000, "currency_code": "USD"}, {"amount_micros": 500000000, "currency_code": "USD"}, {"amount_micros": -1, "currency_code": "USD"}]`` + represents the headers "<= $10", "<= $500", and "> $500". + All prices within a service must have the same currency. + Must be non-empty. Must be positive except -1. Can only be + set if all other fields are not set. + weights (MutableSequence[google.shopping.type.types.Weight]): + Required. A list of inclusive order weight upper bounds. The + last weight's value can be infinity by setting price + amount_micros = -1. For example + ``[{"amount_micros": 10000000, "unit": "kg"}, {"amount_micros": 50000000, "unit": "kg"}, {"amount_micros": -1, "unit": "kg"}]`` + represents the headers "<= 10kg", "<= 50kg", and "> 50kg". + All weights within a service must have the same unit. Must + be non-empty. Must be positive except -1. Can only be set if + all other fields are not set. + number_of_items (MutableSequence[str]): + Required. A list of inclusive number of items upper bounds. + The last value can be ``"infinity"``. For example + ``["10", "50", "infinity"]`` represents the headers "<= 10 + items", "<= 50 items", and "> 50 items". Must be non-empty. + Can only be set if all other fields are not set. + postal_code_group_names (MutableSequence[str]): + Required. A list of postal group names. The last value can + be ``"all other locations"``. Example: + ``["zone 1", "zone 2", "all other locations"]``. The + referred postal code groups must match the delivery country + of the service. Must be non-empty. Can only be set if all + other fields are not set. + locations (MutableSequence[google.shopping.merchant_accounts_v1beta.types.LocationIdSet]): + Required. A list of location ID sets. Must be + non-empty. Can only be set if all other fields + are not set. + """ + + prices: MutableSequence[types.Price] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=types.Price, + ) + weights: MutableSequence[types.Weight] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=types.Weight, + ) + number_of_items: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + postal_code_group_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + locations: MutableSequence['LocationIdSet'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='LocationIdSet', + ) + + +class LocationIdSet(proto.Message): + r"""A list of location ID sets. Must be non-empty. Can only be + set if all other fields are not set. + + Attributes: + location_ids (MutableSequence[str]): + Required. A non-empty list of `location + IDs `__. + They must all be of the same location type (For example, + state). + """ + + location_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class Row(proto.Message): + r"""Include a list of cells. + + Attributes: + cells (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Value]): + Required. The list of cells that constitute the row. Must + have the same length as ``columnHeaders`` for + two-dimensional tables, a length of 1 for one-dimensional + tables. + """ + + cells: MutableSequence['Value'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Value', + ) + + +class Value(proto.Message): + r"""The single value of a rate group or the value of a rate group + table's cell. Exactly one of ``no_shipping``, ``flat_rate``, + ``price_percentage``, ``carrier_rateName``, ``subtable_name`` must + be set. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + no_shipping (bool): + If true, then the product can't be shipped. + Must be true when set, can only be set if all + other fields are not set. + + This field is a member of `oneof`_ ``_no_shipping``. + flat_rate (google.shopping.type.types.Price): + A flat rate. Can only be set if all other + fields are not set. + + This field is a member of `oneof`_ ``_flat_rate``. + price_percentage (str): + A percentage of the price represented as a number in decimal + notation (For example, ``"5.4"``). Can only be set if all + other fields are not set. + + This field is a member of `oneof`_ ``_price_percentage``. + carrier_rate (str): + The name of a carrier rate referring to a + carrier rate defined in the same rate group. Can + only be set if all other fields are not set. + + This field is a member of `oneof`_ ``_carrier_rate``. + subtable (str): + The name of a subtable. Can only be set in + table cells (For example, not for single + values), and only if all other fields are not + set. + + This field is a member of `oneof`_ ``_subtable``. + """ + + no_shipping: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + flat_rate: types.Price = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=types.Price, + ) + price_percentage: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + carrier_rate: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + subtable: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + +class CarrierRate(proto.Message): + r"""A list of carrier rates that can be referred to by ``main_table`` or + ``single_value``. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Name of the carrier rate. Must be + unique per rate group. + + This field is a member of `oneof`_ ``_name``. + carrier (str): + Required. Carrier service, such as ``"UPS"`` or ``"Fedex"``. + + This field is a member of `oneof`_ ``_carrier``. + carrier_service (str): + Required. Carrier service, such as ``"ground"`` or + ``"2 days"``. + + This field is a member of `oneof`_ ``_carrier_service``. + origin_postal_code (str): + Required. Shipping origin for this carrier + rate. + + This field is a member of `oneof`_ ``_origin_postal_code``. + percentage_adjustment (str): + Optional. Multiplicative shipping rate modifier as a number + in decimal notation. Can be negative. For example ``"5.4"`` + increases the rate by 5.4%, ``"-3"`` decreases the rate by + 3%. + + This field is a member of `oneof`_ ``_percentage_adjustment``. + flat_adjustment (google.shopping.type.types.Price): + Optional. Additive shipping rate modifier. Can be negative. + For example + ``{ "amount_micros": 1, "currency_code" : "USD" }`` adds $1 + to the rate, + ``{ "amount_micros": -3, "currency_code" : "USD" }`` removes + $3 from the rate. + + This field is a member of `oneof`_ ``_flat_adjustment``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + carrier: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + carrier_service: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + origin_postal_code: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + percentage_adjustment: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + flat_adjustment: types.Price = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=types.Price, + ) + + +class GetShippingSettingsRequest(proto.Message): + r"""Request message for the ``GetShippingSetting`` method. + + Attributes: + name (str): + Required. The name of the shipping setting to retrieve. + Format: ``accounts/{account}/shippingsetting`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InsertShippingSettingsRequest(proto.Message): + r"""Request message for the ``InsertShippingSetting`` method. + + Attributes: + parent (str): + Required. The account where this product will + be inserted. Format: accounts/{account} + shipping_setting (google.shopping.merchant_accounts_v1beta.types.ShippingSettings): + Required. The new version of the account. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + shipping_setting: 'ShippingSettings' = proto.Field( + proto.MESSAGE, + number=2, + message='ShippingSettings', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py new file mode 100644 index 000000000000..e6c4397d8032 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py @@ -0,0 +1,149 @@ +# -*- 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.type import interval_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'TaxRule', + }, +) + + +class TaxRule(proto.Message): + r"""Primary type convension + + percent micro : 100% = 1 000 000 and 1% = 10 000 + cannot be negative. + + Information about tax nexus and related parameters applicable to + orders delivered to the area covered by a single tax admin. + Nexus is created when a merchant is doing business in an area + administered by tax admin (only US states are supported for + nexus configuration). If merchant has nexus in a US state, + merchant needs to pay tax to all tax authorities associated with + the shipping destination. + Next Id : 8 + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location_id (int): + The admin_id or criteria_id of the region in which this rule + is applicable. + + This field is a member of `oneof`_ ``location``. + post_code_range (google.shopping.merchant_accounts_v1beta.types.TaxRule.TaxPostalCodeRange): + The range of postal codes in which this rule + is applicable. + + This field is a member of `oneof`_ ``location``. + use_google_rate (bool): + Rate that depends on delivery location: if + merchant has a nexus in corresponding US state, + rates from authorities with jurisdiction over + delivery area are added up. + + This field is a member of `oneof`_ ``rate_calculation``. + self_specified_rate_micros (int): + A fixed rate specified in micros, where 100% = 1_000_000. + Suitable for origin-based states. + + This field is a member of `oneof`_ ``rate_calculation``. + region_code (str): + Region code in which this rule is applicable + shipping_taxed (bool): + If set, shipping charge is taxed (at the same + rate as product) when delivering to this admin's + area. Can only be set on US states without + category. + effective_time_period (google.type.interval_pb2.Interval): + Required. Time period when this rule is effective. If the + duration is missing from effective_time listed, then it is + open ended to the future. The start of this time period is + inclusive, and the end is exclusive. + """ + + class TaxPostalCodeRange(proto.Message): + r"""A range of postal codes that defines the area. + + Attributes: + start (str): + Required. The start of the postal code range, + which is also the smallest in the range. + end (str): + The end of the postal code range. Will be the + same as start if not specified. + """ + + start: str = proto.Field( + proto.STRING, + number=1, + ) + end: str = proto.Field( + proto.STRING, + number=2, + ) + + location_id: int = proto.Field( + proto.INT64, + number=2, + oneof='location', + ) + post_code_range: TaxPostalCodeRange = proto.Field( + proto.MESSAGE, + number=3, + oneof='location', + message=TaxPostalCodeRange, + ) + use_google_rate: bool = proto.Field( + proto.BOOL, + number=4, + oneof='rate_calculation', + ) + self_specified_rate_micros: int = proto.Field( + proto.INT64, + number=5, + oneof='rate_calculation', + ) + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + shipping_taxed: bool = proto.Field( + proto.BOOL, + number=6, + ) + effective_time_period: interval_pb2.Interval = proto.Field( + proto.MESSAGE, + number=7, + message=interval_pb2.Interval, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py new file mode 100644 index 000000000000..729b76843be8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py @@ -0,0 +1,164 @@ +# -*- 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_accounts_v1beta.types import termsofservicekind + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'TermsOfService', + 'GetTermsOfServiceRequest', + 'RetrieveLatestTermsOfServiceRequest', + 'AcceptTermsOfServiceRequest', + }, +) + + +class TermsOfService(proto.Message): + r"""A ``TermsOfService``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the terms of service + version. Format: ``termsOfService/{version}`` + region_code (str): + Region code as defined by + `CLDR `__. This is either a + country where the ToS applies specifically to that country + or ``001`` when the same ``TermsOfService`` can be signed in + any country. However note that when signing a ToS that + applies globally we still expect that a specific country is + provided (this should be merchant business country or + program country of participation). + kind (google.shopping.merchant_accounts_v1beta.types.TermsOfServiceKind): + The Kind this terms of service version + applies to. + file_uri (str): + URI for terms of service file that needs to + be displayed to signing users. + + This field is a member of `oneof`_ ``_file_uri``. + external (bool): + Whether this terms of service version is + external. External terms of service versions can + only be agreed through external processes and + not directly by the merchant through UI or API. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + kind: termsofservicekind.TermsOfServiceKind = proto.Field( + proto.ENUM, + number=3, + enum=termsofservicekind.TermsOfServiceKind, + ) + file_uri: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + external: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class GetTermsOfServiceRequest(proto.Message): + r"""Request message for the ``GetTermsOfService`` method. + + Attributes: + name (str): + Required. The resource name of the terms of service version. + Format: ``termsOfService/{version}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RetrieveLatestTermsOfServiceRequest(proto.Message): + r"""Request message for the ``RetrieveLatestTermsOfService`` method. + + Attributes: + region_code (str): + Required. Region code as defined by + `CLDR `__. This is either a + country when the ToS applies specifically to that country or + 001 when it applies globally. + kind (google.shopping.merchant_accounts_v1beta.types.TermsOfServiceKind): + Required. The Kind this terms of service + version applies to. + """ + + region_code: str = proto.Field( + proto.STRING, + number=1, + ) + kind: termsofservicekind.TermsOfServiceKind = proto.Field( + proto.ENUM, + number=2, + enum=termsofservicekind.TermsOfServiceKind, + ) + + +class AcceptTermsOfServiceRequest(proto.Message): + r"""Request message for the ``AcceptTermsOfService`` method. + + Attributes: + name (str): + Required. The resource name of the terms of service version. + Format: ``termsOfService/{version}`` + account (str): + Required. The account for which to accept the + ToS. + region_code (str): + Required. Region code as defined by + `CLDR `__. This is either a + country when the ToS applies specifically to that country or + 001 when it applies globally. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: str = proto.Field( + proto.STRING, + number=2, + ) + region_code: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py new file mode 100644 index 000000000000..236621a96424 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py @@ -0,0 +1,217 @@ +# -*- 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_accounts_v1beta.types import termsofservicekind +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'TermsOfServiceAgreementState', + 'Accepted', + 'Required', + 'GetTermsOfServiceAgreementStateRequest', + 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + }, +) + + +class TermsOfServiceAgreementState(proto.Message): + r"""This resource represents the agreement state for a given account and + terms of service kind. The state is as follows: + + - If the merchant has accepted a terms of service: + `accepted `__ will be + populated, otherwise it will be empty + - If the merchant must sign a terms of service: + `required `__ will be + populated, otherwise it will be empty. + + Note that both `required `__ + and `accepted `__ can be + present. In this case the ``accepted`` terms of services will have + an expiration date set in the `valid_until `__ + field. The ``required`` terms of services need to be accepted before + ``valid_until`` in order for the account to continue having a valid + agreement. When accepting new terms of services we expect 3Ps to + display the text associated with the given terms of service + agreement (the url to the file containing the text is added in the + Required message below as `tos_file_uri `__. + The actual acceptance of the terms of service is done by calling + accept on the `TermsOfService `__ resource. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The resource name of the terms of service + version. Format: + ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` + The identifier format is: ``{TermsOfServiceKind}-{country}`` + For example, an identifier could be: ``MERCHANT_CENTER-US`` + region_code (str): + Region code as defined by + https://cldr.unicode.org/. This is the country + the current state applies to. + terms_of_service_kind (google.shopping.merchant_accounts_v1beta.types.TermsOfServiceKind): + Terms of Service kind associated with the + particular version. + accepted (google.shopping.merchant_accounts_v1beta.types.Accepted): + The accepted terms of service of this kind and for the + associated region_code + + This field is a member of `oneof`_ ``_accepted``. + required (google.shopping.merchant_accounts_v1beta.types.Required): + The required terms of service + + This field is a member of `oneof`_ ``_required``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + region_code: str = proto.Field( + proto.STRING, + number=2, + ) + terms_of_service_kind: termsofservicekind.TermsOfServiceKind = proto.Field( + proto.ENUM, + number=3, + enum=termsofservicekind.TermsOfServiceKind, + ) + accepted: 'Accepted' = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message='Accepted', + ) + required: 'Required' = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message='Required', + ) + + +class Accepted(proto.Message): + r"""Describes the accepted terms of service. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + terms_of_service (str): + The accepted + `termsOfService `__. + accepted_by (str): + The account where the acceptance was + recorded. This can be the account itself or, in + the case of subaccounts, the MCA account. + valid_until (google.type.date_pb2.Date): + When set, it states that the accepted + `TermsOfService `__ + is only valid until the end of this date (in UTC). A new one + must be accepted before then. The information of the + required + `TermsOfService `__ + is found in the `Required `__ message. + + This field is a member of `oneof`_ ``_valid_until``. + """ + + terms_of_service: str = proto.Field( + proto.STRING, + number=1, + ) + accepted_by: str = proto.Field( + proto.STRING, + number=2, + ) + valid_until: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=date_pb2.Date, + ) + + +class Required(proto.Message): + r"""Describes the terms of service which are required to be + accepted. + + Attributes: + terms_of_service (str): + The + `termsOfService `__ + that need to be accepted. + tos_file_uri (str): + Full URL to the terms of service file. This field is the + same as + `TermsOfService.file_uri `__, it is + added here for convenience only. + """ + + terms_of_service: str = proto.Field( + proto.STRING, + number=1, + ) + tos_file_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTermsOfServiceAgreementStateRequest(proto.Message): + r"""Request message for the ``GetTermsOfServiceAgreementState`` method. + + Attributes: + name (str): + Required. The resource name of the terms of service version. + Format: + ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` + The identifier format is: ``{TermsOfServiceKind}-{country}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RetrieveForApplicationTermsOfServiceAgreementStateRequest(proto.Message): + r"""Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` method. + + Attributes: + parent (str): + Required. The account for which to get a + TermsOfServiceAgreementState Format: ``accounts/{account}`` + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py new file mode 100644 index 000000000000..3a69671fc592 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py @@ -0,0 +1,44 @@ +# -*- 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 + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'TermsOfServiceKind', + }, +) + + +class TermsOfServiceKind(proto.Enum): + r"""The TermsOfService Kind. + + Values: + TERMS_OF_SERVICE_KIND_UNSPECIFIED (0): + Default value. This value is unused. + MERCHANT_CENTER (1): + Merchant Center application. + """ + TERMS_OF_SERVICE_KIND_UNSPECIFIED = 0 + MERCHANT_CENTER = 1 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py new file mode 100644 index 000000000000..f291bde9bd29 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py @@ -0,0 +1,246 @@ +# -*- 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.protobuf import field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.types import accessright + + +__protobuf__ = proto.module( + package='google.shopping.merchant.accounts.v1beta', + manifest={ + 'User', + 'GetUserRequest', + 'CreateUserRequest', + 'DeleteUserRequest', + 'UpdateUserRequest', + 'ListUsersRequest', + 'ListUsersResponse', + }, +) + + +class User(proto.Message): + r"""A `user `__. + + Attributes: + name (str): + Identifier. The resource name of the user. Format: + ``accounts/{account}/user/{email}`` + + Use ``me`` to refer to your own email address, for example + ``accounts/{account}/users/me``. + state (google.shopping.merchant_accounts_v1beta.types.User.State): + Output only. The state of the user. + access_rights (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccessRight]): + Optional. The `access + rights `__ + the user has. + """ + class State(proto.Enum): + r"""The possible states of a user. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + PENDING (1): + The user is pending confirmation. In this + state, the user first needs to accept the + invitation before performing other actions. + VERIFIED (2): + The user is verified. + """ + STATE_UNSPECIFIED = 0 + PENDING = 1 + VERIFIED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + access_rights: MutableSequence[accessright.AccessRight] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=accessright.AccessRight, + ) + + +class GetUserRequest(proto.Message): + r"""Request message for the ``GetUser`` method. + + Attributes: + name (str): + Required. The name of the user to retrieve. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to retrieve the user corresponding to + the caller by using ``me`` rather than an email address as + in ``accounts/{account}/users/me``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateUserRequest(proto.Message): + r"""Request message for the ``CreateUser`` method. + + Attributes: + parent (str): + Required. The resource name of the account for which a user + will be created. Format: ``accounts/{account}`` + user_id (str): + Required. The email address of the user (for example, + ``john.doe@gmail.com``). + user (google.shopping.merchant_accounts_v1beta.types.User): + Required. The user to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_id: str = proto.Field( + proto.STRING, + number=2, + ) + user: 'User' = proto.Field( + proto.MESSAGE, + number=3, + message='User', + ) + + +class DeleteUserRequest(proto.Message): + r"""Request message for the ``DeleteUser`` method. + + Attributes: + name (str): + Required. The name of the user to delete. Format: + ``accounts/{account}/users/{email}`` + + It is also possible to delete the user corresponding to the + caller by using ``me`` rather than an email address as in + ``accounts/{account}/users/me``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateUserRequest(proto.Message): + r"""Request message for the ``UpdateUser`` method. + + Attributes: + user (google.shopping.merchant_accounts_v1beta.types.User): + Required. The new version of the user. + + Use ``me`` to refer to your own email address, for example + ``accounts/{account}/users/me``. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields being updated. + """ + + user: 'User' = proto.Field( + proto.MESSAGE, + number=1, + message='User', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListUsersRequest(proto.Message): + r"""Request message for the ``ListUsers`` method. + + Attributes: + parent (str): + Required. The parent, which owns this collection of users. + Format: ``accounts/{account}`` + page_size (int): + Optional. The maximum number of users to + return. The service may return fewer than this + value. If unspecified, at most 50 users will be + returned. The maximum value is 100; values above + 100 will be coerced to 100 + page_token (str): + Optional. A page token, received from a previous + ``ListUsers`` call. Provide this to retrieve the subsequent + page. + + When paginating, all other parameters provided to + ``ListUsers`` must match the call that provided the page + token. + """ + + 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 ListUsersResponse(proto.Message): + r"""Response message for the ``ListUsers`` method. + + Attributes: + users (MutableSequence[google.shopping.merchant_accounts_v1beta.types.User]): + The users from the specified account. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + users: MutableSequence['User'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='User', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py new file mode 100644 index 000000000000..cc47a9500d4c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts" + +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-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py new file mode 100644 index 000000000000..5ea1b7df8abb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_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 ListAccountIssues +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_accounts_v1beta + + +async def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1beta.AccountIssueServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py new file mode 100644 index 000000000000..739c8d0391ad --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_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 ListAccountIssues +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_accounts_v1beta + + +def sample_list_account_issues(): + # Create a client + client = merchant_accounts_v1beta.AccountIssueServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountIssuesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_issues(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py new file mode 100644 index 000000000000..2662cf461666 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccountTax +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_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_accounts_v1beta + + +async def sample_get_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountTaxRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account_tax(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py new file mode 100644 index 000000000000..b6096fa0a5d5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccountTax +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_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_accounts_v1beta + + +def sample_get_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountTaxRequest( + name="name_value", + ) + + # Make the request + response = client.get_account_tax(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py new file mode 100644 index 000000000000..f97f38ee917e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_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 ListAccountTax +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_accounts_v1beta + + +async def sample_list_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountTaxRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_tax(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py new file mode 100644 index 000000000000..97b36a68f990 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_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 ListAccountTax +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_accounts_v1beta + + +def sample_list_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountTaxRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_account_tax(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py new file mode 100644 index 000000000000..a9ceabeaaf9b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAccountTax +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_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_accounts_v1beta + + +async def sample_update_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAccountTaxRequest( + ) + + # Make the request + response = await client.update_account_tax(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py new file mode 100644 index 000000000000..0b93d3fd84ac --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAccountTax +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_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_accounts_v1beta + + +def sample_update_account_tax(): + # Create a client + client = merchant_accounts_v1beta.AccountTaxServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAccountTaxRequest( + ) + + # Make the request + response = client.update_account_tax(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py new file mode 100644 index 000000000000..524357227830 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_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 CreateAndConfigureAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_v1beta + + +async def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = await client.create_and_configure_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py new file mode 100644 index 000000000000..eb1ec2212f92 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_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 CreateAndConfigureAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_v1beta + + +def sample_create_and_configure_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( + account=account, + ) + + # Make the request + response = client.create_and_configure_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_async.py new file mode 100644 index 000000000000..c5fd09662410 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_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 DeleteAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_v1beta + + +async def sample_delete_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_account(request=request) + + +# [END merchantapi_v1beta_generated_AccountsService_DeleteAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_sync.py new file mode 100644 index 000000000000..d57059d3101d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_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 DeleteAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_v1beta + + +def sample_delete_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_account(request=request) + + +# [END merchantapi_v1beta_generated_AccountsService_DeleteAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.py new file mode 100644 index 000000000000..ccb025b6469a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_GetAccount_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_accounts_v1beta + + +async def sample_get_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_GetAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.py new file mode 100644 index 000000000000..683f29580390 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_GetAccount_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_accounts_v1beta + + +def sample_get_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_GetAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.py new file mode 100644 index 000000000000..295ac6219ea6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAccounts +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_ListAccounts_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_accounts_v1beta + + +async def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_ListAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py new file mode 100644 index 000000000000..efbf4429fd18 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAccounts +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_ListAccounts_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_accounts_v1beta + + +def sample_list_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_ListAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py new file mode 100644 index 000000000000..7310b1ccc6bb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_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 ListSubAccounts +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_v1beta + + +async def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_ListSubAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py new file mode 100644 index 000000000000..0fd54afc2a11 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_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 ListSubAccounts +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_v1beta + + +def sample_list_sub_accounts(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListSubAccountsRequest( + provider="provider_value", + ) + + # Make the request + page_result = client.list_sub_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_ListSubAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_async.py new file mode 100644 index 000000000000..c4daae8aecfa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_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 UpdateAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_v1beta + + +async def sample_update_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceAsyncClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = await client.update_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_UpdateAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_sync.py new file mode 100644 index 000000000000..b218b58166f5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_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 UpdateAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_v1beta + + +def sample_update_account(): + # Create a client + client = merchant_accounts_v1beta.AccountsServiceClient() + + # Initialize request argument(s) + account = merchant_accounts_v1beta.Account() + account.account_name = "account_name_value" + account.language_code = "language_code_value" + + request = merchant_accounts_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = client.update_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AccountsService_UpdateAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py new file mode 100644 index 000000000000..3a477d5ec29a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_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_accounts_v1beta + + +async def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py new file mode 100644 index 000000000000..57b46e0531a5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_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_accounts_v1beta + + +def sample_get_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py new file mode 100644 index 000000000000..6c4f2b643787 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_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_accounts_v1beta + + +async def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = await client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py new file mode 100644 index 000000000000..58e602d06f98 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutofeedSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_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_accounts_v1beta + + +def sample_update_autofeed_settings(): + # Create a client + client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() + + # Initialize request argument(s) + autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() + autofeed_settings.enable_products = True + + request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( + autofeed_settings=autofeed_settings, + ) + + # Make the request + response = client.update_autofeed_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py new file mode 100644 index 000000000000..c87df778f553 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_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_accounts_v1beta + + +async def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py new file mode 100644 index 000000000000..853d693b8371 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_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_accounts_v1beta + + +def sample_get_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( + name="name_value", + ) + + # Make the request + response = client.get_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py new file mode 100644 index 000000000000..75bde8f2d529 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_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_accounts_v1beta + + +async def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = await client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py new file mode 100644 index 000000000000..ec9c3fbf4e48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutomaticImprovements +# 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-accounts + + +# [START merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_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_accounts_v1beta + + +def sample_update_automatic_improvements(): + # Create a client + client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( + ) + + # Make the request + response = client.update_automatic_improvements(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py new file mode 100644 index 000000000000..9fc9a1b3d682 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_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_accounts_v1beta + + +async def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py new file mode 100644 index 000000000000..4d4cd1ebdf0c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_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_accounts_v1beta + + +def sample_get_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessIdentityRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py new file mode 100644 index 000000000000..ff68aacc2ec1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_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_accounts_v1beta + + +async def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( + ) + + # Make the request + response = await client.update_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py new file mode 100644 index 000000000000..a0f345b233a9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessIdentity +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_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_accounts_v1beta + + +def sample_update_business_identity(): + # Create a client + client = merchant_accounts_v1beta.BusinessIdentityServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( + ) + + # Make the request + response = client.update_business_identity(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.py new file mode 100644 index 000000000000..b1f8ef39945c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessInfo +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_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_accounts_v1beta + + +async def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.get_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py new file mode 100644 index 000000000000..1e9c258b7ba2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetBusinessInfo +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_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_accounts_v1beta + + +def sample_get_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetBusinessInfoRequest( + name="name_value", + ) + + # Make the request + response = client.get_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.py new file mode 100644 index 000000000000..ff4add791367 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessInfo +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_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_accounts_v1beta + + +async def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( + ) + + # Make the request + response = await client.update_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py new file mode 100644 index 000000000000..757ae6ca4bb7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateBusinessInfo +# 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-accounts + + +# [START merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_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_accounts_v1beta + + +def sample_update_business_info(): + # Create a client + client = merchant_accounts_v1beta.BusinessInfoServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( + ) + + # Make the request + response = client.update_business_info(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py new file mode 100644 index 000000000000..28e4bb99f04a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_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_accounts_v1beta + + +async def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py new file mode 100644 index 000000000000..878e17cad080 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_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_accounts_v1beta + + +def sample_create_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py new file mode 100644 index 000000000000..72c9127845e9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_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 DeleteCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_accounts_v1beta + + +async def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + await client.delete_checkout_settings(request=request) + + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py new file mode 100644 index 000000000000..b4475c2cf898 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_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 DeleteCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_accounts_v1beta + + +def sample_delete_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + client.delete_checkout_settings(request=request) + + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py new file mode 100644 index 000000000000..11ff8acc9dfa --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_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_accounts_v1beta + + +async def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py new file mode 100644 index 000000000000..50b282ea7ce8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_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_accounts_v1beta + + +def sample_get_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py new file mode 100644 index 000000000000..5ffcb28a76ef --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_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_accounts_v1beta + + +async def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = await client.update_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py new file mode 100644 index 000000000000..22842b5365e3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCheckoutSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_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_accounts_v1beta + + +def sample_update_checkout_settings(): + # Create a client + client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( + ) + + # Make the request + response = client.update_checkout_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py new file mode 100644 index 000000000000..8bd2011f1ecd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEmailPreferences +# 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-accounts + + +# [START merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_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_accounts_v1beta + + +async def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = await client.get_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py new file mode 100644 index 000000000000..a255955c9efe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEmailPreferences +# 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-accounts + + +# [START merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_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_accounts_v1beta + + +def sample_get_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetEmailPreferencesRequest( + name="name_value", + ) + + # Make the request + response = client.get_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py new file mode 100644 index 000000000000..d9006e7658b5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEmailPreferences +# 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-accounts + + +# [START merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_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_accounts_v1beta + + +async def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = await client.update_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py new file mode 100644 index 000000000000..f31e1b2eb8ea --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEmailPreferences +# 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-accounts + + +# [START merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_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_accounts_v1beta + + +def sample_update_email_preferences(): + # Create a client + client = merchant_accounts_v1beta.EmailPreferencesServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( + ) + + # Make the request + response = client.update_email_preferences(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py new file mode 100644 index 000000000000..eecf278345da --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_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 LinkGbpAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_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_accounts_v1beta + + +async def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = await client.link_gbp_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py new file mode 100644 index 000000000000..f006819a7953 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_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 LinkGbpAccount +# 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-accounts + + +# [START merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_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_accounts_v1beta + + +def sample_link_gbp_account(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkGbpAccountRequest( + parent="parent_value", + gbp_email="gbp_email_value", + ) + + # Make the request + response = client.link_gbp_account(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py new file mode 100644 index 000000000000..7d57d61ec1bb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_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 ListGbpAccounts +# 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-accounts + + +# [START merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_accounts_v1beta + + +async def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py new file mode 100644 index 000000000000..1a542285bb4d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_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 ListGbpAccounts +# 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-accounts + + +# [START merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_accounts_v1beta + + +def sample_list_gbp_accounts(): + # Create a client + client = merchant_accounts_v1beta.GbpAccountsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListGbpAccountsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_gbp_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py new file mode 100644 index 000000000000..47084883b718 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClaimHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_ClaimHomepage_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_accounts_v1beta + + +async def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.claim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_ClaimHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py new file mode 100644 index 000000000000..d4c0253ec7a2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ClaimHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_ClaimHomepage_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_accounts_v1beta + + +def sample_claim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ClaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.claim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_ClaimHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.py new file mode 100644 index 000000000000..f7b6ea4eda79 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_GetHomepage_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_accounts_v1beta + + +async def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.get_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_GetHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py new file mode 100644 index 000000000000..4c187f50e991 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_GetHomepage_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_accounts_v1beta + + +def sample_get_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.get_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_GetHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py new file mode 100644 index 000000000000..6466c1c9a80c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UnclaimHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_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_accounts_v1beta + + +async def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = await client.unclaim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py new file mode 100644 index 000000000000..0504a1783151 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UnclaimHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_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_accounts_v1beta + + +def sample_unclaim_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UnclaimHomepageRequest( + name="name_value", + ) + + # Make the request + response = client.unclaim_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.py new file mode 100644 index 000000000000..5c13393f78e8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_UpdateHomepage_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_accounts_v1beta + + +async def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateHomepageRequest( + ) + + # Make the request + response = await client.update_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_UpdateHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py new file mode 100644 index 000000000000..f442ce3d814f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHomepage +# 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-accounts + + +# [START merchantapi_v1beta_generated_HomepageService_UpdateHomepage_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_accounts_v1beta + + +def sample_update_homepage(): + # Create a client + client = merchant_accounts_v1beta.HomepageServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateHomepageRequest( + ) + + # Make the request + response = client.update_homepage(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_HomepageService_UpdateHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py new file mode 100644 index 000000000000..a12e25483799 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_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 FindLfpProviders +# 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-accounts + + +# [START merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_accounts_v1beta + + +async def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py new file mode 100644 index 000000000000..8bf78a657d87 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_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 FindLfpProviders +# 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-accounts + + +# [START merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_accounts_v1beta + + +def sample_find_lfp_providers(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.FindLfpProvidersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.find_lfp_providers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py new file mode 100644 index 000000000000..f587f5c30f63 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_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 LinkLfpProvider +# 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-accounts + + +# [START merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_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_accounts_v1beta + + +async def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = await client.link_lfp_provider(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py new file mode 100644 index 000000000000..b239c070f95e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_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 LinkLfpProvider +# 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-accounts + + +# [START merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_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_accounts_v1beta + + +def sample_link_lfp_provider(): + # Create a client + client = merchant_accounts_v1beta.LfpProvidersServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.LinkLfpProviderRequest( + name="name_value", + external_account_id="external_account_id_value", + ) + + # Make the request + response = client.link_lfp_provider(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py new file mode 100644 index 000000000000..706c449172d5 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py @@ -0,0 +1,57 @@ +# -*- 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 CreateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_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_accounts_v1beta + + +async def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py new file mode 100644 index 000000000000..a7f32f69d2be --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py @@ -0,0 +1,57 @@ +# -*- 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 CreateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_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_accounts_v1beta + + +def sample_create_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( + parent="parent_value", + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.create_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py new file mode 100644 index 000000000000..bfe1ccd11d64 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_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_accounts_v1beta + + +async def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py new file mode 100644 index 000000000000..033e27b3fc48 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_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_accounts_v1beta + + +def sample_get_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( + name="name_value", + ) + + # Make the request + response = client.get_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py new file mode 100644 index 000000000000..9b0867ed5318 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_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 ListOmnichannelSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_accounts_v1beta + + +async def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py new file mode 100644 index 000000000000..6115d5a97488 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_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 ListOmnichannelSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_accounts_v1beta + + +def sample_list_omnichannel_settings(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_omnichannel_settings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py new file mode 100644 index 000000000000..7d0336409326 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RequestInventoryVerification +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_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_accounts_v1beta + + +async def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = await client.request_inventory_verification(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py new file mode 100644 index 000000000000..2b46b003b68f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RequestInventoryVerification +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_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_accounts_v1beta + + +def sample_request_inventory_verification(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( + name="name_value", + ) + + # Make the request + response = client.request_inventory_verification(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py new file mode 100644 index 000000000000..1525ff8561bb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_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 UpdateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_accounts_v1beta + + +async def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = await client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py new file mode 100644 index 000000000000..0c5da4398674 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_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 UpdateOmnichannelSetting +# 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-accounts + + +# [START merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_accounts_v1beta + + +def sample_update_omnichannel_setting(): + # Create a client + client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() + + # Initialize request argument(s) + omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() + omnichannel_setting.region_code = "region_code_value" + omnichannel_setting.lsf_type = "MHLSF_FULL" + + request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( + omnichannel_setting=omnichannel_setting, + ) + + # Make the request + response = client.update_omnichannel_setting(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py new file mode 100644 index 000000000000..7405774b5722 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py @@ -0,0 +1,58 @@ +# -*- 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 CreateOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_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_accounts_v1beta + + +async def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = await client.create_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py new file mode 100644 index 000000000000..d66ca038b30d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py @@ -0,0 +1,58 @@ +# -*- 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 CreateOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_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_accounts_v1beta + + +def sample_create_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( + parent="parent_value", + online_return_policy=online_return_policy, + ) + + # Make the request + response = client.create_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py new file mode 100644 index 000000000000..a4b12a0aaa87 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_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 DeleteOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_accounts_v1beta + + +async def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + await client.delete_online_return_policy(request=request) + + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py new file mode 100644 index 000000000000..a4825bcfce55 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_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 DeleteOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_accounts_v1beta + + +def sample_delete_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + client.delete_online_return_policy(request=request) + + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py new file mode 100644 index 000000000000..d1de7bf6b60e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_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_accounts_v1beta + + +async def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py new file mode 100644 index 000000000000..36882cfc09ef --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_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_accounts_v1beta + + +def sample_get_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py new file mode 100644 index 000000000000..66d247a87dd2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_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 ListOnlineReturnPolicies +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_accounts_v1beta + + +async def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py new file mode 100644 index 000000000000..12c5a18b044e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_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 ListOnlineReturnPolicies +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_accounts_v1beta + + +def sample_list_online_return_policies(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_online_return_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py new file mode 100644 index 000000000000..0681372595cc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py @@ -0,0 +1,57 @@ +# -*- 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 UpdateOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_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_accounts_v1beta + + +async def sample_update_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( + online_return_policy=online_return_policy, + ) + + # Make the request + response = await client.update_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py new file mode 100644 index 000000000000..c49e13300805 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py @@ -0,0 +1,57 @@ +# -*- 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 UpdateOnlineReturnPolicy +# 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-accounts + + +# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_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_accounts_v1beta + + +def sample_update_online_return_policy(): + # Create a client + client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() + + # Initialize request argument(s) + online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() + online_return_policy.label = "label_value" + online_return_policy.countries = ['countries_value1', 'countries_value2'] + online_return_policy.return_policy_uri = "return_policy_uri_value" + + request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( + online_return_policy=online_return_policy, + ) + + # Make the request + response = client.update_online_return_policy(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.py new file mode 100644 index 000000000000..2e7d9113e35c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableProgram +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_DisableProgram_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_accounts_v1beta + + +async def sample_disable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.disable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_DisableProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.py new file mode 100644 index 000000000000..725616f474bf --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DisableProgram +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_DisableProgram_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_accounts_v1beta + + +def sample_disable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DisableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.disable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_DisableProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.py new file mode 100644 index 000000000000..f3d12b6b5f39 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableProgram +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_EnableProgram_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_accounts_v1beta + + +async def sample_enable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.enable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_EnableProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.py new file mode 100644 index 000000000000..3dd0e3ab6043 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EnableProgram +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_EnableProgram_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_accounts_v1beta + + +def sample_enable_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.EnableProgramRequest( + name="name_value", + ) + + # Make the request + response = client.enable_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_EnableProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.py new file mode 100644 index 000000000000..94b8bc9539e9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProgram +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_GetProgram_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_accounts_v1beta + + +async def sample_get_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = await client.get_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_GetProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.py new file mode 100644 index 000000000000..19a37108cc6c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetProgram +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_GetProgram_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_accounts_v1beta + + +def sample_get_program(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetProgramRequest( + name="name_value", + ) + + # Make the request + response = client.get_program(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_GetProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_async.py new file mode 100644 index 000000000000..37e62d581817 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_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 ListPrograms +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_accounts_v1beta + + +async def sample_list_programs(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_ListPrograms_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_sync.py new file mode 100644 index 000000000000..05d0c02972d1 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_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 ListPrograms +# 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-accounts + + +# [START merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_accounts_v1beta + + +def sample_list_programs(): + # Create a client + client = merchant_accounts_v1beta.ProgramsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListProgramsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_programs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_ProgramsService_ListPrograms_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_async.py new file mode 100644 index 000000000000..37b7945cd1a3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_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 CreateRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_CreateRegion_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_accounts_v1beta + + +async def sample_create_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = await client.create_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_CreateRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_sync.py new file mode 100644 index 000000000000..a217601a8724 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_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 CreateRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_CreateRegion_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_accounts_v1beta + + +def sample_create_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateRegionRequest( + parent="parent_value", + region_id="region_id_value", + ) + + # Make the request + response = client.create_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_CreateRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_async.py new file mode 100644 index 000000000000..6237e626537d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_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 DeleteRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_accounts_v1beta + + +async def sample_delete_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + await client.delete_region(request=request) + + +# [END merchantapi_v1beta_generated_RegionsService_DeleteRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_sync.py new file mode 100644 index 000000000000..7a62517691d6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_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 DeleteRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_accounts_v1beta + + +def sample_delete_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteRegionRequest( + name="name_value", + ) + + # Make the request + client.delete_region(request=request) + + +# [END merchantapi_v1beta_generated_RegionsService_DeleteRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.py new file mode 100644 index 000000000000..6e421a6a23fd --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_GetRegion_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_accounts_v1beta + + +async def sample_get_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_GetRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.py new file mode 100644 index 000000000000..cf0d010b865e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_GetRegion_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_accounts_v1beta + + +def sample_get_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetRegionRequest( + name="name_value", + ) + + # Make the request + response = client.get_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_GetRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_async.py new file mode 100644 index 000000000000..c726eac7e898 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_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 ListRegions +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_ListRegions_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_accounts_v1beta + + +async def sample_list_regions(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_ListRegions_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_sync.py new file mode 100644 index 000000000000..a8805b8fe32a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_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 ListRegions +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_ListRegions_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_accounts_v1beta + + +def sample_list_regions(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListRegionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_regions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_ListRegions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.py new file mode 100644 index 000000000000..08d6a255a2af --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_UpdateRegion_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_accounts_v1beta + + +async def sample_update_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateRegionRequest( + ) + + # Make the request + response = await client.update_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_UpdateRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.py new file mode 100644 index 000000000000..6a00cfe1fc80 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRegion +# 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-accounts + + +# [START merchantapi_v1beta_generated_RegionsService_UpdateRegion_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_accounts_v1beta + + +def sample_update_region(): + # Create a client + client = merchant_accounts_v1beta.RegionsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateRegionRequest( + ) + + # Make the request + response = client.update_region(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_RegionsService_UpdateRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py new file mode 100644 index 000000000000..4323f9346b15 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetShippingSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_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_accounts_v1beta + + +async def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py new file mode 100644 index 000000000000..fee404678476 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetShippingSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_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_accounts_v1beta + + +def sample_get_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetShippingSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py new file mode 100644 index 000000000000..da31f8338dd9 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_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 InsertShippingSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_accounts_v1beta + + +async def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1beta.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1beta.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = await client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py new file mode 100644 index 000000000000..d8e4f2b2bfdc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_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 InsertShippingSettings +# 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-accounts + + +# [START merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_accounts_v1beta + + +def sample_insert_shipping_settings(): + # Create a client + client = merchant_accounts_v1beta.ShippingSettingsServiceClient() + + # Initialize request argument(s) + shipping_setting = merchant_accounts_v1beta.ShippingSettings() + shipping_setting.etag = "etag_value" + + request = merchant_accounts_v1beta.InsertShippingSettingsRequest( + parent="parent_value", + shipping_setting=shipping_setting, + ) + + # Make the request + response = client.insert_shipping_settings(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py new file mode 100644 index 000000000000..0f464690997a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_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_accounts_v1beta + + +async def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py new file mode 100644 index 000000000000..9c656bb9d8c7 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_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_accounts_v1beta + + +def sample_get_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py new file mode 100644 index 000000000000..2d22c2e0d3fe --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveForApplicationTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_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_accounts_v1beta + + +async def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py new file mode 100644 index 000000000000..5c6186ae2016 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveForApplicationTermsOfServiceAgreementState +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_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_accounts_v1beta + + +def sample_retrieve_for_application_terms_of_service_agreement_state(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", + ) + + # Make the request + response = client.retrieve_for_application_terms_of_service_agreement_state(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py new file mode 100644 index 000000000000..97be366b0de4 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcceptTermsOfService +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_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_accounts_v1beta + + +async def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + await client.accept_terms_of_service(request=request) + + +# [END merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py new file mode 100644 index 000000000000..31dda0c65fe0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcceptTermsOfService +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_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_accounts_v1beta + + +def sample_accept_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( + name="name_value", + account="account_value", + region_code="region_code_value", + ) + + # Make the request + client.accept_terms_of_service(request=request) + + +# [END merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py new file mode 100644 index 000000000000..322da3d5840c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfService +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_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_accounts_v1beta + + +async def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py new file mode 100644 index 000000000000..5210b6498a73 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTermsOfService +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_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_accounts_v1beta + + +def sample_get_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetTermsOfServiceRequest( + name="name_value", + ) + + # Make the request + response = client.get_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py new file mode 100644 index 000000000000..974535b17974 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_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 RetrieveLatestTermsOfService +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_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_accounts_v1beta + + +async def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = await client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py new file mode 100644 index 000000000000..7b020bb5ac91 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_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 RetrieveLatestTermsOfService +# 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-accounts + + +# [START merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_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_accounts_v1beta + + +def sample_retrieve_latest_terms_of_service(): + # Create a client + client = merchant_accounts_v1beta.TermsOfServiceServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( + region_code="region_code_value", + kind="MERCHANT_CENTER", + ) + + # Make the request + response = client.retrieve_latest_terms_of_service(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_async.py new file mode 100644 index 000000000000..4abcac2f7919 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_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 CreateUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_CreateUser_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_accounts_v1beta + + +async def sample_create_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = await client.create_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_UserService_CreateUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_sync.py new file mode 100644 index 000000000000..f36b4ebd09b0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_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 CreateUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_CreateUser_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_accounts_v1beta + + +def sample_create_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + ) + + # Make the request + response = client.create_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_UserService_CreateUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_async.py new file mode 100644 index 000000000000..38af498e1287 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_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 DeleteUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_DeleteUser_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_accounts_v1beta + + +async def sample_delete_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + await client.delete_user(request=request) + + +# [END merchantapi_v1beta_generated_UserService_DeleteUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_sync.py new file mode 100644 index 000000000000..48128db84c71 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_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 DeleteUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_DeleteUser_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_accounts_v1beta + + +def sample_delete_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.DeleteUserRequest( + name="name_value", + ) + + # Make the request + client.delete_user(request=request) + + +# [END merchantapi_v1beta_generated_UserService_DeleteUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.py new file mode 100644 index 000000000000..051bd2395c71 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_GetUser_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_accounts_v1beta + + +async def sample_get_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_UserService_GetUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.py new file mode 100644 index 000000000000..d14d8c6ddc63 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_GetUser_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_accounts_v1beta + + +def sample_get_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.GetUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_UserService_GetUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_async.py new file mode 100644 index 000000000000..ff5126147ce3 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_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 ListUsers +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_ListUsers_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_accounts_v1beta + + +async def sample_list_users(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_UserService_ListUsers_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_sync.py new file mode 100644 index 000000000000..52b2f13b83d2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_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 ListUsers +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_ListUsers_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_accounts_v1beta + + +def sample_list_users(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.ListUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_users(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END merchantapi_v1beta_generated_UserService_ListUsers_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.py new file mode 100644 index 000000000000..8f8af4c92fda --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_UpdateUser_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_accounts_v1beta + + +async def sample_update_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceAsyncClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateUserRequest( + ) + + # Make the request + response = await client.update_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_UserService_UpdateUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.py new file mode 100644 index 000000000000..5d2013ba3077 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateUser +# 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-accounts + + +# [START merchantapi_v1beta_generated_UserService_UpdateUser_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_accounts_v1beta + + +def sample_update_user(): + # Create a client + client = merchant_accounts_v1beta.UserServiceClient() + + # Initialize request argument(s) + request = merchant_accounts_v1beta.UpdateUserRequest( + ) + + # Make the request + response = client.update_user(request=request) + + # Handle the response + print(response) + +# [END merchantapi_v1beta_generated_UserService_UpdateUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json new file mode 100644 index 000000000000..006404653801 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json @@ -0,0 +1,10226 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.shopping.merchant.accounts.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-shopping-merchant-accounts", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceAsyncClient", + "shortName": "AccountIssueServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceAsyncClient.list_account_issues", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService.ListAccountIssues", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", + "shortName": "AccountIssueService" + }, + "shortName": "ListAccountIssues" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest" + }, + { + "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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesAsyncPager", + "shortName": "list_account_issues" + }, + "description": "Sample for ListAccountIssues", + "file": "merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_account_issue_service_list_account_issues_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceClient", + "shortName": "AccountIssueServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceClient.list_account_issues", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService.ListAccountIssues", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", + "shortName": "AccountIssueService" + }, + "shortName": "ListAccountIssues" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest" + }, + { + "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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesPager", + "shortName": "list_account_issues" + }, + "description": "Sample for ListAccountIssues", + "file": "merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_account_issue_service_list_account_issues_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient", + "shortName": "AccountTaxServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient.get_account_tax", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.GetAccountTax", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "shortName": "AccountTaxService" + }, + "shortName": "GetAccountTax" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", + "shortName": "get_account_tax" + }, + "description": "Sample for GetAccountTax", + "file": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient", + "shortName": "AccountTaxServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient.get_account_tax", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.GetAccountTax", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "shortName": "AccountTaxService" + }, + "shortName": "GetAccountTax" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", + "shortName": "get_account_tax" + }, + "description": "Sample for GetAccountTax", + "file": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient", + "shortName": "AccountTaxServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient.list_account_tax", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.ListAccountTax", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "shortName": "AccountTaxService" + }, + "shortName": "ListAccountTax" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest" + }, + { + "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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxAsyncPager", + "shortName": "list_account_tax" + }, + "description": "Sample for ListAccountTax", + "file": "merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_account_tax_service_list_account_tax_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient", + "shortName": "AccountTaxServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient.list_account_tax", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.ListAccountTax", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "shortName": "AccountTaxService" + }, + "shortName": "ListAccountTax" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest" + }, + { + "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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxPager", + "shortName": "list_account_tax" + }, + "description": "Sample for ListAccountTax", + "file": "merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_account_tax_service_list_account_tax_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient", + "shortName": "AccountTaxServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient.update_account_tax", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.UpdateAccountTax", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "shortName": "AccountTaxService" + }, + "shortName": "UpdateAccountTax" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest" + }, + { + "name": "account_tax", + "type": "google.shopping.merchant_accounts_v1beta.types.AccountTax" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.AccountTax", + "shortName": "update_account_tax" + }, + "description": "Sample for UpdateAccountTax", + "file": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient", + "shortName": "AccountTaxServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient.update_account_tax", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.UpdateAccountTax", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", + "shortName": "AccountTaxService" + }, + "shortName": "UpdateAccountTax" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest" + }, + { + "name": "account_tax", + "type": "google.shopping.merchant_accounts_v1beta.types.AccountTax" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.AccountTax", + "shortName": "update_account_tax" + }, + "description": "Sample for UpdateAccountTax", + "file": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.create_and_configure_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.CreateAndConfigureAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "CreateAndConfigureAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest" + }, + { + "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_accounts_v1beta.types.Account", + "shortName": "create_and_configure_account" + }, + "description": "Sample for CreateAndConfigureAccount", + "file": "merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_service_create_and_configure_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.create_and_configure_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.CreateAndConfigureAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "CreateAndConfigureAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest" + }, + { + "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_accounts_v1beta.types.Account", + "shortName": "create_and_configure_account" + }, + "description": "Sample for CreateAndConfigureAccount", + "file": "merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_service_create_and_configure_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.delete_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.DeleteAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "DeleteAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest" + }, + { + "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_account" + }, + "description": "Sample for DeleteAccount", + "file": "merchantapi_v1beta_generated_accounts_service_delete_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_service_delete_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.delete_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.DeleteAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "DeleteAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest" + }, + { + "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_account" + }, + "description": "Sample for DeleteAccount", + "file": "merchantapi_v1beta_generated_accounts_service_delete_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_service_delete_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.get_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.GetAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "GetAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", + "shortName": "get_account" + }, + "description": "Sample for GetAccount", + "file": "merchantapi_v1beta_generated_accounts_service_get_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_GetAccount_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_accounts_service_get_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.get_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.GetAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "GetAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", + "shortName": "get_account" + }, + "description": "Sample for GetAccount", + "file": "merchantapi_v1beta_generated_accounts_service_get_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_GetAccount_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_accounts_service_get_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.list_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest" + }, + { + "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_accounts_v1beta.services.accounts_service.pagers.ListAccountsAsyncPager", + "shortName": "list_accounts" + }, + "description": "Sample for ListAccounts", + "file": "merchantapi_v1beta_generated_accounts_service_list_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_ListAccounts_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_accounts_service_list_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.list_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest" + }, + { + "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_accounts_v1beta.services.accounts_service.pagers.ListAccountsPager", + "shortName": "list_accounts" + }, + "description": "Sample for ListAccounts", + "file": "merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_ListAccounts_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.list_sub_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListSubAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListSubAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest" + }, + { + "name": "provider", + "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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsAsyncPager", + "shortName": "list_sub_accounts" + }, + "description": "Sample for ListSubAccounts", + "file": "merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_service_list_sub_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.list_sub_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListSubAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "ListSubAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest" + }, + { + "name": "provider", + "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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsPager", + "shortName": "list_sub_accounts" + }, + "description": "Sample for ListSubAccounts", + "file": "merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_service_list_sub_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", + "shortName": "AccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.update_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.UpdateAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "UpdateAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest" + }, + { + "name": "account", + "type": "google.shopping.merchant_accounts_v1beta.types.Account" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.Account", + "shortName": "update_account" + }, + "description": "Sample for UpdateAccount", + "file": "merchantapi_v1beta_generated_accounts_service_update_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_service_update_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", + "shortName": "AccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.update_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.UpdateAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", + "shortName": "AccountsService" + }, + "shortName": "UpdateAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest" + }, + { + "name": "account", + "type": "google.shopping.merchant_accounts_v1beta.types.Account" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.Account", + "shortName": "update_account" + }, + "description": "Sample for UpdateAccount", + "file": "merchantapi_v1beta_generated_accounts_service_update_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_service_update_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient", + "shortName": "AutofeedSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient.get_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.GetAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "GetAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", + "shortName": "get_autofeed_settings" + }, + "description": "Sample for GetAutofeedSettings", + "file": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient", + "shortName": "AutofeedSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient.get_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.GetAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "GetAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", + "shortName": "get_autofeed_settings" + }, + "description": "Sample for GetAutofeedSettings", + "file": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient", + "shortName": "AutofeedSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient.update_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.UpdateAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "UpdateAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest" + }, + { + "name": "autofeed_settings", + "type": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.AutofeedSettings", + "shortName": "update_autofeed_settings" + }, + "description": "Sample for UpdateAutofeedSettings", + "file": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient", + "shortName": "AutofeedSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient.update_autofeed_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.UpdateAutofeedSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", + "shortName": "AutofeedSettingsService" + }, + "shortName": "UpdateAutofeedSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest" + }, + { + "name": "autofeed_settings", + "type": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.AutofeedSettings", + "shortName": "update_autofeed_settings" + }, + "description": "Sample for UpdateAutofeedSettings", + "file": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient", + "shortName": "AutomaticImprovementsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient.get_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.GetAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "GetAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements", + "shortName": "get_automatic_improvements" + }, + "description": "Sample for GetAutomaticImprovements", + "file": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient", + "shortName": "AutomaticImprovementsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient.get_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.GetAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "GetAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements", + "shortName": "get_automatic_improvements" + }, + "description": "Sample for GetAutomaticImprovements", + "file": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient", + "shortName": "AutomaticImprovementsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient.update_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.UpdateAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "UpdateAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest" + }, + { + "name": "automatic_improvements", + "type": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.AutomaticImprovements", + "shortName": "update_automatic_improvements" + }, + "description": "Sample for UpdateAutomaticImprovements", + "file": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient", + "shortName": "AutomaticImprovementsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient.update_automatic_improvements", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.UpdateAutomaticImprovements", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", + "shortName": "AutomaticImprovementsService" + }, + "shortName": "UpdateAutomaticImprovements" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest" + }, + { + "name": "automatic_improvements", + "type": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.AutomaticImprovements", + "shortName": "update_automatic_improvements" + }, + "description": "Sample for UpdateAutomaticImprovements", + "file": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient", + "shortName": "BusinessIdentityServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient.get_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.GetBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "GetBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", + "shortName": "get_business_identity" + }, + "description": "Sample for GetBusinessIdentity", + "file": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient", + "shortName": "BusinessIdentityServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient.get_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.GetBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "GetBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", + "shortName": "get_business_identity" + }, + "description": "Sample for GetBusinessIdentity", + "file": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient", + "shortName": "BusinessIdentityServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient.update_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.UpdateBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "UpdateBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest" + }, + { + "name": "business_identity", + "type": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.BusinessIdentity", + "shortName": "update_business_identity" + }, + "description": "Sample for UpdateBusinessIdentity", + "file": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient", + "shortName": "BusinessIdentityServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient.update_business_identity", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.UpdateBusinessIdentity", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", + "shortName": "BusinessIdentityService" + }, + "shortName": "UpdateBusinessIdentity" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest" + }, + { + "name": "business_identity", + "type": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.BusinessIdentity", + "shortName": "update_business_identity" + }, + "description": "Sample for UpdateBusinessIdentity", + "file": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient", + "shortName": "BusinessInfoServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient.get_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.GetBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "GetBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", + "shortName": "get_business_info" + }, + "description": "Sample for GetBusinessInfo", + "file": "merchantapi_v1beta_generated_business_info_service_get_business_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_info_service_get_business_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient", + "shortName": "BusinessInfoServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient.get_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.GetBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "GetBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", + "shortName": "get_business_info" + }, + "description": "Sample for GetBusinessInfo", + "file": "merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient", + "shortName": "BusinessInfoServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient.update_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.UpdateBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "UpdateBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest" + }, + { + "name": "business_info", + "type": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.BusinessInfo", + "shortName": "update_business_info" + }, + "description": "Sample for UpdateBusinessInfo", + "file": "merchantapi_v1beta_generated_business_info_service_update_business_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_info_service_update_business_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient", + "shortName": "BusinessInfoServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient.update_business_info", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.UpdateBusinessInfo", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", + "shortName": "BusinessInfoService" + }, + "shortName": "UpdateBusinessInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest" + }, + { + "name": "business_info", + "type": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.BusinessInfo", + "shortName": "update_business_info" + }, + "description": "Sample for UpdateBusinessInfo", + "file": "merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.create_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.CreateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "CreateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" + }, + { + "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_accounts_v1beta.types.CheckoutSettings", + "shortName": "create_checkout_settings" + }, + "description": "Sample for CreateCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.create_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.CreateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "CreateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" + }, + { + "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_accounts_v1beta.types.CheckoutSettings", + "shortName": "create_checkout_settings" + }, + "description": "Sample for CreateCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.delete_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.DeleteCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "DeleteCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest" + }, + { + "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_checkout_settings" + }, + "description": "Sample for DeleteCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_checkout_settings_service_delete_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.delete_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.DeleteCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "DeleteCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest" + }, + { + "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_checkout_settings" + }, + "description": "Sample for DeleteCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_checkout_settings_service_delete_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.get_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.GetCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "GetCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings", + "shortName": "get_checkout_settings" + }, + "description": "Sample for GetCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.get_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.GetCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "GetCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings", + "shortName": "get_checkout_settings" + }, + "description": "Sample for GetCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", + "shortName": "CheckoutSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.update_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.UpdateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "UpdateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.CheckoutSettings", + "shortName": "update_checkout_settings" + }, + "description": "Sample for UpdateCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", + "shortName": "CheckoutSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.update_checkout_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.UpdateCheckoutSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", + "shortName": "CheckoutSettingsService" + }, + "shortName": "UpdateCheckoutSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest" + }, + { + "name": "checkout_settings", + "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.CheckoutSettings", + "shortName": "update_checkout_settings" + }, + "description": "Sample for UpdateCheckoutSettings", + "file": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient", + "shortName": "EmailPreferencesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient.get_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.GetEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "GetEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", + "shortName": "get_email_preferences" + }, + "description": "Sample for GetEmailPreferences", + "file": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient", + "shortName": "EmailPreferencesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient.get_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.GetEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "GetEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", + "shortName": "get_email_preferences" + }, + "description": "Sample for GetEmailPreferences", + "file": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient", + "shortName": "EmailPreferencesServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient.update_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.UpdateEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "UpdateEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest" + }, + { + "name": "email_preferences", + "type": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.EmailPreferences", + "shortName": "update_email_preferences" + }, + "description": "Sample for UpdateEmailPreferences", + "file": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient", + "shortName": "EmailPreferencesServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient.update_email_preferences", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.UpdateEmailPreferences", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", + "shortName": "EmailPreferencesService" + }, + "shortName": "UpdateEmailPreferences" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest" + }, + { + "name": "email_preferences", + "type": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.EmailPreferences", + "shortName": "update_email_preferences" + }, + "description": "Sample for UpdateEmailPreferences", + "file": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient", + "shortName": "GbpAccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient.link_gbp_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.LinkGbpAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "LinkGbpAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest" + }, + { + "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_accounts_v1beta.types.LinkGbpAccountResponse", + "shortName": "link_gbp_account" + }, + "description": "Sample for LinkGbpAccount", + "file": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient", + "shortName": "GbpAccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient.link_gbp_account", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.LinkGbpAccount", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "LinkGbpAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest" + }, + { + "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_accounts_v1beta.types.LinkGbpAccountResponse", + "shortName": "link_gbp_account" + }, + "description": "Sample for LinkGbpAccount", + "file": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient", + "shortName": "GbpAccountsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient.list_gbp_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.ListGbpAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "ListGbpAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest" + }, + { + "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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsAsyncPager", + "shortName": "list_gbp_accounts" + }, + "description": "Sample for ListGbpAccounts", + "file": "merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_gbp_accounts_service_list_gbp_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient", + "shortName": "GbpAccountsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient.list_gbp_accounts", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.ListGbpAccounts", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", + "shortName": "GbpAccountsService" + }, + "shortName": "ListGbpAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest" + }, + { + "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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsPager", + "shortName": "list_gbp_accounts" + }, + "description": "Sample for ListGbpAccounts", + "file": "merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_gbp_accounts_service_list_gbp_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.claim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.ClaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "ClaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest" + }, + { + "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_accounts_v1beta.types.Homepage", + "shortName": "claim_homepage" + }, + "description": "Sample for ClaimHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_ClaimHomepage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.claim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.ClaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "ClaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest" + }, + { + "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_accounts_v1beta.types.Homepage", + "shortName": "claim_homepage" + }, + "description": "Sample for ClaimHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_ClaimHomepage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.get_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.GetHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "GetHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", + "shortName": "get_homepage" + }, + "description": "Sample for GetHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_get_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_GetHomepage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_get_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.get_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.GetHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "GetHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", + "shortName": "get_homepage" + }, + "description": "Sample for GetHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_GetHomepage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.unclaim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UnclaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UnclaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest" + }, + { + "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_accounts_v1beta.types.Homepage", + "shortName": "unclaim_homepage" + }, + "description": "Sample for UnclaimHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.unclaim_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UnclaimHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UnclaimHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest" + }, + { + "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_accounts_v1beta.types.Homepage", + "shortName": "unclaim_homepage" + }, + "description": "Sample for UnclaimHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", + "shortName": "HomepageServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.update_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UpdateHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UpdateHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest" + }, + { + "name": "homepage", + "type": "google.shopping.merchant_accounts_v1beta.types.Homepage" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.Homepage", + "shortName": "update_homepage" + }, + "description": "Sample for UpdateHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_update_homepage_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_UpdateHomepage_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_update_homepage_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", + "shortName": "HomepageServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.update_homepage", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UpdateHomepage", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", + "shortName": "HomepageService" + }, + "shortName": "UpdateHomepage" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest" + }, + { + "name": "homepage", + "type": "google.shopping.merchant_accounts_v1beta.types.Homepage" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.Homepage", + "shortName": "update_homepage" + }, + "description": "Sample for UpdateHomepage", + "file": "merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_HomepageService_UpdateHomepage_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient", + "shortName": "LfpProvidersServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient.find_lfp_providers", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.FindLfpProviders", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "FindLfpProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest" + }, + { + "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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersAsyncPager", + "shortName": "find_lfp_providers" + }, + "description": "Sample for FindLfpProviders", + "file": "merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_lfp_providers_service_find_lfp_providers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient", + "shortName": "LfpProvidersServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient.find_lfp_providers", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.FindLfpProviders", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "FindLfpProviders" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest" + }, + { + "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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersPager", + "shortName": "find_lfp_providers" + }, + "description": "Sample for FindLfpProviders", + "file": "merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_lfp_providers_service_find_lfp_providers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient", + "shortName": "LfpProvidersServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient.link_lfp_provider", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.LinkLfpProvider", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "LinkLfpProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse", + "shortName": "link_lfp_provider" + }, + "description": "Sample for LinkLfpProvider", + "file": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient", + "shortName": "LfpProvidersServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient.link_lfp_provider", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.LinkLfpProvider", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", + "shortName": "LfpProvidersService" + }, + "shortName": "LinkLfpProvider" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse", + "shortName": "link_lfp_provider" + }, + "description": "Sample for LinkLfpProvider", + "file": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.create_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.CreateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "CreateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" + }, + { + "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_accounts_v1beta.types.OmnichannelSetting", + "shortName": "create_omnichannel_setting" + }, + "description": "Sample for CreateOmnichannelSetting", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.create_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.CreateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "CreateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" + }, + { + "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_accounts_v1beta.types.OmnichannelSetting", + "shortName": "create_omnichannel_setting" + }, + "description": "Sample for CreateOmnichannelSetting", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.get_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.GetOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "GetOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting", + "shortName": "get_omnichannel_setting" + }, + "description": "Sample for GetOmnichannelSetting", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.get_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.GetOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "GetOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting", + "shortName": "get_omnichannel_setting" + }, + "description": "Sample for GetOmnichannelSetting", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.list_omnichannel_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.ListOmnichannelSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "ListOmnichannelSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest" + }, + { + "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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsAsyncPager", + "shortName": "list_omnichannel_settings" + }, + "description": "Sample for ListOmnichannelSettings", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_omnichannel_settings_service_list_omnichannel_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.list_omnichannel_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.ListOmnichannelSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "ListOmnichannelSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest" + }, + { + "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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsPager", + "shortName": "list_omnichannel_settings" + }, + "description": "Sample for ListOmnichannelSettings", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_omnichannel_settings_service_list_omnichannel_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.request_inventory_verification", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.RequestInventoryVerification", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "RequestInventoryVerification" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse", + "shortName": "request_inventory_verification" + }, + "description": "Sample for RequestInventoryVerification", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.request_inventory_verification", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.RequestInventoryVerification", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "RequestInventoryVerification" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse", + "shortName": "request_inventory_verification" + }, + "description": "Sample for RequestInventoryVerification", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", + "shortName": "OmnichannelSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.update_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.UpdateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "UpdateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.OmnichannelSetting", + "shortName": "update_omnichannel_setting" + }, + "description": "Sample for UpdateOmnichannelSetting", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_omnichannel_settings_service_update_omnichannel_setting_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", + "shortName": "OmnichannelSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.update_omnichannel_setting", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.UpdateOmnichannelSetting", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", + "shortName": "OmnichannelSettingsService" + }, + "shortName": "UpdateOmnichannelSetting" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest" + }, + { + "name": "omnichannel_setting", + "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.OmnichannelSetting", + "shortName": "update_omnichannel_setting" + }, + "description": "Sample for UpdateOmnichannelSetting", + "file": "merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_omnichannel_settings_service_update_omnichannel_setting_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.create_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.CreateOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "CreateOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "online_return_policy", + "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" + }, + { + "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_accounts_v1beta.types.OnlineReturnPolicy", + "shortName": "create_online_return_policy" + }, + "description": "Sample for CreateOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.create_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.CreateOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "CreateOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "online_return_policy", + "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" + }, + { + "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_accounts_v1beta.types.OnlineReturnPolicy", + "shortName": "create_online_return_policy" + }, + "description": "Sample for CreateOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.delete_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.DeleteOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "DeleteOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest" + }, + { + "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_online_return_policy" + }, + "description": "Sample for DeleteOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_online_return_policy_service_delete_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.delete_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.DeleteOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "DeleteOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest" + }, + { + "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_online_return_policy" + }, + "description": "Sample for DeleteOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_online_return_policy_service_delete_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.get_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.GetOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "GetOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy", + "shortName": "get_online_return_policy" + }, + "description": "Sample for GetOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.get_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.GetOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "GetOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy", + "shortName": "get_online_return_policy" + }, + "description": "Sample for GetOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.list_online_return_policies", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.ListOnlineReturnPolicies", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "ListOnlineReturnPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest" + }, + { + "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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager", + "shortName": "list_online_return_policies" + }, + "description": "Sample for ListOnlineReturnPolicies", + "file": "merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_online_return_policy_service_list_online_return_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.list_online_return_policies", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.ListOnlineReturnPolicies", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "ListOnlineReturnPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest" + }, + { + "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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager", + "shortName": "list_online_return_policies" + }, + "description": "Sample for ListOnlineReturnPolicies", + "file": "merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_online_return_policy_service_list_online_return_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", + "shortName": "OnlineReturnPolicyServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.update_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.UpdateOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "UpdateOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest" + }, + { + "name": "online_return_policy", + "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.OnlineReturnPolicy", + "shortName": "update_online_return_policy" + }, + "description": "Sample for UpdateOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", + "shortName": "OnlineReturnPolicyServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.update_online_return_policy", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.UpdateOnlineReturnPolicy", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", + "shortName": "OnlineReturnPolicyService" + }, + "shortName": "UpdateOnlineReturnPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest" + }, + { + "name": "online_return_policy", + "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.OnlineReturnPolicy", + "shortName": "update_online_return_policy" + }, + "description": "Sample for UpdateOnlineReturnPolicy", + "file": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.disable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.DisableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "DisableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", + "shortName": "disable_program" + }, + "description": "Sample for DisableProgram", + "file": "merchantapi_v1beta_generated_programs_service_disable_program_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_DisableProgram_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_programs_service_disable_program_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.disable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.DisableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "DisableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", + "shortName": "disable_program" + }, + "description": "Sample for DisableProgram", + "file": "merchantapi_v1beta_generated_programs_service_disable_program_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_DisableProgram_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_programs_service_disable_program_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.enable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.EnableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "EnableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", + "shortName": "enable_program" + }, + "description": "Sample for EnableProgram", + "file": "merchantapi_v1beta_generated_programs_service_enable_program_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_EnableProgram_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_programs_service_enable_program_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.enable_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.EnableProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "EnableProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", + "shortName": "enable_program" + }, + "description": "Sample for EnableProgram", + "file": "merchantapi_v1beta_generated_programs_service_enable_program_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_EnableProgram_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_programs_service_enable_program_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.get_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.GetProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "GetProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", + "shortName": "get_program" + }, + "description": "Sample for GetProgram", + "file": "merchantapi_v1beta_generated_programs_service_get_program_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_GetProgram_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_programs_service_get_program_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.get_program", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.GetProgram", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "GetProgram" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetProgramRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", + "shortName": "get_program" + }, + "description": "Sample for GetProgram", + "file": "merchantapi_v1beta_generated_programs_service_get_program_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_GetProgram_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_programs_service_get_program_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", + "shortName": "ProgramsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.list_programs", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.ListPrograms", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "ListPrograms" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest" + }, + { + "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_accounts_v1beta.services.programs_service.pagers.ListProgramsAsyncPager", + "shortName": "list_programs" + }, + "description": "Sample for ListPrograms", + "file": "merchantapi_v1beta_generated_programs_service_list_programs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_programs_service_list_programs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", + "shortName": "ProgramsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.list_programs", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.ListPrograms", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", + "shortName": "ProgramsService" + }, + "shortName": "ListPrograms" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest" + }, + { + "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_accounts_v1beta.services.programs_service.pagers.ListProgramsPager", + "shortName": "list_programs" + }, + "description": "Sample for ListPrograms", + "file": "merchantapi_v1beta_generated_programs_service_list_programs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_programs_service_list_programs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.create_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.CreateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "CreateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1beta.types.Region" + }, + { + "name": "region_id", + "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_accounts_v1beta.types.Region", + "shortName": "create_region" + }, + "description": "Sample for CreateRegion", + "file": "merchantapi_v1beta_generated_regions_service_create_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_CreateRegion_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regions_service_create_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.create_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.CreateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "CreateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1beta.types.Region" + }, + { + "name": "region_id", + "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_accounts_v1beta.types.Region", + "shortName": "create_region" + }, + "description": "Sample for CreateRegion", + "file": "merchantapi_v1beta_generated_regions_service_create_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_CreateRegion_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regions_service_create_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.delete_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.DeleteRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "DeleteRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest" + }, + { + "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_region" + }, + "description": "Sample for DeleteRegion", + "file": "merchantapi_v1beta_generated_regions_service_delete_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_regions_service_delete_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.delete_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.DeleteRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "DeleteRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest" + }, + { + "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_region" + }, + "description": "Sample for DeleteRegion", + "file": "merchantapi_v1beta_generated_regions_service_delete_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_regions_service_delete_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.get_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.GetRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "GetRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetRegionRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", + "shortName": "get_region" + }, + "description": "Sample for GetRegion", + "file": "merchantapi_v1beta_generated_regions_service_get_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_GetRegion_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regions_service_get_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.get_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.GetRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "GetRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetRegionRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", + "shortName": "get_region" + }, + "description": "Sample for GetRegion", + "file": "merchantapi_v1beta_generated_regions_service_get_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_GetRegion_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regions_service_get_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.list_regions", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.ListRegions", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "ListRegions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest" + }, + { + "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_accounts_v1beta.services.regions_service.pagers.ListRegionsAsyncPager", + "shortName": "list_regions" + }, + "description": "Sample for ListRegions", + "file": "merchantapi_v1beta_generated_regions_service_list_regions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_ListRegions_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_regions_service_list_regions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.list_regions", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.ListRegions", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "ListRegions" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest" + }, + { + "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_accounts_v1beta.services.regions_service.pagers.ListRegionsPager", + "shortName": "list_regions" + }, + "description": "Sample for ListRegions", + "file": "merchantapi_v1beta_generated_regions_service_list_regions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_ListRegions_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_regions_service_list_regions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", + "shortName": "RegionsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.update_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.UpdateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "UpdateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1beta.types.Region" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.Region", + "shortName": "update_region" + }, + "description": "Sample for UpdateRegion", + "file": "merchantapi_v1beta_generated_regions_service_update_region_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_UpdateRegion_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regions_service_update_region_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", + "shortName": "RegionsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.update_region", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.UpdateRegion", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", + "shortName": "RegionsService" + }, + "shortName": "UpdateRegion" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest" + }, + { + "name": "region", + "type": "google.shopping.merchant_accounts_v1beta.types.Region" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.Region", + "shortName": "update_region" + }, + "description": "Sample for UpdateRegion", + "file": "merchantapi_v1beta_generated_regions_service_update_region_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_RegionsService_UpdateRegion_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_regions_service_update_region_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient", + "shortName": "ShippingSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient.get_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.GetShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "GetShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", + "shortName": "get_shipping_settings" + }, + "description": "Sample for GetShippingSettings", + "file": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient", + "shortName": "ShippingSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient.get_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.GetShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "GetShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", + "shortName": "get_shipping_settings" + }, + "description": "Sample for GetShippingSettings", + "file": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient", + "shortName": "ShippingSettingsServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient.insert_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.InsertShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "InsertShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest" + }, + { + "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_accounts_v1beta.types.ShippingSettings", + "shortName": "insert_shipping_settings" + }, + "description": "Sample for InsertShippingSettings", + "file": "merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_shipping_settings_service_insert_shipping_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient", + "shortName": "ShippingSettingsServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient.insert_shipping_settings", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.InsertShippingSettings", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", + "shortName": "ShippingSettingsService" + }, + "shortName": "InsertShippingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest" + }, + { + "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_accounts_v1beta.types.ShippingSettings", + "shortName": "insert_shipping_settings" + }, + "description": "Sample for InsertShippingSettings", + "file": "merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_shipping_settings_service_insert_shipping_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient", + "shortName": "TermsOfServiceAgreementStateServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient.get_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.GetTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "GetTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", + "shortName": "get_terms_of_service_agreement_state" + }, + "description": "Sample for GetTermsOfServiceAgreementState", + "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient", + "shortName": "TermsOfServiceAgreementStateServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.GetTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "GetTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", + "shortName": "get_terms_of_service_agreement_state" + }, + "description": "Sample for GetTermsOfServiceAgreementState", + "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient", + "shortName": "TermsOfServiceAgreementStateServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient.retrieve_for_application_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.RetrieveForApplicationTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "RetrieveForApplicationTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest" + }, + { + "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_accounts_v1beta.types.TermsOfServiceAgreementState", + "shortName": "retrieve_for_application_terms_of_service_agreement_state" + }, + "description": "Sample for RetrieveForApplicationTermsOfServiceAgreementState", + "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient", + "shortName": "TermsOfServiceAgreementStateServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.RetrieveForApplicationTermsOfServiceAgreementState", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", + "shortName": "TermsOfServiceAgreementStateService" + }, + "shortName": "RetrieveForApplicationTermsOfServiceAgreementState" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest" + }, + { + "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_accounts_v1beta.types.TermsOfServiceAgreementState", + "shortName": "retrieve_for_application_terms_of_service_agreement_state" + }, + "description": "Sample for RetrieveForApplicationTermsOfServiceAgreementState", + "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient", + "shortName": "TermsOfServiceServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient.accept_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.AcceptTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "AcceptTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest" + }, + { + "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": "accept_terms_of_service" + }, + "description": "Sample for AcceptTermsOfService", + "file": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient", + "shortName": "TermsOfServiceServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient.accept_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.AcceptTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "AcceptTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest" + }, + { + "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": "accept_terms_of_service" + }, + "description": "Sample for AcceptTermsOfService", + "file": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient", + "shortName": "TermsOfServiceServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient.get_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.GetTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "GetTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", + "shortName": "get_terms_of_service" + }, + "description": "Sample for GetTermsOfService", + "file": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient", + "shortName": "TermsOfServiceServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient.get_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.GetTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "GetTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", + "shortName": "get_terms_of_service" + }, + "description": "Sample for GetTermsOfService", + "file": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient", + "shortName": "TermsOfServiceServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient.retrieve_latest_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.RetrieveLatestTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "RetrieveLatestTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest" + }, + { + "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_accounts_v1beta.types.TermsOfService", + "shortName": "retrieve_latest_terms_of_service" + }, + "description": "Sample for RetrieveLatestTermsOfService", + "file": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient", + "shortName": "TermsOfServiceServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.RetrieveLatestTermsOfService", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", + "shortName": "TermsOfServiceService" + }, + "shortName": "RetrieveLatestTermsOfService" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest" + }, + { + "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_accounts_v1beta.types.TermsOfService", + "shortName": "retrieve_latest_terms_of_service" + }, + "description": "Sample for RetrieveLatestTermsOfService", + "file": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.create_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.CreateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1beta.types.User" + }, + { + "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_accounts_v1beta.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "merchantapi_v1beta_generated_user_service_create_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_CreateUser_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_user_service_create_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.create_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.CreateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "CreateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.CreateUserRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1beta.types.User" + }, + { + "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_accounts_v1beta.types.User", + "shortName": "create_user" + }, + "description": "Sample for CreateUser", + "file": "merchantapi_v1beta_generated_user_service_create_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_CreateUser_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_user_service_create_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.delete_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.DeleteUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest" + }, + { + "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_user" + }, + "description": "Sample for DeleteUser", + "file": "merchantapi_v1beta_generated_user_service_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_DeleteUser_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_user_service_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.delete_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.DeleteUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest" + }, + { + "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_user" + }, + "description": "Sample for DeleteUser", + "file": "merchantapi_v1beta_generated_user_service_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_DeleteUser_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_user_service_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.get_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.GetUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetUserRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "merchantapi_v1beta_generated_user_service_get_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_GetUser_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_user_service_get_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.get_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.GetUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "GetUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.GetUserRequest" + }, + { + "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]]]" + } + ], + "resultType": "google.shopping.merchant_accounts_v1beta.types.User", + "shortName": "get_user" + }, + "description": "Sample for GetUser", + "file": "merchantapi_v1beta_generated_user_service_get_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_GetUser_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_user_service_get_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.list_users", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.ListUsers", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListUsersRequest" + }, + { + "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_accounts_v1beta.services.user_service.pagers.ListUsersAsyncPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "merchantapi_v1beta_generated_user_service_list_users_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_ListUsers_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_user_service_list_users_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.list_users", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.ListUsers", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "ListUsers" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.ListUsersRequest" + }, + { + "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_accounts_v1beta.services.user_service.pagers.ListUsersPager", + "shortName": "list_users" + }, + "description": "Sample for ListUsers", + "file": "merchantapi_v1beta_generated_user_service_list_users_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_ListUsers_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_user_service_list_users_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", + "shortName": "UserServiceAsyncClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.update_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.UpdateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1beta.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "merchantapi_v1beta_generated_user_service_update_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_UpdateUser_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_user_service_update_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", + "shortName": "UserServiceClient" + }, + "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.update_user", + "method": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService.UpdateUser", + "service": { + "fullName": "google.shopping.merchant.accounts.v1beta.UserService", + "shortName": "UserService" + }, + "shortName": "UpdateUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest" + }, + { + "name": "user", + "type": "google.shopping.merchant_accounts_v1beta.types.User" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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_accounts_v1beta.types.User", + "shortName": "update_user" + }, + "description": "Sample for UpdateUser", + "file": "merchantapi_v1beta_generated_user_service_update_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "merchantapi_v1beta_generated_UserService_UpdateUser_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "merchantapi_v1beta_generated_user_service_update_user_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py new file mode 100644 index 000000000000..3f1eb8528ccc --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py @@ -0,0 +1,238 @@ +#! /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_accountsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'accept_terms_of_service': ('name', 'account', 'region_code', ), + 'claim_homepage': ('name', ), + 'create_and_configure_account': ('account', 'service', 'users', 'accept_terms_of_service', ), + 'create_checkout_settings': ('parent', 'checkout_settings', ), + 'create_omnichannel_setting': ('parent', 'omnichannel_setting', ), + 'create_online_return_policy': ('parent', 'online_return_policy', ), + 'create_region': ('parent', 'region_id', 'region', ), + 'create_user': ('parent', 'user_id', 'user', ), + 'delete_account': ('name', 'force', ), + 'delete_checkout_settings': ('name', ), + 'delete_online_return_policy': ('name', ), + 'delete_region': ('name', ), + 'delete_user': ('name', ), + 'disable_program': ('name', ), + 'enable_program': ('name', ), + 'find_lfp_providers': ('parent', 'page_size', 'page_token', ), + 'get_account': ('name', ), + 'get_account_tax': ('name', ), + 'get_autofeed_settings': ('name', ), + 'get_automatic_improvements': ('name', ), + 'get_business_identity': ('name', ), + 'get_business_info': ('name', ), + 'get_checkout_settings': ('name', ), + 'get_email_preferences': ('name', ), + 'get_homepage': ('name', ), + 'get_omnichannel_setting': ('name', ), + 'get_online_return_policy': ('name', ), + 'get_program': ('name', ), + 'get_region': ('name', ), + 'get_shipping_settings': ('name', ), + 'get_terms_of_service': ('name', ), + 'get_terms_of_service_agreement_state': ('name', ), + 'get_user': ('name', ), + 'insert_shipping_settings': ('parent', 'shipping_setting', ), + 'link_gbp_account': ('parent', 'gbp_email', ), + 'link_lfp_provider': ('name', 'external_account_id', ), + 'list_account_issues': ('parent', 'page_size', 'page_token', 'language_code', 'time_zone', ), + 'list_accounts': ('page_size', 'page_token', 'filter', ), + 'list_account_tax': ('parent', 'page_size', 'page_token', ), + 'list_gbp_accounts': ('parent', 'page_size', 'page_token', ), + 'list_omnichannel_settings': ('parent', 'page_size', 'page_token', ), + 'list_online_return_policies': ('parent', 'page_size', 'page_token', ), + 'list_programs': ('parent', 'page_size', 'page_token', ), + 'list_regions': ('parent', 'page_size', 'page_token', ), + 'list_sub_accounts': ('provider', 'page_size', 'page_token', ), + 'list_users': ('parent', 'page_size', 'page_token', ), + 'request_inventory_verification': ('name', ), + 'retrieve_for_application_terms_of_service_agreement_state': ('parent', ), + 'retrieve_latest_terms_of_service': ('region_code', 'kind', ), + 'unclaim_homepage': ('name', ), + 'update_account': ('account', 'update_mask', ), + 'update_account_tax': ('account_tax', 'update_mask', ), + 'update_autofeed_settings': ('autofeed_settings', 'update_mask', ), + 'update_automatic_improvements': ('automatic_improvements', 'update_mask', ), + 'update_business_identity': ('business_identity', 'update_mask', ), + 'update_business_info': ('business_info', 'update_mask', ), + 'update_checkout_settings': ('checkout_settings', 'update_mask', ), + 'update_email_preferences': ('email_preferences', 'update_mask', ), + 'update_homepage': ('homepage', 'update_mask', ), + 'update_omnichannel_setting': ('omnichannel_setting', 'update_mask', ), + 'update_online_return_policy': ('online_return_policy', 'update_mask', ), + 'update_region': ('region', 'update_mask', ), + 'update_user': ('user', 'update_mask', ), + } + + 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_accountsCallTransformer(), +): + """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_accounts 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-accounts/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/setup.py new file mode 100644 index 000000000000..9c31c0f0922e --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts' + + +description = "Google Shopping Merchant Accounts API client library" + +version = None + +with open(os.path.join(package_root, 'google/shopping/merchant_accounts/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-accounts" + +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-accounts/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.txt new file mode 100644 index 000000000000..0112695e5bbb --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..2af887ec8ba0 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..4cae520d02b2 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py new file mode 100644 index 000000000000..b7516e226838 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py @@ -0,0 +1,2418 @@ +# -*- 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.shopping.merchant_accounts_v1beta.services.account_issue_service import AccountIssueServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.account_issue_service import AccountIssueServiceClient +from google.shopping.merchant_accounts_v1beta.services.account_issue_service import pagers +from google.shopping.merchant_accounts_v1beta.services.account_issue_service import transports +from google.shopping.merchant_accounts_v1beta.types import accountissue +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 AccountIssueServiceClient._get_default_mtls_endpoint(None) is None + assert AccountIssueServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountIssueServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountIssueServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountIssueServiceClient._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 AccountIssueServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountIssueServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountIssueServiceClient._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 AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, False) is None + assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountIssueServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountIssueServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountIssueServiceClient._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 AccountIssueServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountIssueServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountIssueServiceClient._get_universe_domain(None, None) == AccountIssueServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountIssueServiceClient._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 = AccountIssueServiceClient(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 = AccountIssueServiceClient(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", [ + (AccountIssueServiceClient, "grpc"), + (AccountIssueServiceAsyncClient, "grpc_asyncio"), + (AccountIssueServiceClient, "rest"), +]) +def test_account_issue_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.AccountIssueServiceGrpcTransport, "grpc"), + (transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountIssueServiceRestTransport, "rest"), +]) +def test_account_issue_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", [ + (AccountIssueServiceClient, "grpc"), + (AccountIssueServiceAsyncClient, "grpc_asyncio"), + (AccountIssueServiceClient, "rest"), +]) +def test_account_issue_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_account_issue_service_client_get_transport_class(): + transport = AccountIssueServiceClient.get_transport_class() + available_transports = [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountIssueServiceClient.get_transport_class("grpc") + assert transport == transports.AccountIssueServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +def test_account_issue_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(AccountIssueServiceClient, '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(AccountIssueServiceClient, '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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "true"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "false"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "true"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_account_issue_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", [ + AccountIssueServiceClient, AccountIssueServiceAsyncClient +]) +@mock.patch.object(AccountIssueServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceAsyncClient)) +def test_account_issue_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", [ + AccountIssueServiceClient, AccountIssueServiceAsyncClient +]) +@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) +@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +def test_account_issue_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountIssueServiceClient._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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), +]) +def test_account_issue_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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", None), +]) +def test_account_issue_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_account_issue_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountIssueServiceClient( + 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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_account_issue_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", [ + accountissue.ListAccountIssuesRequest, + dict, +]) +def test_list_account_issues(request_type, transport: str = 'grpc'): + client = AccountIssueServiceClient( + 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_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountissue.ListAccountIssuesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accountissue.ListAccountIssuesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountIssuesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_issues_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 = AccountIssueServiceClient( + 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 = accountissue.ListAccountIssuesRequest( + parent='parent_value', + page_token='page_token_value', + language_code='language_code_value', + time_zone='time_zone_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_issues(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accountissue.ListAccountIssuesRequest( + parent='parent_value', + page_token='page_token_value', + language_code='language_code_value', + time_zone='time_zone_value', + ) + +def test_list_account_issues_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 = AccountIssueServiceClient( + 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_account_issues in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_issues] = mock_rpc + request = {} + client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_issues(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_account_issues_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 = AccountIssueServiceAsyncClient( + 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_account_issues 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_account_issues] = mock_rpc + + request = {} + await client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_account_issues(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_account_issues_async(transport: str = 'grpc_asyncio', request_type=accountissue.ListAccountIssuesRequest): + client = AccountIssueServiceAsyncClient( + 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_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accountissue.ListAccountIssuesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountIssuesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_issues_async_from_dict(): + await test_list_account_issues_async(request_type=dict) + +def test_list_account_issues_field_headers(): + client = AccountIssueServiceClient( + 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 = accountissue.ListAccountIssuesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value = accountissue.ListAccountIssuesResponse() + client.list_account_issues(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_account_issues_field_headers_async(): + client = AccountIssueServiceAsyncClient( + 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 = accountissue.ListAccountIssuesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) + await client.list_account_issues(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_account_issues_flattened(): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountissue.ListAccountIssuesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_account_issues( + 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_account_issues_flattened_error(): + client = AccountIssueServiceClient( + 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_account_issues( + accountissue.ListAccountIssuesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_account_issues_flattened_async(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accountissue.ListAccountIssuesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_account_issues( + 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_account_issues_flattened_error_async(): + client = AccountIssueServiceAsyncClient( + 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_account_issues( + accountissue.ListAccountIssuesRequest(), + parent='parent_value', + ) + + +def test_list_account_issues_pager(transport_name: str = "grpc"): + client = AccountIssueServiceClient( + 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_account_issues), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_account_issues(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, accountissue.AccountIssue) + for i in results) +def test_list_account_issues_pages(transport_name: str = "grpc"): + client = AccountIssueServiceClient( + 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_account_issues), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_issues(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_account_issues_async_pager(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_issues(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, accountissue.AccountIssue) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_issues_async_pages(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + 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_account_issues(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_account_issues_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 = AccountIssueServiceClient( + 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_account_issues in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_issues] = mock_rpc + + request = {} + client.list_account_issues(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_issues(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_account_issues_rest_required_fields(request_type=accountissue.ListAccountIssuesRequest): + transport_class = transports.AccountIssueServiceRestTransport + + 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_account_issues._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_account_issues._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("language_code", "page_size", "page_token", "time_zone", )) + 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 = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accountissue.ListAccountIssuesResponse() + # 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 = accountissue.ListAccountIssuesResponse.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_account_issues(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_account_issues_rest_unset_required_fields(): + transport = transports.AccountIssueServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_account_issues._get_unset_required_fields({}) + assert set(unset_fields) == (set(("languageCode", "pageSize", "pageToken", "timeZone", )) & set(("parent", ))) + + +def test_list_account_issues_rest_flattened(): + client = AccountIssueServiceClient( + 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 = accountissue.ListAccountIssuesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = accountissue.ListAccountIssuesResponse.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_account_issues(**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/accounts/v1beta/{parent=accounts/*}/issues" % client.transport._host, args[1]) + + +def test_list_account_issues_rest_flattened_error(transport: str = 'rest'): + client = AccountIssueServiceClient( + 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_account_issues( + accountissue.ListAccountIssuesRequest(), + parent='parent_value', + ) + + +def test_list_account_issues_rest_pager(transport: str = 'rest'): + client = AccountIssueServiceClient( + 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 = ( + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + next_page_token='abc', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[], + next_page_token='def', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + ], + next_page_token='ghi', + ), + accountissue.ListAccountIssuesResponse( + account_issues=[ + accountissue.AccountIssue(), + accountissue.AccountIssue(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accountissue.ListAccountIssuesResponse.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'} + + pager = client.list_account_issues(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accountissue.AccountIssue) + for i in results) + + pages = list(client.list_account_issues(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + 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 = AccountIssueServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountIssueServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountIssueServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountIssueServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountIssueServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + transports.AccountIssueServiceRestTransport, +]) +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 = AccountIssueServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountIssueServiceClient( + 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_account_issues_empty_call_grpc(): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + call.return_value = accountissue.ListAccountIssuesResponse() + client.list_account_issues(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountissue.ListAccountIssuesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountIssueServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountIssueServiceAsyncClient( + 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_account_issues_empty_call_grpc_asyncio(): + client = AccountIssueServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( + next_page_token='next_page_token_value', + )) + await client.list_account_issues(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountissue.ListAccountIssuesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountIssueServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_account_issues_rest_bad_request(request_type=accountissue.ListAccountIssuesRequest): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_account_issues(request) + + +@pytest.mark.parametrize("request_type", [ + accountissue.ListAccountIssuesRequest, + dict, +]) +def test_list_account_issues_rest_call_success(request_type): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accountissue.ListAccountIssuesResponse( + 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 = accountissue.ListAccountIssuesResponse.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_account_issues(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountIssuesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_issues_rest_interceptors(null_interceptor): + transport = transports.AccountIssueServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountIssueServiceRestInterceptor(), + ) + client = AccountIssueServiceClient(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.AccountIssueServiceRestInterceptor, "post_list_account_issues") as post, \ + mock.patch.object(transports.AccountIssueServiceRestInterceptor, "post_list_account_issues_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountIssueServiceRestInterceptor, "pre_list_account_issues") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accountissue.ListAccountIssuesRequest.pb(accountissue.ListAccountIssuesRequest()) + 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 = accountissue.ListAccountIssuesResponse.to_json(accountissue.ListAccountIssuesResponse()) + req.return_value.content = return_value + + request = accountissue.ListAccountIssuesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accountissue.ListAccountIssuesResponse() + post_with_metadata.return_value = accountissue.ListAccountIssuesResponse(), metadata + + client.list_account_issues(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountIssueServiceClient( + 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_account_issues_empty_call_rest(): + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_issues), + '__call__') as call: + client.list_account_issues(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accountissue.ListAccountIssuesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountIssueServiceGrpcTransport, + ) + +def test_account_issue_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountIssueServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_account_issue_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountIssueServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_account_issues', + ) + 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_account_issue_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_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountIssueServiceTransport( + 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_account_issue_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_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountIssueServiceTransport() + adc.assert_called_once() + + +def test_account_issue_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) + AccountIssueServiceClient() + 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.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + ], +) +def test_account_issue_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.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + transports.AccountIssueServiceRestTransport, + ], +) +def test_account_issue_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.AccountIssueServiceGrpcTransport, grpc_helpers), + (transports.AccountIssueServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +def test_account_issue_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_account_issue_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.AccountIssueServiceRestTransport ( + 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_account_issue_service_host_no_port(transport_name): + client = AccountIssueServiceClient( + 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_account_issue_service_host_with_port(transport_name): + client = AccountIssueServiceClient( + 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_account_issue_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountIssueServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountIssueServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_account_issues._session + session2 = client2.transport.list_account_issues._session + assert session1 != session2 +def test_account_issue_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountIssueServiceGrpcTransport( + 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_account_issue_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountIssueServiceGrpcAsyncIOTransport( + 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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +def test_account_issue_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AccountIssueServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AccountIssueServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_account_path(path) + assert expected == actual + +def test_account_issue_path(): + account = "whelk" + issue = "octopus" + expected = "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) + actual = AccountIssueServiceClient.account_issue_path(account, issue) + assert expected == actual + + +def test_parse_account_issue_path(): + expected = { + "account": "oyster", + "issue": "nudibranch", + } + path = AccountIssueServiceClient.account_issue_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_account_issue_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountIssueServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = AccountIssueServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountIssueServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = AccountIssueServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountIssueServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = AccountIssueServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = AccountIssueServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = AccountIssueServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = AccountIssueServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountIssueServiceClient.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.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountIssueServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountIssueServiceClient.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 = AccountIssueServiceClient( + 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 = AccountIssueServiceAsyncClient( + 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 = AccountIssueServiceClient( + 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 = AccountIssueServiceClient( + 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", [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport), + (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py new file mode 100644 index 000000000000..2cbf312aa0d8 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py @@ -0,0 +1,3803 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.account_tax_service import AccountTaxServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.account_tax_service import AccountTaxServiceClient +from google.shopping.merchant_accounts_v1beta.services.account_tax_service import pagers +from google.shopping.merchant_accounts_v1beta.services.account_tax_service import transports +from google.shopping.merchant_accounts_v1beta.types import account_tax +from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax +from google.shopping.merchant_accounts_v1beta.types import tax_rule +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 AccountTaxServiceClient._get_default_mtls_endpoint(None) is None + assert AccountTaxServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountTaxServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountTaxServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountTaxServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountTaxServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountTaxServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountTaxServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountTaxServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountTaxServiceClient._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 AccountTaxServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountTaxServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountTaxServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountTaxServiceClient._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 AccountTaxServiceClient._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 AccountTaxServiceClient._get_client_cert_source(None, False) is None + assert AccountTaxServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountTaxServiceClient._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 AccountTaxServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountTaxServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) +@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountTaxServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountTaxServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountTaxServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountTaxServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountTaxServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountTaxServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountTaxServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountTaxServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountTaxServiceClient._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 AccountTaxServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountTaxServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountTaxServiceClient._get_universe_domain(None, None) == AccountTaxServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountTaxServiceClient._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 = AccountTaxServiceClient(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 = AccountTaxServiceClient(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", [ + (AccountTaxServiceClient, "grpc"), + (AccountTaxServiceAsyncClient, "grpc_asyncio"), + (AccountTaxServiceClient, "rest"), +]) +def test_account_tax_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.AccountTaxServiceGrpcTransport, "grpc"), + (transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountTaxServiceRestTransport, "rest"), +]) +def test_account_tax_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", [ + (AccountTaxServiceClient, "grpc"), + (AccountTaxServiceAsyncClient, "grpc_asyncio"), + (AccountTaxServiceClient, "rest"), +]) +def test_account_tax_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_account_tax_service_client_get_transport_class(): + transport = AccountTaxServiceClient.get_transport_class() + available_transports = [ + transports.AccountTaxServiceGrpcTransport, + transports.AccountTaxServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountTaxServiceClient.get_transport_class("grpc") + assert transport == transports.AccountTaxServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc"), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) +@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) +def test_account_tax_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(AccountTaxServiceClient, '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(AccountTaxServiceClient, '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", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", "true"), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", "false"), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest", "true"), + (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) +@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_account_tax_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", [ + AccountTaxServiceClient, AccountTaxServiceAsyncClient +]) +@mock.patch.object(AccountTaxServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountTaxServiceClient)) +@mock.patch.object(AccountTaxServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountTaxServiceAsyncClient)) +def test_account_tax_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", [ + AccountTaxServiceClient, AccountTaxServiceAsyncClient +]) +@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) +@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) +def test_account_tax_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountTaxServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountTaxServiceClient._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", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc"), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest"), +]) +def test_account_tax_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", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", grpc_helpers), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest", None), +]) +def test_account_tax_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_account_tax_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountTaxServiceClient( + 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", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", grpc_helpers), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_account_tax_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", [ + account_tax.GetAccountTaxRequest, + dict, +]) +def test_get_account_tax(request_type, transport: str = 'grpc'): + client = AccountTaxServiceClient( + 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.get_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = account_tax.AccountTax( + name='name_value', + account=749, + ) + response = client.get_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = account_tax.GetAccountTaxRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, account_tax.AccountTax) + assert response.name == 'name_value' + assert response.account == 749 + + +def test_get_account_tax_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 = AccountTaxServiceClient( + 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 = account_tax.GetAccountTaxRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account_tax(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == account_tax.GetAccountTaxRequest( + name='name_value', + ) + +def test_get_account_tax_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 = AccountTaxServiceClient( + 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.get_account_tax in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account_tax] = mock_rpc + request = {} + client.get_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_tax(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_get_account_tax_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 = AccountTaxServiceAsyncClient( + 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.get_account_tax in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_account_tax] = mock_rpc + + request = {} + await client.get_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_account_tax(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_get_account_tax_async(transport: str = 'grpc_asyncio', request_type=account_tax.GetAccountTaxRequest): + client = AccountTaxServiceAsyncClient( + 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.get_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax( + name='name_value', + account=749, + )) + response = await client.get_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = account_tax.GetAccountTaxRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, account_tax.AccountTax) + assert response.name == 'name_value' + assert response.account == 749 + + +@pytest.mark.asyncio +async def test_get_account_tax_async_from_dict(): + await test_get_account_tax_async(request_type=dict) + +def test_get_account_tax_field_headers(): + client = AccountTaxServiceClient( + 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 = account_tax.GetAccountTaxRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + call.return_value = account_tax.AccountTax() + client.get_account_tax(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_get_account_tax_field_headers_async(): + client = AccountTaxServiceAsyncClient( + 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 = account_tax.GetAccountTaxRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax()) + await client.get_account_tax(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_get_account_tax_flattened(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = account_tax.AccountTax() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account_tax( + 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_get_account_tax_flattened_error(): + client = AccountTaxServiceClient( + 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.get_account_tax( + account_tax.GetAccountTaxRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_tax_flattened_async(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = account_tax.AccountTax() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account_tax( + 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_get_account_tax_flattened_error_async(): + client = AccountTaxServiceAsyncClient( + 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.get_account_tax( + account_tax.GetAccountTaxRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + account_tax.ListAccountTaxRequest, + dict, +]) +def test_list_account_tax(request_type, transport: str = 'grpc'): + client = AccountTaxServiceClient( + 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_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = account_tax.ListAccountTaxResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = account_tax.ListAccountTaxRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountTaxPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_tax_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 = AccountTaxServiceClient( + 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 = account_tax.ListAccountTaxRequest( + 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_account_tax), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_tax(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == account_tax.ListAccountTaxRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_account_tax_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 = AccountTaxServiceClient( + 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_account_tax in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_tax] = mock_rpc + request = {} + client.list_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_tax(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_account_tax_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 = AccountTaxServiceAsyncClient( + 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_account_tax 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_account_tax] = mock_rpc + + request = {} + await client.list_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_account_tax(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_account_tax_async(transport: str = 'grpc_asyncio', request_type=account_tax.ListAccountTaxRequest): + client = AccountTaxServiceAsyncClient( + 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_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = account_tax.ListAccountTaxRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountTaxAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_tax_async_from_dict(): + await test_list_account_tax_async(request_type=dict) + +def test_list_account_tax_field_headers(): + client = AccountTaxServiceClient( + 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 = account_tax.ListAccountTaxRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + call.return_value = account_tax.ListAccountTaxResponse() + client.list_account_tax(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_account_tax_field_headers_async(): + client = AccountTaxServiceAsyncClient( + 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 = account_tax.ListAccountTaxRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse()) + await client.list_account_tax(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_account_tax_flattened(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = account_tax.ListAccountTaxResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_account_tax( + 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_account_tax_flattened_error(): + client = AccountTaxServiceClient( + 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_account_tax( + account_tax.ListAccountTaxRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_account_tax_flattened_async(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = account_tax.ListAccountTaxResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_account_tax( + 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_account_tax_flattened_error_async(): + client = AccountTaxServiceAsyncClient( + 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_account_tax( + account_tax.ListAccountTaxRequest(), + parent='parent_value', + ) + + +def test_list_account_tax_pager(transport_name: str = "grpc"): + client = AccountTaxServiceClient( + 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_account_tax), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + next_page_token='abc', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[], + next_page_token='def', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + ], + next_page_token='ghi', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_account_tax(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, account_tax.AccountTax) + for i in results) +def test_list_account_tax_pages(transport_name: str = "grpc"): + client = AccountTaxServiceClient( + 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_account_tax), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + next_page_token='abc', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[], + next_page_token='def', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + ], + next_page_token='ghi', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_tax(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_account_tax_async_pager(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + next_page_token='abc', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[], + next_page_token='def', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + ], + next_page_token='ghi', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_tax(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, account_tax.AccountTax) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_tax_async_pages(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + next_page_token='abc', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[], + next_page_token='def', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + ], + next_page_token='ghi', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + ), + 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_account_tax(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", [ + gsma_account_tax.UpdateAccountTaxRequest, + dict, +]) +def test_update_account_tax(request_type, transport: str = 'grpc'): + client = AccountTaxServiceClient( + 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.update_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_account_tax.AccountTax( + name='name_value', + account=749, + ) + response = client.update_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_account_tax.UpdateAccountTaxRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_account_tax.AccountTax) + assert response.name == 'name_value' + assert response.account == 749 + + +def test_update_account_tax_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 = AccountTaxServiceClient( + 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 = gsma_account_tax.UpdateAccountTaxRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account_tax(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_account_tax.UpdateAccountTaxRequest( + ) + +def test_update_account_tax_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 = AccountTaxServiceClient( + 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.update_account_tax in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account_tax] = mock_rpc + request = {} + client.update_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account_tax(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_update_account_tax_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 = AccountTaxServiceAsyncClient( + 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.update_account_tax in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_account_tax] = mock_rpc + + request = {} + await client.update_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_account_tax(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_update_account_tax_async(transport: str = 'grpc_asyncio', request_type=gsma_account_tax.UpdateAccountTaxRequest): + client = AccountTaxServiceAsyncClient( + 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.update_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax( + name='name_value', + account=749, + )) + response = await client.update_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_account_tax.UpdateAccountTaxRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_account_tax.AccountTax) + assert response.name == 'name_value' + assert response.account == 749 + + +@pytest.mark.asyncio +async def test_update_account_tax_async_from_dict(): + await test_update_account_tax_async(request_type=dict) + +def test_update_account_tax_field_headers(): + client = AccountTaxServiceClient( + 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 = gsma_account_tax.UpdateAccountTaxRequest() + + request.account_tax.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + call.return_value = gsma_account_tax.AccountTax() + client.update_account_tax(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', + 'account_tax.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_account_tax_field_headers_async(): + client = AccountTaxServiceAsyncClient( + 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 = gsma_account_tax.UpdateAccountTaxRequest() + + request.account_tax.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax()) + await client.update_account_tax(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', + 'account_tax.name=name_value', + ) in kw['metadata'] + + +def test_update_account_tax_flattened(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_account_tax.AccountTax() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_account_tax( + account_tax=gsma_account_tax.AccountTax(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account_tax + mock_val = gsma_account_tax.AccountTax(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_account_tax_flattened_error(): + client = AccountTaxServiceClient( + 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.update_account_tax( + gsma_account_tax.UpdateAccountTaxRequest(), + account_tax=gsma_account_tax.AccountTax(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_account_tax_flattened_async(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_account_tax.AccountTax() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account_tax( + account_tax=gsma_account_tax.AccountTax(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account_tax + mock_val = gsma_account_tax.AccountTax(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_account_tax_flattened_error_async(): + client = AccountTaxServiceAsyncClient( + 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.update_account_tax( + gsma_account_tax.UpdateAccountTaxRequest(), + account_tax=gsma_account_tax.AccountTax(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_account_tax_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 = AccountTaxServiceClient( + 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.get_account_tax in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account_tax] = mock_rpc + + request = {} + client.get_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_tax(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_get_account_tax_rest_required_fields(request_type=account_tax.GetAccountTaxRequest): + transport_class = transports.AccountTaxServiceRestTransport + + 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()).get_account_tax._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_tax._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 = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = account_tax.AccountTax() + # 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 = account_tax.AccountTax.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.get_account_tax(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_tax_rest_unset_required_fields(): + transport = transports.AccountTaxServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account_tax._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_account_tax_rest_flattened(): + client = AccountTaxServiceClient( + 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 = account_tax.AccountTax() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/accounttax/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = account_tax.AccountTax.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.get_account_tax(**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/accounts/v1beta/{name=accounts/*/accounttax/*}" % client.transport._host, args[1]) + + +def test_get_account_tax_rest_flattened_error(transport: str = 'rest'): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_account_tax( + account_tax.GetAccountTaxRequest(), + name='name_value', + ) + + +def test_list_account_tax_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 = AccountTaxServiceClient( + 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_account_tax in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account_tax] = mock_rpc + + request = {} + client.list_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_tax(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_account_tax_rest_required_fields(request_type=account_tax.ListAccountTaxRequest): + transport_class = transports.AccountTaxServiceRestTransport + + 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_account_tax._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_account_tax._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 = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = account_tax.ListAccountTaxResponse() + # 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 = account_tax.ListAccountTaxResponse.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_account_tax(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_account_tax_rest_unset_required_fields(): + transport = transports.AccountTaxServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_account_tax._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_account_tax_rest_flattened(): + client = AccountTaxServiceClient( + 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 = account_tax.ListAccountTaxResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = account_tax.ListAccountTaxResponse.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_account_tax(**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/accounts/v1beta/{parent=accounts/*}/accounttax" % client.transport._host, args[1]) + + +def test_list_account_tax_rest_flattened_error(transport: str = 'rest'): + client = AccountTaxServiceClient( + 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_account_tax( + account_tax.ListAccountTaxRequest(), + parent='parent_value', + ) + + +def test_list_account_tax_rest_pager(transport: str = 'rest'): + client = AccountTaxServiceClient( + 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 = ( + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + next_page_token='abc', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[], + next_page_token='def', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + ], + next_page_token='ghi', + ), + account_tax.ListAccountTaxResponse( + account_taxes=[ + account_tax.AccountTax(), + account_tax.AccountTax(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(account_tax.ListAccountTaxResponse.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'} + + pager = client.list_account_tax(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, account_tax.AccountTax) + for i in results) + + pages = list(client.list_account_tax(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_update_account_tax_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 = AccountTaxServiceClient( + 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.update_account_tax in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account_tax] = mock_rpc + + request = {} + client.update_account_tax(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account_tax(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_update_account_tax_rest_required_fields(request_type=gsma_account_tax.UpdateAccountTaxRequest): + transport_class = transports.AccountTaxServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_tax._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_tax._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_account_tax.AccountTax() + # 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': "patch", + '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 = gsma_account_tax.AccountTax.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.update_account_tax(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_account_tax_rest_unset_required_fields(): + transport = transports.AccountTaxServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_account_tax._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("accountTax", ))) + + +def test_update_account_tax_rest_flattened(): + client = AccountTaxServiceClient( + 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 = gsma_account_tax.AccountTax() + + # get arguments that satisfy an http rule for this method + sample_request = {'account_tax': {'name': 'accounts/sample1/accounttax/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + account_tax=gsma_account_tax.AccountTax(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_account_tax.AccountTax.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.update_account_tax(**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/accounts/v1beta/{account_tax.name=accounts/*/accounttax/*}" % client.transport._host, args[1]) + + +def test_update_account_tax_rest_flattened_error(transport: str = 'rest'): + client = AccountTaxServiceClient( + 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.update_account_tax( + gsma_account_tax.UpdateAccountTaxRequest(), + account_tax=gsma_account_tax.AccountTax(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountTaxServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountTaxServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountTaxServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountTaxServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountTaxServiceClient( + 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 = AccountTaxServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountTaxServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountTaxServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountTaxServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountTaxServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountTaxServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountTaxServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountTaxServiceGrpcTransport, + transports.AccountTaxServiceGrpcAsyncIOTransport, + transports.AccountTaxServiceRestTransport, +]) +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 = AccountTaxServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountTaxServiceClient( + 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_get_account_tax_empty_call_grpc(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + call.return_value = account_tax.AccountTax() + client.get_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = account_tax.GetAccountTaxRequest() + + 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_list_account_tax_empty_call_grpc(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + call.return_value = account_tax.ListAccountTaxResponse() + client.list_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = account_tax.ListAccountTaxRequest() + + 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_update_account_tax_empty_call_grpc(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + call.return_value = gsma_account_tax.AccountTax() + client.update_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_account_tax.UpdateAccountTaxRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountTaxServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountTaxServiceAsyncClient( + 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_get_account_tax_empty_call_grpc_asyncio(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax( + name='name_value', + account=749, + )) + await client.get_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = account_tax.GetAccountTaxRequest() + + 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_list_account_tax_empty_call_grpc_asyncio(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse( + next_page_token='next_page_token_value', + )) + await client.list_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = account_tax.ListAccountTaxRequest() + + 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_update_account_tax_empty_call_grpc_asyncio(): + client = AccountTaxServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax( + name='name_value', + account=749, + )) + await client.update_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_account_tax.UpdateAccountTaxRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountTaxServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_account_tax_rest_bad_request(request_type=account_tax.GetAccountTaxRequest): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/accounttax/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.get_account_tax(request) + + +@pytest.mark.parametrize("request_type", [ + account_tax.GetAccountTaxRequest, + dict, +]) +def test_get_account_tax_rest_call_success(request_type): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/accounttax/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 = account_tax.AccountTax( + name='name_value', + account=749, + ) + + # 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 = account_tax.AccountTax.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.get_account_tax(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, account_tax.AccountTax) + assert response.name == 'name_value' + assert response.account == 749 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_tax_rest_interceptors(null_interceptor): + transport = transports.AccountTaxServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountTaxServiceRestInterceptor(), + ) + client = AccountTaxServiceClient(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.AccountTaxServiceRestInterceptor, "post_get_account_tax") as post, \ + mock.patch.object(transports.AccountTaxServiceRestInterceptor, "post_get_account_tax_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountTaxServiceRestInterceptor, "pre_get_account_tax") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = account_tax.GetAccountTaxRequest.pb(account_tax.GetAccountTaxRequest()) + 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 = account_tax.AccountTax.to_json(account_tax.AccountTax()) + req.return_value.content = return_value + + request = account_tax.GetAccountTaxRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = account_tax.AccountTax() + post_with_metadata.return_value = account_tax.AccountTax(), metadata + + client.get_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_account_tax_rest_bad_request(request_type=account_tax.ListAccountTaxRequest): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_account_tax(request) + + +@pytest.mark.parametrize("request_type", [ + account_tax.ListAccountTaxRequest, + dict, +]) +def test_list_account_tax_rest_call_success(request_type): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = account_tax.ListAccountTaxResponse( + 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 = account_tax.ListAccountTaxResponse.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_account_tax(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountTaxPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_tax_rest_interceptors(null_interceptor): + transport = transports.AccountTaxServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountTaxServiceRestInterceptor(), + ) + client = AccountTaxServiceClient(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.AccountTaxServiceRestInterceptor, "post_list_account_tax") as post, \ + mock.patch.object(transports.AccountTaxServiceRestInterceptor, "post_list_account_tax_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountTaxServiceRestInterceptor, "pre_list_account_tax") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = account_tax.ListAccountTaxRequest.pb(account_tax.ListAccountTaxRequest()) + 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 = account_tax.ListAccountTaxResponse.to_json(account_tax.ListAccountTaxResponse()) + req.return_value.content = return_value + + request = account_tax.ListAccountTaxRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = account_tax.ListAccountTaxResponse() + post_with_metadata.return_value = account_tax.ListAccountTaxResponse(), metadata + + client.list_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_account_tax_rest_bad_request(request_type=gsma_account_tax.UpdateAccountTaxRequest): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'account_tax': {'name': 'accounts/sample1/accounttax/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.update_account_tax(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_account_tax.UpdateAccountTaxRequest, + dict, +]) +def test_update_account_tax_rest_call_success(request_type): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'account_tax': {'name': 'accounts/sample1/accounttax/sample2'}} + request_init["account_tax"] = {'name': 'accounts/sample1/accounttax/sample2', 'account': 749, 'tax_rules': [{'location_id': 1157, 'post_code_range': {'start': 'start_value', 'end': 'end_value'}, 'use_google_rate': True, 'self_specified_rate_micros': 2732, 'region_code': 'region_code_value', 'shipping_taxed': True, 'effective_time_period': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}}]} + # 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 = gsma_account_tax.UpdateAccountTaxRequest.meta.fields["account_tax"] + + 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["account_tax"].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["account_tax"][field])): + del request_init["account_tax"][field][i][subfield] + else: + del request_init["account_tax"][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 = gsma_account_tax.AccountTax( + name='name_value', + account=749, + ) + + # 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 = gsma_account_tax.AccountTax.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.update_account_tax(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_account_tax.AccountTax) + assert response.name == 'name_value' + assert response.account == 749 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_tax_rest_interceptors(null_interceptor): + transport = transports.AccountTaxServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountTaxServiceRestInterceptor(), + ) + client = AccountTaxServiceClient(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.AccountTaxServiceRestInterceptor, "post_update_account_tax") as post, \ + mock.patch.object(transports.AccountTaxServiceRestInterceptor, "post_update_account_tax_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountTaxServiceRestInterceptor, "pre_update_account_tax") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_account_tax.UpdateAccountTaxRequest.pb(gsma_account_tax.UpdateAccountTaxRequest()) + 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 = gsma_account_tax.AccountTax.to_json(gsma_account_tax.AccountTax()) + req.return_value.content = return_value + + request = gsma_account_tax.UpdateAccountTaxRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_account_tax.AccountTax() + post_with_metadata.return_value = gsma_account_tax.AccountTax(), metadata + + client.update_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountTaxServiceClient( + 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_get_account_tax_empty_call_rest(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_tax), + '__call__') as call: + client.get_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = account_tax.GetAccountTaxRequest() + + 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_list_account_tax_empty_call_rest(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_tax), + '__call__') as call: + client.list_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = account_tax.ListAccountTaxRequest() + + 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_update_account_tax_empty_call_rest(): + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_tax), + '__call__') as call: + client.update_account_tax(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_account_tax.UpdateAccountTaxRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountTaxServiceGrpcTransport, + ) + +def test_account_tax_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountTaxServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_account_tax_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountTaxServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account_tax', + 'list_account_tax', + 'update_account_tax', + ) + 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_account_tax_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_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountTaxServiceTransport( + 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_account_tax_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_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountTaxServiceTransport() + adc.assert_called_once() + + +def test_account_tax_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) + AccountTaxServiceClient() + 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.AccountTaxServiceGrpcTransport, + transports.AccountTaxServiceGrpcAsyncIOTransport, + ], +) +def test_account_tax_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.AccountTaxServiceGrpcTransport, + transports.AccountTaxServiceGrpcAsyncIOTransport, + transports.AccountTaxServiceRestTransport, + ], +) +def test_account_tax_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.AccountTaxServiceGrpcTransport, grpc_helpers), + (transports.AccountTaxServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_account_tax_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.AccountTaxServiceGrpcTransport, transports.AccountTaxServiceGrpcAsyncIOTransport]) +def test_account_tax_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_account_tax_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.AccountTaxServiceRestTransport ( + 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_account_tax_service_host_no_port(transport_name): + client = AccountTaxServiceClient( + 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_account_tax_service_host_with_port(transport_name): + client = AccountTaxServiceClient( + 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_account_tax_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountTaxServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountTaxServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account_tax._session + session2 = client2.transport.get_account_tax._session + assert session1 != session2 + session1 = client1.transport.list_account_tax._session + session2 = client2.transport.list_account_tax._session + assert session1 != session2 + session1 = client1.transport.update_account_tax._session + session2 = client2.transport.update_account_tax._session + assert session1 != session2 +def test_account_tax_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountTaxServiceGrpcTransport( + 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_account_tax_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountTaxServiceGrpcAsyncIOTransport( + 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.AccountTaxServiceGrpcTransport, transports.AccountTaxServiceGrpcAsyncIOTransport]) +def test_account_tax_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.AccountTaxServiceGrpcTransport, transports.AccountTaxServiceGrpcAsyncIOTransport]) +def test_account_tax_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_account_tax_path(): + account = "squid" + tax = "clam" + expected = "accounts/{account}/accounttax/{tax}".format(account=account, tax=tax, ) + actual = AccountTaxServiceClient.account_tax_path(account, tax) + assert expected == actual + + +def test_parse_account_tax_path(): + expected = { + "account": "whelk", + "tax": "octopus", + } + path = AccountTaxServiceClient.account_tax_path(**expected) + + # Check that the path construction is reversible. + actual = AccountTaxServiceClient.parse_account_tax_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountTaxServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = AccountTaxServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountTaxServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountTaxServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = AccountTaxServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountTaxServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountTaxServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = AccountTaxServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountTaxServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = AccountTaxServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = AccountTaxServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountTaxServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AccountTaxServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = AccountTaxServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountTaxServiceClient.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.AccountTaxServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountTaxServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountTaxServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountTaxServiceClient.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 = AccountTaxServiceClient( + 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 = AccountTaxServiceAsyncClient( + 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 = AccountTaxServiceClient( + 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 = AccountTaxServiceClient( + 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", [ + (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport), + (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py new file mode 100644 index 000000000000..add2c943db1c --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py @@ -0,0 +1,5650 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.accounts_service import AccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.accounts_service import AccountsServiceClient +from google.shopping.merchant_accounts_v1beta.services.accounts_service import pagers +from google.shopping.merchant_accounts_v1beta.services.accounts_service import transports +from google.shopping.merchant_accounts_v1beta.types import accessright +from google.shopping.merchant_accounts_v1beta.types import accounts +from google.shopping.merchant_accounts_v1beta.types import accountservices +from google.shopping.merchant_accounts_v1beta.types import user +from google.type import datetime_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 AccountsServiceClient._get_default_mtls_endpoint(None) is None + assert AccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AccountsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AccountsServiceClient._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 AccountsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AccountsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountsServiceClient._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 AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, False) is None + assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AccountsServiceClient._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 AccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AccountsServiceClient._get_universe_domain(None, None) == AccountsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AccountsServiceClient._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 = AccountsServiceClient(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 = AccountsServiceClient(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", [ + (AccountsServiceClient, "grpc"), + (AccountsServiceAsyncClient, "grpc_asyncio"), + (AccountsServiceClient, "rest"), +]) +def test_accounts_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.AccountsServiceGrpcTransport, "grpc"), + (transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountsServiceRestTransport, "rest"), +]) +def test_accounts_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", [ + (AccountsServiceClient, "grpc"), + (AccountsServiceAsyncClient, "grpc_asyncio"), + (AccountsServiceClient, "rest"), +]) +def test_accounts_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_accounts_service_client_get_transport_class(): + transport = AccountsServiceClient.get_transport_class() + available_transports = [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceRestTransport, + ] + assert transport in available_transports + + transport = AccountsServiceClient.get_transport_class("grpc") + assert transport == transports.AccountsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), +]) +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +def test_accounts_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(AccountsServiceClient, '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(AccountsServiceClient, '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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "true"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "false"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "true"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_accounts_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", [ + AccountsServiceClient, AccountsServiceAsyncClient +]) +@mock.patch.object(AccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceAsyncClient)) +def test_accounts_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", [ + AccountsServiceClient, AccountsServiceAsyncClient +]) +@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) +@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +def test_accounts_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AccountsServiceClient._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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), +]) +def test_accounts_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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", None), +]) +def test_accounts_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_accounts_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.accounts_service.transports.AccountsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AccountsServiceClient( + 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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_accounts_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", [ + accounts.GetAccountRequest, + dict, +]) +def test_get_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + ) + response = client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +def test_get_account_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 = AccountsServiceClient( + 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 = accounts.GetAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.GetAccountRequest( + name='name_value', + ) + +def test_get_account_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 = AccountsServiceClient( + 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.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(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_get_account_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 = AccountsServiceAsyncClient( + 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.get_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_account] = mock_rpc + + request = {} + await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_account(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_get_account_async(transport: str = 'grpc_asyncio', request_type=accounts.GetAccountRequest): + client = AccountsServiceAsyncClient( + 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.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + response = await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_get_account_async_from_dict(): + await test_get_account_async(request_type=dict) + +def test_get_account_field_headers(): + client = AccountsServiceClient( + 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 = accounts.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = accounts.Account() + client.get_account(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_get_account_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + await client.get_account(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_get_account_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account( + 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_get_account_flattened_error(): + client = AccountsServiceClient( + 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.get_account( + accounts.GetAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account( + 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_get_account_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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.get_account( + accounts.GetAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accounts.CreateAndConfigureAccountRequest, + dict, +]) +def test_create_and_configure_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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.create_and_configure_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + ) + response = client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.CreateAndConfigureAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +def test_create_and_configure_account_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 = AccountsServiceClient( + 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 = accounts.CreateAndConfigureAccountRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_and_configure_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.CreateAndConfigureAccountRequest( + ) + +def test_create_and_configure_account_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 = AccountsServiceClient( + 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.create_and_configure_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc + request = {} + client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_and_configure_account(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_create_and_configure_account_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 = AccountsServiceAsyncClient( + 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.create_and_configure_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_and_configure_account] = mock_rpc + + request = {} + await client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_and_configure_account(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_create_and_configure_account_async(transport: str = 'grpc_asyncio', request_type=accounts.CreateAndConfigureAccountRequest): + client = AccountsServiceAsyncClient( + 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.create_and_configure_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + response = await client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.CreateAndConfigureAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_create_and_configure_account_async_from_dict(): + await test_create_and_configure_account_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + accounts.DeleteAccountRequest, + dict, +]) +def test_delete_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.DeleteAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_account_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 = AccountsServiceClient( + 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 = accounts.DeleteAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.DeleteAccountRequest( + name='name_value', + ) + +def test_delete_account_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 = AccountsServiceClient( + 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_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account] = mock_rpc + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(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_account_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 = AccountsServiceAsyncClient( + 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_account 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_account] = mock_rpc + + request = {} + await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_account(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_account_async(transport: str = 'grpc_asyncio', request_type=accounts.DeleteAccountRequest): + client = AccountsServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.DeleteAccountRequest() + 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_account_async_from_dict(): + await test_delete_account_async(request_type=dict) + +def test_delete_account_field_headers(): + client = AccountsServiceClient( + 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 = accounts.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = None + client.delete_account(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_account_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_account(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_account_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error(): + client = AccountsServiceClient( + 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_account( + accounts.DeleteAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_account_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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_account( + accounts.DeleteAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + accounts.UpdateAccountRequest, + dict, +]) +def test_update_account(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + ) + response = client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +def test_update_account_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 = AccountsServiceClient( + 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 = accounts.UpdateAccountRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.UpdateAccountRequest( + ) + +def test_update_account_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 = AccountsServiceClient( + 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.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(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_update_account_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 = AccountsServiceAsyncClient( + 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.update_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_account] = mock_rpc + + request = {} + await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_account(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_update_account_async(transport: str = 'grpc_asyncio', request_type=accounts.UpdateAccountRequest): + client = AccountsServiceAsyncClient( + 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.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + response = await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.asyncio +async def test_update_account_async_from_dict(): + await test_update_account_async(request_type=dict) + +def test_update_account_field_headers(): + client = AccountsServiceClient( + 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 = accounts.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = accounts.Account() + client.update_account(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', + 'account.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_account_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + await client.update_account(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', + 'account.name=name_value', + ) in kw['metadata'] + + +def test_update_account_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_account( + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account + mock_val = accounts.Account(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_account_flattened_error(): + client = AccountsServiceClient( + 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.update_account( + accounts.UpdateAccountRequest(), + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_account_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account( + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account + mock_val = accounts.Account(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_account_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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.update_account( + accounts.UpdateAccountRequest(), + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + accounts.ListAccountsRequest, + dict, +]) +def test_list_accounts(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_accounts_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 = AccountsServiceClient( + 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 = accounts.ListAccountsRequest( + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.ListAccountsRequest( + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_accounts_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 = AccountsServiceClient( + 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_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_accounts] = mock_rpc + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(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_accounts_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 = AccountsServiceAsyncClient( + 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_accounts 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_accounts] = mock_rpc + + request = {} + await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_accounts(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_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListAccountsRequest): + client = AccountsServiceAsyncClient( + 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_accounts_async_from_dict(): + await test_list_accounts_async(request_type=dict) + + +def test_list_accounts_pager(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_accounts(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, accounts.Account) + for i in results) +def test_list_accounts_pages(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + pages = list(client.list_accounts(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_accounts_async_pager(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_accounts(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, accounts.Account) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_accounts_async_pages(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + 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_accounts(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", [ + accounts.ListSubAccountsRequest, + dict, +]) +def test_list_sub_accounts(request_type, transport: str = 'grpc'): + client = AccountsServiceClient( + 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_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListSubAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = accounts.ListSubAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sub_accounts_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 = AccountsServiceClient( + 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 = accounts.ListSubAccountsRequest( + provider='provider_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_sub_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sub_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == accounts.ListSubAccountsRequest( + provider='provider_value', + page_token='page_token_value', + ) + +def test_list_sub_accounts_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 = AccountsServiceClient( + 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_sub_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_sub_accounts] = mock_rpc + request = {} + client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sub_accounts(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_sub_accounts_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 = AccountsServiceAsyncClient( + 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_sub_accounts 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_sub_accounts] = mock_rpc + + request = {} + await client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_sub_accounts(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_sub_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListSubAccountsRequest): + client = AccountsServiceAsyncClient( + 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_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = accounts.ListSubAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sub_accounts_async_from_dict(): + await test_list_sub_accounts_async(request_type=dict) + +def test_list_sub_accounts_field_headers(): + client = AccountsServiceClient( + 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 = accounts.ListSubAccountsRequest() + + request.provider = 'provider_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + call.return_value = accounts.ListSubAccountsResponse() + client.list_sub_accounts(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', + 'provider=provider_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_sub_accounts_field_headers_async(): + client = AccountsServiceAsyncClient( + 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 = accounts.ListSubAccountsRequest() + + request.provider = 'provider_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) + await client.list_sub_accounts(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', + 'provider=provider_value', + ) in kw['metadata'] + + +def test_list_sub_accounts_flattened(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListSubAccountsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sub_accounts( + provider='provider_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].provider + mock_val = 'provider_value' + assert arg == mock_val + + +def test_list_sub_accounts_flattened_error(): + client = AccountsServiceClient( + 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_sub_accounts( + accounts.ListSubAccountsRequest(), + provider='provider_value', + ) + +@pytest.mark.asyncio +async def test_list_sub_accounts_flattened_async(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = accounts.ListSubAccountsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sub_accounts( + provider='provider_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].provider + mock_val = 'provider_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_sub_accounts_flattened_error_async(): + client = AccountsServiceAsyncClient( + 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_sub_accounts( + accounts.ListSubAccountsRequest(), + provider='provider_value', + ) + + +def test_list_sub_accounts_pager(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_sub_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('provider', ''), + )), + ) + pager = client.list_sub_accounts(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, accounts.Account) + for i in results) +def test_list_sub_accounts_pages(transport_name: str = "grpc"): + client = AccountsServiceClient( + 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_sub_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sub_accounts(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_sub_accounts_async_pager(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sub_accounts(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, accounts.Account) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sub_accounts_async_pages(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + 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_sub_accounts(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_account_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 = AccountsServiceClient( + 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.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(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_get_account_rest_required_fields(request_type=accounts.GetAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + 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()).get_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account._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 = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.Account() + # 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 = accounts.Account.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.get_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_account_rest_flattened(): + client = AccountsServiceClient( + 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 = accounts.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1'} + + # 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 + # Convert return value to protobuf type + return_value = accounts.Account.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.get_account(**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/accounts/v1beta/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_get_account_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_account( + accounts.GetAccountRequest(), + name='name_value', + ) + + +def test_create_and_configure_account_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 = AccountsServiceClient( + 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.create_and_configure_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc + + request = {} + client.create_and_configure_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_and_configure_account(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_create_and_configure_account_rest_required_fields(request_type=accounts.CreateAndConfigureAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.Account() + # 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 = accounts.Account.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.create_and_configure_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_and_configure_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_and_configure_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("account", "service", ))) + + +def test_delete_account_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 = AccountsServiceClient( + 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_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_account] = mock_rpc + + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(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_account_rest_required_fields(request_type=accounts.DeleteAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + 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_account._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_account._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + 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 = AccountsServiceClient( + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +def test_delete_account_rest_flattened(): + client = AccountsServiceClient( + 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'} + + # 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_account(**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/accounts/v1beta/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_delete_account_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + 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_account( + accounts.DeleteAccountRequest(), + name='name_value', + ) + + +def test_update_account_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 = AccountsServiceClient( + 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.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(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_update_account_rest_required_fields(request_type=accounts.UpdateAccountRequest): + transport_class = transports.AccountsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.Account() + # 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': "patch", + '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 = accounts.Account.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.update_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_account_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("account", "updateMask", ))) + + +def test_update_account_rest_flattened(): + client = AccountsServiceClient( + 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 = accounts.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'account': {'name': 'accounts/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = accounts.Account.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.update_account(**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/accounts/v1beta/{account.name=accounts/*}" % client.transport._host, args[1]) + + +def test_update_account_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + 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.update_account( + accounts.UpdateAccountRequest(), + account=accounts.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_accounts_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 = AccountsServiceClient( + 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_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_accounts] = mock_rpc + + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(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_accounts_rest_pager(transport: str = 'rest'): + client = AccountsServiceClient( + 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 = ( + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accounts.ListAccountsResponse.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 = {} + + pager = client.list_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accounts.Account) + for i in results) + + pages = list(client.list_accounts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_sub_accounts_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 = AccountsServiceClient( + 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_sub_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_sub_accounts] = mock_rpc + + request = {} + client.list_sub_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sub_accounts(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_sub_accounts_rest_required_fields(request_type=accounts.ListSubAccountsRequest): + transport_class = transports.AccountsServiceRestTransport + + request_init = {} + request_init["provider"] = "" + 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_sub_accounts._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["provider"] = 'provider_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_sub_accounts._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 "provider" in jsonified_request + assert jsonified_request["provider"] == 'provider_value' + + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = accounts.ListSubAccountsResponse() + # 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 = accounts.ListSubAccountsResponse.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_sub_accounts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sub_accounts_rest_unset_required_fields(): + transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sub_accounts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("provider", ))) + + +def test_list_sub_accounts_rest_flattened(): + client = AccountsServiceClient( + 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 = accounts.ListSubAccountsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'provider': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + provider='provider_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 = accounts.ListSubAccountsResponse.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_sub_accounts(**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/accounts/v1beta/{provider=accounts/*}:listSubaccounts" % client.transport._host, args[1]) + + +def test_list_sub_accounts_rest_flattened_error(transport: str = 'rest'): + client = AccountsServiceClient( + 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_sub_accounts( + accounts.ListSubAccountsRequest(), + provider='provider_value', + ) + + +def test_list_sub_accounts_rest_pager(transport: str = 'rest'): + client = AccountsServiceClient( + 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 = ( + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + accounts.Account(), + ], + next_page_token='abc', + ), + accounts.ListSubAccountsResponse( + accounts=[], + next_page_token='def', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + ], + next_page_token='ghi', + ), + accounts.ListSubAccountsResponse( + accounts=[ + accounts.Account(), + accounts.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(accounts.ListSubAccountsResponse.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 = {'provider': 'accounts/sample1'} + + pager = client.list_sub_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, accounts.Account) + for i in results) + + pages = list(client.list_sub_accounts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AccountsServiceClient( + 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 = AccountsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AccountsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AccountsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AccountsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + transports.AccountsServiceRestTransport, +]) +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 = AccountsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AccountsServiceClient( + 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_get_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = accounts.Account() + client.get_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.GetAccountRequest() + + 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_create_and_configure_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + call.return_value = accounts.Account() + client.create_and_configure_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.CreateAndConfigureAccountRequest() + + 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_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = None + client.delete_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.DeleteAccountRequest() + + 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_update_account_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = accounts.Account() + client.update_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.UpdateAccountRequest() + + 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_list_accounts_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + call.return_value = accounts.ListAccountsResponse() + client.list_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListAccountsRequest() + + 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_list_sub_accounts_empty_call_grpc(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + call.return_value = accounts.ListSubAccountsResponse() + client.list_sub_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListSubAccountsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AccountsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AccountsServiceAsyncClient( + 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_get_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + await client.get_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.GetAccountRequest() + + 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_create_and_configure_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + await client.create_and_configure_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.CreateAndConfigureAccountRequest() + + 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_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.DeleteAccountRequest() + + 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_update_account_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_code_value', + )) + await client.update_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.UpdateAccountRequest() + + 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_list_accounts_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + await client.list_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListAccountsRequest() + + 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_list_sub_accounts_empty_call_grpc_asyncio(): + client = AccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( + next_page_token='next_page_token_value', + )) + await client.list_sub_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListSubAccountsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AccountsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_account_rest_bad_request(request_type=accounts.GetAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + 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.get_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.GetAccountRequest, + dict, +]) +def test_get_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_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 = accounts.Account.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.get_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_get_account") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_get_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_get_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.GetAccountRequest.pb(accounts.GetAccountRequest()) + 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 = accounts.Account.to_json(accounts.Account()) + req.return_value.content = return_value + + request = accounts.GetAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.Account() + post_with_metadata.return_value = accounts.Account(), metadata + + client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_and_configure_account_rest_bad_request(request_type=accounts.CreateAndConfigureAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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.create_and_configure_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.CreateAndConfigureAccountRequest, + dict, +]) +def test_create_and_configure_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_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 = accounts.Account.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.create_and_configure_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_and_configure_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_create_and_configure_account") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_create_and_configure_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_create_and_configure_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.CreateAndConfigureAccountRequest.pb(accounts.CreateAndConfigureAccountRequest()) + 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 = accounts.Account.to_json(accounts.Account()) + req.return_value.content = return_value + + request = accounts.CreateAndConfigureAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.Account() + post_with_metadata.return_value = accounts.Account(), metadata + + client.create_and_configure_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_account_rest_bad_request(request_type=accounts.DeleteAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + 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_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.DeleteAccountRequest, + dict, +]) +def test_delete_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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_account(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_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "pre_delete_account") as pre: + pre.assert_not_called() + pb_message = accounts.DeleteAccountRequest.pb(accounts.DeleteAccountRequest()) + 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 = accounts.DeleteAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_update_account_rest_bad_request(request_type=accounts.UpdateAccountRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/sample1'}} + 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.update_account(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.UpdateAccountRequest, + dict, +]) +def test_update_account_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/sample1'}} + request_init["account"] = {'name': 'accounts/sample1', 'account_id': 1049, 'account_name': 'account_name_value', 'adult_content': True, 'test_account': True, 'time_zone': {'id': 'id_value', 'version': 'version_value'}, 'language_code': 'language_code_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 = accounts.UpdateAccountRequest.meta.fields["account"] + + 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["account"].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["account"][field])): + del request_init["account"][field][i][subfield] + else: + del request_init["account"][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 = accounts.Account( + name='name_value', + account_id=1049, + account_name='account_name_value', + adult_content=True, + test_account=True, + language_code='language_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 = accounts.Account.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.update_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, accounts.Account) + assert response.name == 'name_value' + assert response.account_id == 1049 + assert response.account_name == 'account_name_value' + assert response.adult_content is True + assert response.test_account is True + assert response.language_code == 'language_code_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_update_account") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_update_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_update_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.UpdateAccountRequest.pb(accounts.UpdateAccountRequest()) + 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 = accounts.Account.to_json(accounts.Account()) + req.return_value.content = return_value + + request = accounts.UpdateAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.Account() + post_with_metadata.return_value = accounts.Account(), metadata + + client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_accounts_rest_bad_request(request_type=accounts.ListAccountsRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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_accounts(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.ListAccountsRequest, + dict, +]) +def test_list_accounts_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.ListAccountsResponse( + 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 = accounts.ListAccountsResponse.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_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_accounts_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_accounts") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_accounts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.ListAccountsRequest.pb(accounts.ListAccountsRequest()) + 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 = accounts.ListAccountsResponse.to_json(accounts.ListAccountsResponse()) + req.return_value.content = return_value + + request = accounts.ListAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.ListAccountsResponse() + post_with_metadata.return_value = accounts.ListAccountsResponse(), metadata + + client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_sub_accounts_rest_bad_request(request_type=accounts.ListSubAccountsRequest): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'provider': 'accounts/sample1'} + 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_sub_accounts(request) + + +@pytest.mark.parametrize("request_type", [ + accounts.ListSubAccountsRequest, + dict, +]) +def test_list_sub_accounts_rest_call_success(request_type): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'provider': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = accounts.ListSubAccountsResponse( + 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 = accounts.ListSubAccountsResponse.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_sub_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sub_accounts_rest_interceptors(null_interceptor): + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), + ) + client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_sub_accounts") as post, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_sub_accounts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_sub_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = accounts.ListSubAccountsRequest.pb(accounts.ListSubAccountsRequest()) + 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 = accounts.ListSubAccountsResponse.to_json(accounts.ListSubAccountsResponse()) + req.return_value.content = return_value + + request = accounts.ListSubAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = accounts.ListSubAccountsResponse() + post_with_metadata.return_value = accounts.ListSubAccountsResponse(), metadata + + client.list_sub_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AccountsServiceClient( + 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_get_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + client.get_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.GetAccountRequest() + + 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_create_and_configure_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_and_configure_account), + '__call__') as call: + client.create_and_configure_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.CreateAndConfigureAccountRequest() + + 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_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + client.delete_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.DeleteAccountRequest() + + 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_update_account_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + client.update_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.UpdateAccountRequest() + + 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_list_accounts_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + client.list_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListAccountsRequest() + + 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_list_sub_accounts_empty_call_rest(): + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_sub_accounts), + '__call__') as call: + client.list_sub_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = accounts.ListSubAccountsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AccountsServiceGrpcTransport, + ) + +def test_accounts_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_accounts_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.accounts_service.transports.AccountsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account', + 'create_and_configure_account', + 'delete_account', + 'update_account', + 'list_accounts', + 'list_sub_accounts', + ) + 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_accounts_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_accounts_v1beta.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountsServiceTransport( + 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_accounts_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_accounts_v1beta.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AccountsServiceTransport() + adc.assert_called_once() + + +def test_accounts_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) + AccountsServiceClient() + 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.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + ], +) +def test_accounts_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.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + transports.AccountsServiceRestTransport, + ], +) +def test_accounts_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.AccountsServiceGrpcTransport, grpc_helpers), + (transports.AccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +def test_accounts_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_accounts_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.AccountsServiceRestTransport ( + 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_accounts_service_host_no_port(transport_name): + client = AccountsServiceClient( + 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_accounts_service_host_with_port(transport_name): + client = AccountsServiceClient( + 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_accounts_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AccountsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AccountsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account._session + session2 = client2.transport.get_account._session + assert session1 != session2 + session1 = client1.transport.create_and_configure_account._session + session2 = client2.transport.create_and_configure_account._session + assert session1 != session2 + session1 = client1.transport.delete_account._session + session2 = client2.transport.delete_account._session + assert session1 != session2 + session1 = client1.transport.update_account._session + session2 = client2.transport.update_account._session + assert session1 != session2 + session1 = client1.transport.list_accounts._session + session2 = client2.transport.list_accounts._session + assert session1 != session2 + session1 = client1.transport.list_sub_accounts._session + session2 = client2.transport.list_sub_accounts._session + assert session1 != session2 +def test_accounts_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountsServiceGrpcTransport( + 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_accounts_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AccountsServiceGrpcAsyncIOTransport( + 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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +def test_accounts_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AccountsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AccountsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_account_path(path) + assert expected == actual + +def test_terms_of_service_path(): + version = "whelk" + expected = "termsOfService/{version}".format(version=version, ) + actual = AccountsServiceClient.terms_of_service_path(version) + assert expected == actual + + +def test_parse_terms_of_service_path(): + expected = { + "version": "octopus", + } + path = AccountsServiceClient.terms_of_service_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_terms_of_service_path(path) + assert expected == actual + +def test_user_path(): + account = "oyster" + email = "nudibranch" + expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) + actual = AccountsServiceClient.user_path(account, email) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "account": "cuttlefish", + "email": "mussel", + } + path = AccountsServiceClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AccountsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = AccountsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = AccountsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = AccountsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AccountsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = AccountsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = AccountsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = AccountsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AccountsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = AccountsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AccountsServiceClient.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.AccountsServiceTransport, '_prep_wrapped_messages') as prep: + client = AccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AccountsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AccountsServiceClient.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 = AccountsServiceClient( + 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 = AccountsServiceAsyncClient( + 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 = AccountsServiceClient( + 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 = AccountsServiceClient( + 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", [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py new file mode 100644 index 000000000000..e0498b775e93 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py @@ -0,0 +1,2890 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service import AutofeedSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service import transports +from google.shopping.merchant_accounts_v1beta.types import autofeedsettings +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 AutofeedSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, False) is None + assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AutofeedSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AutofeedSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AutofeedSettingsServiceClient._get_universe_domain(None, None) == AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient(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 = AutofeedSettingsServiceClient(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", [ + (AutofeedSettingsServiceClient, "grpc"), + (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), + (AutofeedSettingsServiceClient, "rest"), +]) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, "grpc"), + (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +def test_autofeed_settings_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", [ + (AutofeedSettingsServiceClient, "grpc"), + (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), + (AutofeedSettingsServiceClient, "rest"), +]) +def test_autofeed_settings_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_autofeed_settings_service_client_get_transport_class(): + transport = AutofeedSettingsServiceClient.get_transport_class() + available_transports = [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = AutofeedSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.AutofeedSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +def test_autofeed_settings_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(AutofeedSettingsServiceClient, '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(AutofeedSettingsServiceClient, '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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "true"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "false"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "true"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_autofeed_settings_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", [ + AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient +]) +@mock.patch.object(AutofeedSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceAsyncClient)) +def test_autofeed_settings_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", [ + AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient +]) +@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) +@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +def test_autofeed_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutofeedSettingsServiceClient._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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), +]) +def test_autofeed_settings_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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", None), +]) +def test_autofeed_settings_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_autofeed_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AutofeedSettingsServiceClient( + 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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_autofeed_settings_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", [ + autofeedsettings.GetAutofeedSettingsRequest, + dict, +]) +def test_get_autofeed_settings(request_type, transport: str = 'grpc'): + client = AutofeedSettingsServiceClient( + 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.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + response = client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autofeedsettings.GetAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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 = autofeedsettings.GetAutofeedSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_autofeed_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autofeedsettings.GetAutofeedSettingsRequest( + name='name_value', + ) + +def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.get_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc + request = {} + client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_autofeed_settings(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_get_autofeed_settings_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 = AutofeedSettingsServiceAsyncClient( + 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.get_autofeed_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_autofeed_settings] = mock_rpc + + request = {} + await client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_autofeed_settings(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_get_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.GetAutofeedSettingsRequest): + client = AutofeedSettingsServiceAsyncClient( + 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.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + response = await client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autofeedsettings.GetAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.asyncio +async def test_get_autofeed_settings_async_from_dict(): + await test_get_autofeed_settings_async(request_type=dict) + +def test_get_autofeed_settings_field_headers(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.GetAutofeedSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.get_autofeed_settings(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_get_autofeed_settings_field_headers_async(): + client = AutofeedSettingsServiceAsyncClient( + 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 = autofeedsettings.GetAutofeedSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + await client.get_autofeed_settings(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_get_autofeed_settings_flattened(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_autofeed_settings( + 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_get_autofeed_settings_flattened_error(): + client = AutofeedSettingsServiceClient( + 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.get_autofeed_settings( + autofeedsettings.GetAutofeedSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_autofeed_settings_flattened_async(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_autofeed_settings( + 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_get_autofeed_settings_flattened_error_async(): + client = AutofeedSettingsServiceAsyncClient( + 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.get_autofeed_settings( + autofeedsettings.GetAutofeedSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + autofeedsettings.UpdateAutofeedSettingsRequest, + dict, +]) +def test_update_autofeed_settings(request_type, transport: str = 'grpc'): + client = AutofeedSettingsServiceClient( + 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.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + response = client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autofeedsettings.UpdateAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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 = autofeedsettings.UpdateAutofeedSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_autofeed_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autofeedsettings.UpdateAutofeedSettingsRequest( + ) + +def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.update_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc + request = {} + client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_autofeed_settings(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_update_autofeed_settings_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 = AutofeedSettingsServiceAsyncClient( + 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.update_autofeed_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_autofeed_settings] = mock_rpc + + request = {} + await client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_autofeed_settings(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_update_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.UpdateAutofeedSettingsRequest): + client = AutofeedSettingsServiceAsyncClient( + 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.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + response = await client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autofeedsettings.UpdateAutofeedSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.asyncio +async def test_update_autofeed_settings_async_from_dict(): + await test_update_autofeed_settings_async(request_type=dict) + +def test_update_autofeed_settings_field_headers(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.UpdateAutofeedSettingsRequest() + + request.autofeed_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.update_autofeed_settings(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', + 'autofeed_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_autofeed_settings_field_headers_async(): + client = AutofeedSettingsServiceAsyncClient( + 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 = autofeedsettings.UpdateAutofeedSettingsRequest() + + request.autofeed_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + await client.update_autofeed_settings(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', + 'autofeed_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_autofeed_settings_flattened(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_autofeed_settings( + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].autofeed_settings + mock_val = autofeedsettings.AutofeedSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_autofeed_settings_flattened_error(): + client = AutofeedSettingsServiceClient( + 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.update_autofeed_settings( + autofeedsettings.UpdateAutofeedSettingsRequest(), + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_autofeed_settings_flattened_async(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autofeedsettings.AutofeedSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_autofeed_settings( + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].autofeed_settings + mock_val = autofeedsettings.AutofeedSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_autofeed_settings_flattened_error_async(): + client = AutofeedSettingsServiceAsyncClient( + 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.update_autofeed_settings( + autofeedsettings.UpdateAutofeedSettingsRequest(), + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.get_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc + + request = {} + client.get_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_autofeed_settings(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_get_autofeed_settings_rest_required_fields(request_type=autofeedsettings.GetAutofeedSettingsRequest): + transport_class = transports.AutofeedSettingsServiceRestTransport + + 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()).get_autofeed_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autofeed_settings._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 = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autofeedsettings.AutofeedSettings() + # 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 = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_autofeed_settings_rest_unset_required_fields(): + transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_autofeed_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_autofeed_settings_rest_flattened(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.AutofeedSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/autofeedSettings'} + + # 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 + # Convert return value to protobuf type + return_value = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(**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/accounts/v1beta/{name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) + + +def test_get_autofeed_settings_rest_flattened_error(transport: str = 'rest'): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_autofeed_settings( + autofeedsettings.GetAutofeedSettingsRequest(), + name='name_value', + ) + + +def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( + 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.update_autofeed_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc + + request = {} + client.update_autofeed_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_autofeed_settings(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_update_autofeed_settings_rest_required_fields(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): + transport_class = transports.AutofeedSettingsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autofeedsettings.AutofeedSettings() + # 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': "patch", + '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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_autofeed_settings_rest_unset_required_fields(): + transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_autofeed_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("autofeedSettings", "updateMask", ))) + + +def test_update_autofeed_settings_rest_flattened(): + client = AutofeedSettingsServiceClient( + 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 = autofeedsettings.AutofeedSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(**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/accounts/v1beta/{autofeed_settings.name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) + + +def test_update_autofeed_settings_rest_flattened_error(transport: str = 'rest'): + client = AutofeedSettingsServiceClient( + 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.update_autofeed_settings( + autofeedsettings.UpdateAutofeedSettingsRequest(), + autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + 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 = AutofeedSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutofeedSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AutofeedSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutofeedSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AutofeedSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + transports.AutofeedSettingsServiceRestTransport, +]) +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 = AutofeedSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AutofeedSettingsServiceClient( + 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_get_autofeed_settings_empty_call_grpc(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.get_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.GetAutofeedSettingsRequest() + + 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_update_autofeed_settings_empty_call_grpc(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + call.return_value = autofeedsettings.AutofeedSettings() + client.update_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AutofeedSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AutofeedSettingsServiceAsyncClient( + 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_get_autofeed_settings_empty_call_grpc_asyncio(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + await client.get_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.GetAutofeedSettingsRequest() + + 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_update_autofeed_settings_empty_call_grpc_asyncio(): + client = AutofeedSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + )) + await client.update_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AutofeedSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_autofeed_settings_rest_bad_request(request_type=autofeedsettings.GetAutofeedSettingsRequest): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/autofeedSettings'} + 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.get_autofeed_settings(request) + + +@pytest.mark.parametrize("request_type", [ + autofeedsettings.GetAutofeedSettingsRequest, + dict, +]) +def test_get_autofeed_settings_rest_call_success(request_type): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/autofeedSettings'} + request = request_type(**request_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 = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + + # 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 = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_autofeed_settings_rest_interceptors(null_interceptor): + transport = transports.AutofeedSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), + ) + client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings") as post, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_get_autofeed_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autofeedsettings.GetAutofeedSettingsRequest.pb(autofeedsettings.GetAutofeedSettingsRequest()) + 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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) + req.return_value.content = return_value + + request = autofeedsettings.GetAutofeedSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autofeedsettings.AutofeedSettings() + post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata + + client.get_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_autofeed_settings_rest_bad_request(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + 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.update_autofeed_settings(request) + + +@pytest.mark.parametrize("request_type", [ + autofeedsettings.UpdateAutofeedSettingsRequest, + dict, +]) +def test_update_autofeed_settings_rest_call_success(request_type): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + request_init["autofeed_settings"] = {'name': 'accounts/sample1/autofeedSettings', 'enable_products': True, 'eligible': True} + # 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 = autofeedsettings.UpdateAutofeedSettingsRequest.meta.fields["autofeed_settings"] + + 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["autofeed_settings"].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["autofeed_settings"][field])): + del request_init["autofeed_settings"][field][i][subfield] + else: + del request_init["autofeed_settings"][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 = autofeedsettings.AutofeedSettings( + name='name_value', + enable_products=True, + eligible=True, + ) + + # 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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autofeedsettings.AutofeedSettings) + assert response.name == 'name_value' + assert response.enable_products is True + assert response.eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_autofeed_settings_rest_interceptors(null_interceptor): + transport = transports.AutofeedSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), + ) + client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings") as post, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_update_autofeed_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = autofeedsettings.UpdateAutofeedSettingsRequest.pb(autofeedsettings.UpdateAutofeedSettingsRequest()) + 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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) + req.return_value.content = return_value + + request = autofeedsettings.UpdateAutofeedSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autofeedsettings.AutofeedSettings() + post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata + + client.update_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AutofeedSettingsServiceClient( + 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_get_autofeed_settings_empty_call_rest(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autofeed_settings), + '__call__') as call: + client.get_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.GetAutofeedSettingsRequest() + + 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_update_autofeed_settings_empty_call_rest(): + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autofeed_settings), + '__call__') as call: + client.update_autofeed_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AutofeedSettingsServiceGrpcTransport, + ) + +def test_autofeed_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AutofeedSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_autofeed_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AutofeedSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_autofeed_settings', + 'update_autofeed_settings', + ) + 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_autofeed_settings_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_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutofeedSettingsServiceTransport( + 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_autofeed_settings_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_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutofeedSettingsServiceTransport() + adc.assert_called_once() + + +def test_autofeed_settings_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) + AutofeedSettingsServiceClient() + 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.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + transports.AutofeedSettingsServiceRestTransport, + ], +) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, grpc_helpers), + (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +def test_autofeed_settings_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_autofeed_settings_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.AutofeedSettingsServiceRestTransport ( + 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_autofeed_settings_service_host_no_port(transport_name): + client = AutofeedSettingsServiceClient( + 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_autofeed_settings_service_host_with_port(transport_name): + client = AutofeedSettingsServiceClient( + 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_autofeed_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutofeedSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutofeedSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_autofeed_settings._session + session2 = client2.transport.get_autofeed_settings._session + assert session1 != session2 + session1 = client1.transport.update_autofeed_settings._session + session2 = client2.transport.update_autofeed_settings._session + assert session1 != session2 +def test_autofeed_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutofeedSettingsServiceGrpcTransport( + 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_autofeed_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutofeedSettingsServiceGrpcAsyncIOTransport( + 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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +def test_autofeed_settings_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_autofeed_settings_path(): + account = "squid" + expected = "accounts/{account}/autofeedSettings".format(account=account, ) + actual = AutofeedSettingsServiceClient.autofeed_settings_path(account) + assert expected == actual + + +def test_parse_autofeed_settings_path(): + expected = { + "account": "clam", + } + path = AutofeedSettingsServiceClient.autofeed_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_autofeed_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AutofeedSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AutofeedSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AutofeedSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AutofeedSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AutofeedSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AutofeedSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AutofeedSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AutofeedSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AutofeedSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AutofeedSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AutofeedSettingsServiceClient.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.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = AutofeedSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AutofeedSettingsServiceClient.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 = AutofeedSettingsServiceClient( + 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 = AutofeedSettingsServiceAsyncClient( + 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 = AutofeedSettingsServiceClient( + 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 = AutofeedSettingsServiceClient( + 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", [ + (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport), + (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py new file mode 100644 index 000000000000..c95f4dd231df --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py @@ -0,0 +1,2862 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service import AutomaticImprovementsServiceClient +from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service import transports +from google.shopping.merchant_accounts_v1beta.types import automaticimprovements +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 AutomaticImprovementsServiceClient._get_default_mtls_endpoint(None) is None + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, False) is None + assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AutomaticImprovementsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AutomaticImprovementsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AutomaticImprovementsServiceClient._get_universe_domain(None, None) == AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient(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 = AutomaticImprovementsServiceClient(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", [ + (AutomaticImprovementsServiceClient, "grpc"), + (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, "rest"), +]) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutomaticImprovementsServiceRestTransport, "rest"), +]) +def test_automatic_improvements_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", [ + (AutomaticImprovementsServiceClient, "grpc"), + (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, "rest"), +]) +def test_automatic_improvements_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_automatic_improvements_service_client_get_transport_class(): + transport = AutomaticImprovementsServiceClient.get_transport_class() + available_transports = [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceRestTransport, + ] + assert transport in available_transports + + transport = AutomaticImprovementsServiceClient.get_transport_class("grpc") + assert transport == transports.AutomaticImprovementsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +def test_automatic_improvements_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(AutomaticImprovementsServiceClient, '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(AutomaticImprovementsServiceClient, '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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "true"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "false"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "true"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_automatic_improvements_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", [ + AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceAsyncClient)) +def test_automatic_improvements_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", [ + AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient +]) +@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) +@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +def test_automatic_improvements_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutomaticImprovementsServiceClient._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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), +]) +def test_automatic_improvements_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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", None), +]) +def test_automatic_improvements_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_automatic_improvements_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AutomaticImprovementsServiceClient( + 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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_automatic_improvements_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", [ + automaticimprovements.GetAutomaticImprovementsRequest, + dict, +]) +def test_get_automatic_improvements(request_type, transport: str = 'grpc'): + client = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements( + name='name_value', + ) + response = client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = automaticimprovements.GetAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.GetAutomaticImprovementsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_automatic_improvements(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == automaticimprovements.GetAutomaticImprovementsRequest( + name='name_value', + ) + +def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc + request = {} + client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_automatic_improvements(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_get_automatic_improvements_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 = AutomaticImprovementsServiceAsyncClient( + 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.get_automatic_improvements in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_automatic_improvements] = mock_rpc + + request = {} + await client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_automatic_improvements(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_get_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.GetAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceAsyncClient( + 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.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + response = await client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = automaticimprovements.GetAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_automatic_improvements_async_from_dict(): + await test_get_automatic_improvements_async(request_type=dict) + +def test_get_automatic_improvements_field_headers(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.GetAutomaticImprovementsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.get_automatic_improvements(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_get_automatic_improvements_field_headers_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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 = automaticimprovements.GetAutomaticImprovementsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + await client.get_automatic_improvements(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_get_automatic_improvements_flattened(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_automatic_improvements( + 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_get_automatic_improvements_flattened_error(): + client = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements( + automaticimprovements.GetAutomaticImprovementsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_automatic_improvements_flattened_async(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_automatic_improvements( + 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_get_automatic_improvements_flattened_error_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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.get_automatic_improvements( + automaticimprovements.GetAutomaticImprovementsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + automaticimprovements.UpdateAutomaticImprovementsRequest, + dict, +]) +def test_update_automatic_improvements(request_type, transport: str = 'grpc'): + client = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements( + name='name_value', + ) + response = client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = automaticimprovements.UpdateAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.UpdateAutomaticImprovementsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_automatic_improvements(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == automaticimprovements.UpdateAutomaticImprovementsRequest( + ) + +def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc + request = {} + client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_automatic_improvements(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_update_automatic_improvements_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 = AutomaticImprovementsServiceAsyncClient( + 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.update_automatic_improvements in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_automatic_improvements] = mock_rpc + + request = {} + await client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_automatic_improvements(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_update_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceAsyncClient( + 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.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + response = await client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = automaticimprovements.UpdateAutomaticImprovementsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_update_automatic_improvements_async_from_dict(): + await test_update_automatic_improvements_async(request_type=dict) + +def test_update_automatic_improvements_field_headers(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.UpdateAutomaticImprovementsRequest() + + request.automatic_improvements.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.update_automatic_improvements(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', + 'automatic_improvements.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_automatic_improvements_field_headers_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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 = automaticimprovements.UpdateAutomaticImprovementsRequest() + + request.automatic_improvements.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + await client.update_automatic_improvements(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', + 'automatic_improvements.name=name_value', + ) in kw['metadata'] + + +def test_update_automatic_improvements_flattened(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_automatic_improvements( + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].automatic_improvements + mock_val = automaticimprovements.AutomaticImprovements(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_automatic_improvements_flattened_error(): + client = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements( + automaticimprovements.UpdateAutomaticImprovementsRequest(), + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_automatic_improvements_flattened_async(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = automaticimprovements.AutomaticImprovements() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_automatic_improvements( + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].automatic_improvements + mock_val = automaticimprovements.AutomaticImprovements(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_automatic_improvements_flattened_error_async(): + client = AutomaticImprovementsServiceAsyncClient( + 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.update_automatic_improvements( + automaticimprovements.UpdateAutomaticImprovementsRequest(), + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.get_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc + + request = {} + client.get_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_automatic_improvements(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_get_automatic_improvements_rest_required_fields(request_type=automaticimprovements.GetAutomaticImprovementsRequest): + transport_class = transports.AutomaticImprovementsServiceRestTransport + + 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()).get_automatic_improvements._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_automatic_improvements._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 = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = automaticimprovements.AutomaticImprovements() + # 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 = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_automatic_improvements_rest_unset_required_fields(): + transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_automatic_improvements._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_automatic_improvements_rest_flattened(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.AutomaticImprovements() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/automaticImprovements'} + + # 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 + # Convert return value to protobuf type + return_value = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(**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/accounts/v1beta/{name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) + + +def test_get_automatic_improvements_rest_flattened_error(transport: str = 'rest'): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_automatic_improvements( + automaticimprovements.GetAutomaticImprovementsRequest(), + name='name_value', + ) + + +def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc + + request = {} + client.update_automatic_improvements(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_automatic_improvements(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_update_automatic_improvements_rest_required_fields(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): + transport_class = transports.AutomaticImprovementsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = automaticimprovements.AutomaticImprovements() + # 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': "patch", + '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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_automatic_improvements_rest_unset_required_fields(): + transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_automatic_improvements._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("automaticImprovements", "updateMask", ))) + + +def test_update_automatic_improvements_rest_flattened(): + client = AutomaticImprovementsServiceClient( + 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 = automaticimprovements.AutomaticImprovements() + + # get arguments that satisfy an http rule for this method + sample_request = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + + # get truthy value for each flattened field + mock_args = dict( + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(**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/accounts/v1beta/{automatic_improvements.name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) + + +def test_update_automatic_improvements_rest_flattened_error(transport: str = 'rest'): + client = AutomaticImprovementsServiceClient( + 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.update_automatic_improvements( + automaticimprovements.UpdateAutomaticImprovementsRequest(), + automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + 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 = AutomaticImprovementsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutomaticImprovementsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AutomaticImprovementsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AutomaticImprovementsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + transports.AutomaticImprovementsServiceRestTransport, +]) +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 = AutomaticImprovementsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AutomaticImprovementsServiceClient( + 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_get_automatic_improvements_empty_call_grpc(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.get_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.GetAutomaticImprovementsRequest() + + 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_update_automatic_improvements_empty_call_grpc(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + call.return_value = automaticimprovements.AutomaticImprovements() + client.update_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AutomaticImprovementsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AutomaticImprovementsServiceAsyncClient( + 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_get_automatic_improvements_empty_call_grpc_asyncio(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + await client.get_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.GetAutomaticImprovementsRequest() + + 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_update_automatic_improvements_empty_call_grpc_asyncio(): + client = AutomaticImprovementsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( + name='name_value', + )) + await client.update_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AutomaticImprovementsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_automatic_improvements_rest_bad_request(request_type=automaticimprovements.GetAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/automaticImprovements'} + 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.get_automatic_improvements(request) + + +@pytest.mark.parametrize("request_type", [ + automaticimprovements.GetAutomaticImprovementsRequest, + dict, +]) +def test_get_automatic_improvements_rest_call_success(request_type): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/automaticImprovements'} + request = request_type(**request_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 = automaticimprovements.AutomaticImprovements( + name='name_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 = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_automatic_improvements_rest_interceptors(null_interceptor): + transport = transports.AutomaticImprovementsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), + ) + client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements") as post, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_get_automatic_improvements") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = automaticimprovements.GetAutomaticImprovementsRequest.pb(automaticimprovements.GetAutomaticImprovementsRequest()) + 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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) + req.return_value.content = return_value + + request = automaticimprovements.GetAutomaticImprovementsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = automaticimprovements.AutomaticImprovements() + post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata + + client.get_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_automatic_improvements_rest_bad_request(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + 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.update_automatic_improvements(request) + + +@pytest.mark.parametrize("request_type", [ + automaticimprovements.UpdateAutomaticImprovementsRequest, + dict, +]) +def test_update_automatic_improvements_rest_call_success(request_type): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + request_init["automatic_improvements"] = {'name': 'accounts/sample1/automaticImprovements', 'item_updates': {'account_item_updates_settings': {'allow_price_updates': True, 'allow_availability_updates': True, 'allow_strict_availability_updates': True, 'allow_condition_updates': True}, 'effective_allow_price_updates': True, 'effective_allow_availability_updates': True, 'effective_allow_strict_availability_updates': True, 'effective_allow_condition_updates': True}, 'image_improvements': {'account_image_improvements_settings': {'allow_automatic_image_improvements': True}, 'effective_allow_automatic_image_improvements': True}, 'shipping_improvements': {'allow_shipping_improvements': True}} + # 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 = automaticimprovements.UpdateAutomaticImprovementsRequest.meta.fields["automatic_improvements"] + + 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["automatic_improvements"].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["automatic_improvements"][field])): + del request_init["automatic_improvements"][field][i][subfield] + else: + del request_init["automatic_improvements"][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 = automaticimprovements.AutomaticImprovements( + name='name_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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, automaticimprovements.AutomaticImprovements) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_automatic_improvements_rest_interceptors(null_interceptor): + transport = transports.AutomaticImprovementsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), + ) + client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements") as post, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_update_automatic_improvements") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = automaticimprovements.UpdateAutomaticImprovementsRequest.pb(automaticimprovements.UpdateAutomaticImprovementsRequest()) + 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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) + req.return_value.content = return_value + + request = automaticimprovements.UpdateAutomaticImprovementsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = automaticimprovements.AutomaticImprovements() + post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata + + client.update_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = AutomaticImprovementsServiceClient( + 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_get_automatic_improvements_empty_call_rest(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_automatic_improvements), + '__call__') as call: + client.get_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.GetAutomaticImprovementsRequest() + + 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_update_automatic_improvements_empty_call_rest(): + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_automatic_improvements), + '__call__') as call: + client.update_automatic_improvements(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AutomaticImprovementsServiceGrpcTransport, + ) + +def test_automatic_improvements_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AutomaticImprovementsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_automatic_improvements_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AutomaticImprovementsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_automatic_improvements', + 'update_automatic_improvements', + ) + 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_automatic_improvements_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_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutomaticImprovementsServiceTransport( + 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_automatic_improvements_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_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutomaticImprovementsServiceTransport() + adc.assert_called_once() + + +def test_automatic_improvements_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) + AutomaticImprovementsServiceClient() + 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.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + ], +) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + transports.AutomaticImprovementsServiceRestTransport, + ], +) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, grpc_helpers), + (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +def test_automatic_improvements_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_automatic_improvements_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.AutomaticImprovementsServiceRestTransport ( + 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_automatic_improvements_service_host_no_port(transport_name): + client = AutomaticImprovementsServiceClient( + 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_automatic_improvements_service_host_with_port(transport_name): + client = AutomaticImprovementsServiceClient( + 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_automatic_improvements_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutomaticImprovementsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutomaticImprovementsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_automatic_improvements._session + session2 = client2.transport.get_automatic_improvements._session + assert session1 != session2 + session1 = client1.transport.update_automatic_improvements._session + session2 = client2.transport.update_automatic_improvements._session + assert session1 != session2 +def test_automatic_improvements_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutomaticImprovementsServiceGrpcTransport( + 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_automatic_improvements_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutomaticImprovementsServiceGrpcAsyncIOTransport( + 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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +def test_automatic_improvements_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_automatic_improvements_path(): + account = "squid" + expected = "accounts/{account}/automaticImprovements".format(account=account, ) + actual = AutomaticImprovementsServiceClient.automatic_improvements_path(account) + assert expected == actual + + +def test_parse_automatic_improvements_path(): + expected = { + "account": "clam", + } + path = AutomaticImprovementsServiceClient.automatic_improvements_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_automatic_improvements_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AutomaticImprovementsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AutomaticImprovementsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AutomaticImprovementsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AutomaticImprovementsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AutomaticImprovementsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AutomaticImprovementsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AutomaticImprovementsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AutomaticImprovementsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AutomaticImprovementsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AutomaticImprovementsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AutomaticImprovementsServiceClient.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.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: + client = AutomaticImprovementsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AutomaticImprovementsServiceClient.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 = AutomaticImprovementsServiceClient( + 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 = AutomaticImprovementsServiceAsyncClient( + 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 = AutomaticImprovementsServiceClient( + 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 = AutomaticImprovementsServiceClient( + 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", [ + (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport), + (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py new file mode 100644 index 000000000000..cc178368626f --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py @@ -0,0 +1,2876 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.business_identity_service import BusinessIdentityServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.business_identity_service import BusinessIdentityServiceClient +from google.shopping.merchant_accounts_v1beta.services.business_identity_service import transports +from google.shopping.merchant_accounts_v1beta.types import businessidentity +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 BusinessIdentityServiceClient._get_default_mtls_endpoint(None) is None + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert BusinessIdentityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, False) is None + assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert BusinessIdentityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert BusinessIdentityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert BusinessIdentityServiceClient._get_universe_domain(None, None) == BusinessIdentityServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient(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 = BusinessIdentityServiceClient(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", [ + (BusinessIdentityServiceClient, "grpc"), + (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), + (BusinessIdentityServiceClient, "rest"), +]) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, "grpc"), + (transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BusinessIdentityServiceRestTransport, "rest"), +]) +def test_business_identity_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", [ + (BusinessIdentityServiceClient, "grpc"), + (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), + (BusinessIdentityServiceClient, "rest"), +]) +def test_business_identity_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_business_identity_service_client_get_transport_class(): + transport = BusinessIdentityServiceClient.get_transport_class() + available_transports = [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceRestTransport, + ] + assert transport in available_transports + + transport = BusinessIdentityServiceClient.get_transport_class("grpc") + assert transport == transports.BusinessIdentityServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), +]) +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +def test_business_identity_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(BusinessIdentityServiceClient, '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(BusinessIdentityServiceClient, '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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "true"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "false"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "true"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_business_identity_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", [ + BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient +]) +@mock.patch.object(BusinessIdentityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceAsyncClient)) +def test_business_identity_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", [ + BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient +]) +@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) +@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +def test_business_identity_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessIdentityServiceClient._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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), +]) +def test_business_identity_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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", None), +]) +def test_business_identity_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_business_identity_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = BusinessIdentityServiceClient( + 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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_business_identity_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", [ + businessidentity.GetBusinessIdentityRequest, + dict, +]) +def test_get_business_identity(request_type, transport: str = 'grpc'): + client = BusinessIdentityServiceClient( + 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.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + response = client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessidentity.GetBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +def test_get_business_identity_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 = BusinessIdentityServiceClient( + 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 = businessidentity.GetBusinessIdentityRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_business_identity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessidentity.GetBusinessIdentityRequest( + name='name_value', + ) + +def test_get_business_identity_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 = BusinessIdentityServiceClient( + 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.get_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc + request = {} + client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_identity(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_get_business_identity_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 = BusinessIdentityServiceAsyncClient( + 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.get_business_identity in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_business_identity] = mock_rpc + + request = {} + await client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_business_identity(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_get_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.GetBusinessIdentityRequest): + client = BusinessIdentityServiceAsyncClient( + 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.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + response = await client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessidentity.GetBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.asyncio +async def test_get_business_identity_async_from_dict(): + await test_get_business_identity_async(request_type=dict) + +def test_get_business_identity_field_headers(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.GetBusinessIdentityRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.get_business_identity(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_get_business_identity_field_headers_async(): + client = BusinessIdentityServiceAsyncClient( + 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 = businessidentity.GetBusinessIdentityRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + await client.get_business_identity(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_get_business_identity_flattened(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_business_identity( + 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_get_business_identity_flattened_error(): + client = BusinessIdentityServiceClient( + 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.get_business_identity( + businessidentity.GetBusinessIdentityRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_business_identity_flattened_async(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_business_identity( + 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_get_business_identity_flattened_error_async(): + client = BusinessIdentityServiceAsyncClient( + 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.get_business_identity( + businessidentity.GetBusinessIdentityRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + businessidentity.UpdateBusinessIdentityRequest, + dict, +]) +def test_update_business_identity(request_type, transport: str = 'grpc'): + client = BusinessIdentityServiceClient( + 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.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + response = client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessidentity.UpdateBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +def test_update_business_identity_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 = BusinessIdentityServiceClient( + 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 = businessidentity.UpdateBusinessIdentityRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_business_identity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessidentity.UpdateBusinessIdentityRequest( + ) + +def test_update_business_identity_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 = BusinessIdentityServiceClient( + 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.update_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc + request = {} + client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_identity(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_update_business_identity_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 = BusinessIdentityServiceAsyncClient( + 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.update_business_identity in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_business_identity] = mock_rpc + + request = {} + await client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_business_identity(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_update_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.UpdateBusinessIdentityRequest): + client = BusinessIdentityServiceAsyncClient( + 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.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + response = await client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessidentity.UpdateBusinessIdentityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.asyncio +async def test_update_business_identity_async_from_dict(): + await test_update_business_identity_async(request_type=dict) + +def test_update_business_identity_field_headers(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.UpdateBusinessIdentityRequest() + + request.business_identity.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.update_business_identity(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', + 'business_identity.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_business_identity_field_headers_async(): + client = BusinessIdentityServiceAsyncClient( + 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 = businessidentity.UpdateBusinessIdentityRequest() + + request.business_identity.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + await client.update_business_identity(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', + 'business_identity.name=name_value', + ) in kw['metadata'] + + +def test_update_business_identity_flattened(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_business_identity( + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_identity + mock_val = businessidentity.BusinessIdentity(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_business_identity_flattened_error(): + client = BusinessIdentityServiceClient( + 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.update_business_identity( + businessidentity.UpdateBusinessIdentityRequest(), + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_business_identity_flattened_async(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessidentity.BusinessIdentity() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_business_identity( + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_identity + mock_val = businessidentity.BusinessIdentity(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_business_identity_flattened_error_async(): + client = BusinessIdentityServiceAsyncClient( + 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.update_business_identity( + businessidentity.UpdateBusinessIdentityRequest(), + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_business_identity_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 = BusinessIdentityServiceClient( + 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.get_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc + + request = {} + client.get_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_identity(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_get_business_identity_rest_required_fields(request_type=businessidentity.GetBusinessIdentityRequest): + transport_class = transports.BusinessIdentityServiceRestTransport + + 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()).get_business_identity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_identity._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 = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessidentity.BusinessIdentity() + # 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 = businessidentity.BusinessIdentity.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.get_business_identity(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_business_identity_rest_unset_required_fields(): + transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_business_identity._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_business_identity_rest_flattened(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.BusinessIdentity() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/businessIdentity'} + + # 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 + # Convert return value to protobuf type + return_value = businessidentity.BusinessIdentity.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.get_business_identity(**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/accounts/v1beta/{name=accounts/*/businessIdentity}" % client.transport._host, args[1]) + + +def test_get_business_identity_rest_flattened_error(transport: str = 'rest'): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_business_identity( + businessidentity.GetBusinessIdentityRequest(), + name='name_value', + ) + + +def test_update_business_identity_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 = BusinessIdentityServiceClient( + 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.update_business_identity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc + + request = {} + client.update_business_identity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_identity(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_update_business_identity_rest_required_fields(request_type=businessidentity.UpdateBusinessIdentityRequest): + transport_class = transports.BusinessIdentityServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessidentity.BusinessIdentity() + # 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': "patch", + '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 = businessidentity.BusinessIdentity.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.update_business_identity(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_business_identity_rest_unset_required_fields(): + transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_business_identity._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("businessIdentity", "updateMask", ))) + + +def test_update_business_identity_rest_flattened(): + client = BusinessIdentityServiceClient( + 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 = businessidentity.BusinessIdentity() + + # get arguments that satisfy an http rule for this method + sample_request = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + + # get truthy value for each flattened field + mock_args = dict( + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = businessidentity.BusinessIdentity.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.update_business_identity(**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/accounts/v1beta/{business_identity.name=accounts/*/businessIdentity}" % client.transport._host, args[1]) + + +def test_update_business_identity_rest_flattened_error(transport: str = 'rest'): + client = BusinessIdentityServiceClient( + 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.update_business_identity( + businessidentity.UpdateBusinessIdentityRequest(), + business_identity=businessidentity.BusinessIdentity(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + 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 = BusinessIdentityServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessIdentityServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BusinessIdentityServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessIdentityServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BusinessIdentityServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + transports.BusinessIdentityServiceRestTransport, +]) +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 = BusinessIdentityServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BusinessIdentityServiceClient( + 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_get_business_identity_empty_call_grpc(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.get_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.GetBusinessIdentityRequest() + + 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_update_business_identity_empty_call_grpc(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + call.return_value = businessidentity.BusinessIdentity() + client.update_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.UpdateBusinessIdentityRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BusinessIdentityServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BusinessIdentityServiceAsyncClient( + 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_get_business_identity_empty_call_grpc_asyncio(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + await client.get_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.GetBusinessIdentityRequest() + + 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_update_business_identity_empty_call_grpc_asyncio(): + client = BusinessIdentityServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + )) + await client.update_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.UpdateBusinessIdentityRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BusinessIdentityServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_business_identity_rest_bad_request(request_type=businessidentity.GetBusinessIdentityRequest): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessIdentity'} + 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.get_business_identity(request) + + +@pytest.mark.parametrize("request_type", [ + businessidentity.GetBusinessIdentityRequest, + dict, +]) +def test_get_business_identity_rest_call_success(request_type): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessIdentity'} + request = request_type(**request_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 = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + + # 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 = businessidentity.BusinessIdentity.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.get_business_identity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_business_identity_rest_interceptors(null_interceptor): + transport = transports.BusinessIdentityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), + ) + client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_get_business_identity") as post, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_get_business_identity_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_get_business_identity") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessidentity.GetBusinessIdentityRequest.pb(businessidentity.GetBusinessIdentityRequest()) + 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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) + req.return_value.content = return_value + + request = businessidentity.GetBusinessIdentityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessidentity.BusinessIdentity() + post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata + + client.get_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_business_identity_rest_bad_request(request_type=businessidentity.UpdateBusinessIdentityRequest): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + 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.update_business_identity(request) + + +@pytest.mark.parametrize("request_type", [ + businessidentity.UpdateBusinessIdentityRequest, + dict, +]) +def test_update_business_identity_rest_call_success(request_type): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + request_init["business_identity"] = {'name': 'accounts/sample1/businessIdentity', 'promotions_consent': 1, 'black_owned': {'identity_declaration': 1}, 'women_owned': {}, 'veteran_owned': {}, 'latino_owned': {}, 'small_business': {}} + # 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 = businessidentity.UpdateBusinessIdentityRequest.meta.fields["business_identity"] + + 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["business_identity"].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["business_identity"][field])): + del request_init["business_identity"][field][i][subfield] + else: + del request_init["business_identity"][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 = businessidentity.BusinessIdentity( + name='name_value', + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + + # 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 = businessidentity.BusinessIdentity.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.update_business_identity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessidentity.BusinessIdentity) + assert response.name == 'name_value' + assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_business_identity_rest_interceptors(null_interceptor): + transport = transports.BusinessIdentityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), + ) + client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_update_business_identity") as post, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_update_business_identity_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_update_business_identity") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessidentity.UpdateBusinessIdentityRequest.pb(businessidentity.UpdateBusinessIdentityRequest()) + 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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) + req.return_value.content = return_value + + request = businessidentity.UpdateBusinessIdentityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessidentity.BusinessIdentity() + post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata + + client.update_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = BusinessIdentityServiceClient( + 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_get_business_identity_empty_call_rest(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_identity), + '__call__') as call: + client.get_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.GetBusinessIdentityRequest() + + 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_update_business_identity_empty_call_rest(): + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_identity), + '__call__') as call: + client.update_business_identity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessidentity.UpdateBusinessIdentityRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BusinessIdentityServiceGrpcTransport, + ) + +def test_business_identity_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BusinessIdentityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_business_identity_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.BusinessIdentityServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_business_identity', + 'update_business_identity', + ) + 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_business_identity_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_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessIdentityServiceTransport( + 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_business_identity_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_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessIdentityServiceTransport() + adc.assert_called_once() + + +def test_business_identity_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) + BusinessIdentityServiceClient() + 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.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + ], +) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + transports.BusinessIdentityServiceRestTransport, + ], +) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, grpc_helpers), + (transports.BusinessIdentityServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +def test_business_identity_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_business_identity_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.BusinessIdentityServiceRestTransport ( + 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_business_identity_service_host_no_port(transport_name): + client = BusinessIdentityServiceClient( + 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_business_identity_service_host_with_port(transport_name): + client = BusinessIdentityServiceClient( + 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_business_identity_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BusinessIdentityServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BusinessIdentityServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_business_identity._session + session2 = client2.transport.get_business_identity._session + assert session1 != session2 + session1 = client1.transport.update_business_identity._session + session2 = client2.transport.update_business_identity._session + assert session1 != session2 +def test_business_identity_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessIdentityServiceGrpcTransport( + 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_business_identity_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessIdentityServiceGrpcAsyncIOTransport( + 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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +def test_business_identity_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_business_identity_path(): + account = "squid" + expected = "accounts/{account}/businessIdentity".format(account=account, ) + actual = BusinessIdentityServiceClient.business_identity_path(account) + assert expected == actual + + +def test_parse_business_identity_path(): + expected = { + "account": "clam", + } + path = BusinessIdentityServiceClient.business_identity_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_business_identity_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = BusinessIdentityServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = BusinessIdentityServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = BusinessIdentityServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = BusinessIdentityServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = BusinessIdentityServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = BusinessIdentityServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = BusinessIdentityServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = BusinessIdentityServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = BusinessIdentityServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = BusinessIdentityServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessIdentityServiceClient.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.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: + client = BusinessIdentityServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = BusinessIdentityServiceClient.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 = BusinessIdentityServiceClient( + 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 = BusinessIdentityServiceAsyncClient( + 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 = BusinessIdentityServiceClient( + 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 = BusinessIdentityServiceClient( + 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", [ + (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport), + (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py new file mode 100644 index 000000000000..eccedd1d0cee --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py @@ -0,0 +1,2894 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.business_info_service import BusinessInfoServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.business_info_service import BusinessInfoServiceClient +from google.shopping.merchant_accounts_v1beta.services.business_info_service import transports +from google.shopping.merchant_accounts_v1beta.types import businessinfo +from google.shopping.merchant_accounts_v1beta.types import customerservice +from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate +from google.type import phone_number_pb2 # type: ignore +from google.type import postal_address_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 BusinessInfoServiceClient._get_default_mtls_endpoint(None) is None + assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert BusinessInfoServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert BusinessInfoServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + BusinessInfoServiceClient._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 BusinessInfoServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessInfoServiceClient._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 BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, False) is None + assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert BusinessInfoServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + assert BusinessInfoServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert BusinessInfoServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert BusinessInfoServiceClient._get_universe_domain(None, None) == BusinessInfoServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + BusinessInfoServiceClient._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 = BusinessInfoServiceClient(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 = BusinessInfoServiceClient(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", [ + (BusinessInfoServiceClient, "grpc"), + (BusinessInfoServiceAsyncClient, "grpc_asyncio"), + (BusinessInfoServiceClient, "rest"), +]) +def test_business_info_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.BusinessInfoServiceGrpcTransport, "grpc"), + (transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BusinessInfoServiceRestTransport, "rest"), +]) +def test_business_info_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", [ + (BusinessInfoServiceClient, "grpc"), + (BusinessInfoServiceAsyncClient, "grpc_asyncio"), + (BusinessInfoServiceClient, "rest"), +]) +def test_business_info_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_business_info_service_client_get_transport_class(): + transport = BusinessInfoServiceClient.get_transport_class() + available_transports = [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceRestTransport, + ] + assert transport in available_transports + + transport = BusinessInfoServiceClient.get_transport_class("grpc") + assert transport == transports.BusinessInfoServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), +]) +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +def test_business_info_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(BusinessInfoServiceClient, '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(BusinessInfoServiceClient, '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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "true"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "false"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "true"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_business_info_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", [ + BusinessInfoServiceClient, BusinessInfoServiceAsyncClient +]) +@mock.patch.object(BusinessInfoServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceAsyncClient)) +def test_business_info_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", [ + BusinessInfoServiceClient, BusinessInfoServiceAsyncClient +]) +@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) +@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +def test_business_info_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE + default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = BusinessInfoServiceClient._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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), +]) +def test_business_info_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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", None), +]) +def test_business_info_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_business_info_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = BusinessInfoServiceClient( + 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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_business_info_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", [ + businessinfo.GetBusinessInfoRequest, + dict, +]) +def test_get_business_info(request_type, transport: str = 'grpc'): + client = BusinessInfoServiceClient( + 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.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + ) + response = client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessinfo.GetBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +def test_get_business_info_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 = BusinessInfoServiceClient( + 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 = businessinfo.GetBusinessInfoRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_business_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessinfo.GetBusinessInfoRequest( + name='name_value', + ) + +def test_get_business_info_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 = BusinessInfoServiceClient( + 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.get_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc + request = {} + client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_info(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_get_business_info_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 = BusinessInfoServiceAsyncClient( + 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.get_business_info in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_business_info] = mock_rpc + + request = {} + await client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_business_info(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_get_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.GetBusinessInfoRequest): + client = BusinessInfoServiceAsyncClient( + 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.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + response = await client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessinfo.GetBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.asyncio +async def test_get_business_info_async_from_dict(): + await test_get_business_info_async(request_type=dict) + +def test_get_business_info_field_headers(): + client = BusinessInfoServiceClient( + 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 = businessinfo.GetBusinessInfoRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.get_business_info(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_get_business_info_field_headers_async(): + client = BusinessInfoServiceAsyncClient( + 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 = businessinfo.GetBusinessInfoRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + await client.get_business_info(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_get_business_info_flattened(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_business_info( + 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_get_business_info_flattened_error(): + client = BusinessInfoServiceClient( + 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.get_business_info( + businessinfo.GetBusinessInfoRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_business_info_flattened_async(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_business_info( + 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_get_business_info_flattened_error_async(): + client = BusinessInfoServiceAsyncClient( + 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.get_business_info( + businessinfo.GetBusinessInfoRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + businessinfo.UpdateBusinessInfoRequest, + dict, +]) +def test_update_business_info(request_type, transport: str = 'grpc'): + client = BusinessInfoServiceClient( + 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.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + ) + response = client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = businessinfo.UpdateBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +def test_update_business_info_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 = BusinessInfoServiceClient( + 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 = businessinfo.UpdateBusinessInfoRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_business_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == businessinfo.UpdateBusinessInfoRequest( + ) + +def test_update_business_info_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 = BusinessInfoServiceClient( + 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.update_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc + request = {} + client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_info(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_update_business_info_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 = BusinessInfoServiceAsyncClient( + 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.update_business_info in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_business_info] = mock_rpc + + request = {} + await client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_business_info(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_update_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.UpdateBusinessInfoRequest): + client = BusinessInfoServiceAsyncClient( + 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.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + response = await client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = businessinfo.UpdateBusinessInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.asyncio +async def test_update_business_info_async_from_dict(): + await test_update_business_info_async(request_type=dict) + +def test_update_business_info_field_headers(): + client = BusinessInfoServiceClient( + 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 = businessinfo.UpdateBusinessInfoRequest() + + request.business_info.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.update_business_info(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', + 'business_info.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_business_info_field_headers_async(): + client = BusinessInfoServiceAsyncClient( + 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 = businessinfo.UpdateBusinessInfoRequest() + + request.business_info.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + await client.update_business_info(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', + 'business_info.name=name_value', + ) in kw['metadata'] + + +def test_update_business_info_flattened(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_business_info( + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_info + mock_val = businessinfo.BusinessInfo(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_business_info_flattened_error(): + client = BusinessInfoServiceClient( + 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.update_business_info( + businessinfo.UpdateBusinessInfoRequest(), + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_business_info_flattened_async(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = businessinfo.BusinessInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_business_info( + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_info + mock_val = businessinfo.BusinessInfo(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_business_info_flattened_error_async(): + client = BusinessInfoServiceAsyncClient( + 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.update_business_info( + businessinfo.UpdateBusinessInfoRequest(), + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_business_info_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 = BusinessInfoServiceClient( + 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.get_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc + + request = {} + client.get_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_business_info(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_get_business_info_rest_required_fields(request_type=businessinfo.GetBusinessInfoRequest): + transport_class = transports.BusinessInfoServiceRestTransport + + 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()).get_business_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_info._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 = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessinfo.BusinessInfo() + # 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 = businessinfo.BusinessInfo.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.get_business_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_business_info_rest_unset_required_fields(): + transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_business_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_business_info_rest_flattened(): + client = BusinessInfoServiceClient( + 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 = businessinfo.BusinessInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/businessInfo'} + + # 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 + # Convert return value to protobuf type + return_value = businessinfo.BusinessInfo.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.get_business_info(**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/accounts/v1beta/{name=accounts/*/businessInfo}" % client.transport._host, args[1]) + + +def test_get_business_info_rest_flattened_error(transport: str = 'rest'): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_business_info( + businessinfo.GetBusinessInfoRequest(), + name='name_value', + ) + + +def test_update_business_info_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 = BusinessInfoServiceClient( + 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.update_business_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc + + request = {} + client.update_business_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_business_info(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_update_business_info_rest_required_fields(request_type=businessinfo.UpdateBusinessInfoRequest): + transport_class = transports.BusinessInfoServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = businessinfo.BusinessInfo() + # 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': "patch", + '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 = businessinfo.BusinessInfo.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.update_business_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_business_info_rest_unset_required_fields(): + transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_business_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("businessInfo", "updateMask", ))) + + +def test_update_business_info_rest_flattened(): + client = BusinessInfoServiceClient( + 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 = businessinfo.BusinessInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + + # get truthy value for each flattened field + mock_args = dict( + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = businessinfo.BusinessInfo.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.update_business_info(**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/accounts/v1beta/{business_info.name=accounts/*/businessInfo}" % client.transport._host, args[1]) + + +def test_update_business_info_rest_flattened_error(transport: str = 'rest'): + client = BusinessInfoServiceClient( + 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.update_business_info( + businessinfo.UpdateBusinessInfoRequest(), + business_info=businessinfo.BusinessInfo(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + 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 = BusinessInfoServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BusinessInfoServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BusinessInfoServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BusinessInfoServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BusinessInfoServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + transports.BusinessInfoServiceRestTransport, +]) +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 = BusinessInfoServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BusinessInfoServiceClient( + 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_get_business_info_empty_call_grpc(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.get_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.GetBusinessInfoRequest() + + 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_update_business_info_empty_call_grpc(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + call.return_value = businessinfo.BusinessInfo() + client.update_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.UpdateBusinessInfoRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BusinessInfoServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BusinessInfoServiceAsyncClient( + 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_get_business_info_empty_call_grpc_asyncio(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + await client.get_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.GetBusinessInfoRequest() + + 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_update_business_info_empty_call_grpc_asyncio(): + client = BusinessInfoServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_value', + )) + await client.update_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.UpdateBusinessInfoRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BusinessInfoServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_business_info_rest_bad_request(request_type=businessinfo.GetBusinessInfoRequest): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessInfo'} + 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.get_business_info(request) + + +@pytest.mark.parametrize("request_type", [ + businessinfo.GetBusinessInfoRequest, + dict, +]) +def test_get_business_info_rest_call_success(request_type): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/businessInfo'} + request = request_type(**request_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 = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_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 = businessinfo.BusinessInfo.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.get_business_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_business_info_rest_interceptors(null_interceptor): + transport = transports.BusinessInfoServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), + ) + client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_get_business_info") as post, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_get_business_info_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_get_business_info") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessinfo.GetBusinessInfoRequest.pb(businessinfo.GetBusinessInfoRequest()) + 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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) + req.return_value.content = return_value + + request = businessinfo.GetBusinessInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessinfo.BusinessInfo() + post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata + + client.get_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_business_info_rest_bad_request(request_type=businessinfo.UpdateBusinessInfoRequest): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + 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.update_business_info(request) + + +@pytest.mark.parametrize("request_type", [ + businessinfo.UpdateBusinessInfoRequest, + dict, +]) +def test_update_business_info_rest_call_success(request_type): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + request_init["business_info"] = {'name': 'accounts/sample1/businessInfo', 'address': {'revision': 879, 'region_code': 'region_code_value', 'language_code': 'language_code_value', 'postal_code': 'postal_code_value', 'sorting_code': 'sorting_code_value', 'administrative_area': 'administrative_area_value', 'locality': 'locality_value', 'sublocality': 'sublocality_value', 'address_lines': ['address_lines_value1', 'address_lines_value2'], 'recipients': ['recipients_value1', 'recipients_value2'], 'organization': 'organization_value'}, 'phone': {'e164_number': 'e164_number_value', 'short_code': {'region_code': 'region_code_value', 'number': 'number_value'}, 'extension': 'extension_value'}, 'phone_verification_state': 1, 'customer_service': {'uri': 'uri_value', 'email': 'email_value', 'phone': {}}, 'korean_business_registration_number': 'korean_business_registration_number_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 = businessinfo.UpdateBusinessInfoRequest.meta.fields["business_info"] + + 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["business_info"].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["business_info"][field])): + del request_init["business_info"][field][i][subfield] + else: + del request_init["business_info"][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 = businessinfo.BusinessInfo( + name='name_value', + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number='korean_business_registration_number_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 = businessinfo.BusinessInfo.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.update_business_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, businessinfo.BusinessInfo) + assert response.name == 'name_value' + assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + assert response.korean_business_registration_number == 'korean_business_registration_number_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_business_info_rest_interceptors(null_interceptor): + transport = transports.BusinessInfoServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), + ) + client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_update_business_info") as post, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_update_business_info_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_update_business_info") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = businessinfo.UpdateBusinessInfoRequest.pb(businessinfo.UpdateBusinessInfoRequest()) + 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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) + req.return_value.content = return_value + + request = businessinfo.UpdateBusinessInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = businessinfo.BusinessInfo() + post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata + + client.update_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = BusinessInfoServiceClient( + 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_get_business_info_empty_call_rest(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_business_info), + '__call__') as call: + client.get_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.GetBusinessInfoRequest() + + 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_update_business_info_empty_call_rest(): + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_business_info), + '__call__') as call: + client.update_business_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = businessinfo.UpdateBusinessInfoRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BusinessInfoServiceGrpcTransport, + ) + +def test_business_info_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BusinessInfoServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_business_info_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.BusinessInfoServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_business_info', + 'update_business_info', + ) + 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_business_info_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_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessInfoServiceTransport( + 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_business_info_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_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.BusinessInfoServiceTransport() + adc.assert_called_once() + + +def test_business_info_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) + BusinessInfoServiceClient() + 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.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + ], +) +def test_business_info_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.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + transports.BusinessInfoServiceRestTransport, + ], +) +def test_business_info_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.BusinessInfoServiceGrpcTransport, grpc_helpers), + (transports.BusinessInfoServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +def test_business_info_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_business_info_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.BusinessInfoServiceRestTransport ( + 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_business_info_service_host_no_port(transport_name): + client = BusinessInfoServiceClient( + 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_business_info_service_host_with_port(transport_name): + client = BusinessInfoServiceClient( + 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_business_info_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BusinessInfoServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BusinessInfoServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_business_info._session + session2 = client2.transport.get_business_info._session + assert session1 != session2 + session1 = client1.transport.update_business_info._session + session2 = client2.transport.update_business_info._session + assert session1 != session2 +def test_business_info_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessInfoServiceGrpcTransport( + 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_business_info_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.BusinessInfoServiceGrpcAsyncIOTransport( + 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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +def test_business_info_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_business_info_path(): + account = "squid" + expected = "accounts/{account}/businessInfo".format(account=account, ) + actual = BusinessInfoServiceClient.business_info_path(account) + assert expected == actual + + +def test_parse_business_info_path(): + expected = { + "account": "clam", + } + path = BusinessInfoServiceClient.business_info_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_business_info_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = BusinessInfoServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = BusinessInfoServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = BusinessInfoServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = BusinessInfoServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = BusinessInfoServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = BusinessInfoServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = BusinessInfoServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = BusinessInfoServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = BusinessInfoServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = BusinessInfoServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = BusinessInfoServiceClient.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.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: + client = BusinessInfoServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = BusinessInfoServiceClient.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 = BusinessInfoServiceClient( + 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 = BusinessInfoServiceAsyncClient( + 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 = BusinessInfoServiceClient( + 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 = BusinessInfoServiceClient( + 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", [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport), + (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py new file mode 100644 index 000000000000..9df5ec1b5213 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py @@ -0,0 +1,4334 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service import CheckoutSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service import CheckoutSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service import transports +from google.shopping.merchant_accounts_v1beta.types import checkoutsettings +from google.shopping.type.types import types +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 CheckoutSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, False) is None + assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert CheckoutSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert CheckoutSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert CheckoutSettingsServiceClient._get_universe_domain(None, None) == CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient(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 = CheckoutSettingsServiceClient(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", [ + (CheckoutSettingsServiceClient, "grpc"), + (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), + (CheckoutSettingsServiceClient, "rest"), +]) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, "grpc"), + (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CheckoutSettingsServiceRestTransport, "rest"), +]) +def test_checkout_settings_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", [ + (CheckoutSettingsServiceClient, "grpc"), + (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), + (CheckoutSettingsServiceClient, "rest"), +]) +def test_checkout_settings_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_checkout_settings_service_client_get_transport_class(): + transport = CheckoutSettingsServiceClient.get_transport_class() + available_transports = [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = CheckoutSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.CheckoutSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +def test_checkout_settings_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(CheckoutSettingsServiceClient, '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(CheckoutSettingsServiceClient, '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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "true"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "false"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "true"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_checkout_settings_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", [ + CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient +]) +@mock.patch.object(CheckoutSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceAsyncClient)) +def test_checkout_settings_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", [ + CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient +]) +@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) +@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +def test_checkout_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = CheckoutSettingsServiceClient._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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), +]) +def test_checkout_settings_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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", None), +]) +def test_checkout_settings_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_checkout_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CheckoutSettingsServiceClient( + 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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_checkout_settings_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", [ + checkoutsettings.GetCheckoutSettingsRequest, + dict, +]) +def test_get_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + response = client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.GetCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.GetCheckoutSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.GetCheckoutSettingsRequest( + name='name_value', + ) + +def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.get_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc + request = {} + client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_checkout_settings(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_get_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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.get_checkout_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_checkout_settings] = mock_rpc + + request = {} + await client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_checkout_settings(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_get_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.GetCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + response = await client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.GetCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.asyncio +async def test_get_checkout_settings_async_from_dict(): + await test_get_checkout_settings_async(request_type=dict) + +def test_get_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.GetCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.get_checkout_settings(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_get_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.GetCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + await client.get_checkout_settings(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_get_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_checkout_settings( + 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_get_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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.get_checkout_settings( + checkoutsettings.GetCheckoutSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_checkout_settings( + 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_get_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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.get_checkout_settings( + checkoutsettings.GetCheckoutSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.CreateCheckoutSettingsRequest, + dict, +]) +def test_create_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + response = client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.CreateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CreateCheckoutSettingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.CreateCheckoutSettingsRequest( + parent='parent_value', + ) + +def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.create_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc + request = {} + client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_checkout_settings(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_create_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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.create_checkout_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_checkout_settings] = mock_rpc + + request = {} + await client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_checkout_settings(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_create_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.CreateCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + response = await client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.CreateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.asyncio +async def test_create_checkout_settings_async_from_dict(): + await test_create_checkout_settings_async(request_type=dict) + +def test_create_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CreateCheckoutSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.create_checkout_settings(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_create_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.CreateCheckoutSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + await client.create_checkout_settings(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_create_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_checkout_settings( + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + + +def test_create_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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.create_checkout_settings( + checkoutsettings.CreateCheckoutSettingsRequest(), + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_checkout_settings( + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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.create_checkout_settings( + checkoutsettings.CreateCheckoutSettingsRequest(), + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.UpdateCheckoutSettingsRequest, + dict, +]) +def test_update_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + response = client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.UpdateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.UpdateCheckoutSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.UpdateCheckoutSettingsRequest( + ) + +def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.update_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc + request = {} + client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_checkout_settings(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_update_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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.update_checkout_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_checkout_settings] = mock_rpc + + request = {} + await client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_checkout_settings(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_update_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.UpdateCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + response = await client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.UpdateCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.asyncio +async def test_update_checkout_settings_async_from_dict(): + await test_update_checkout_settings_async(request_type=dict) + +def test_update_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.UpdateCheckoutSettingsRequest() + + request.checkout_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.update_checkout_settings(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', + 'checkout_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.UpdateCheckoutSettingsRequest() + + request.checkout_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + await client.update_checkout_settings(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', + 'checkout_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_checkout_settings( + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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.update_checkout_settings( + checkoutsettings.UpdateCheckoutSettingsRequest(), + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = checkoutsettings.CheckoutSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_checkout_settings( + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].checkout_settings + mock_val = checkoutsettings.CheckoutSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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.update_checkout_settings( + checkoutsettings.UpdateCheckoutSettingsRequest(), + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.DeleteCheckoutSettingsRequest, + dict, +]) +def test_delete_checkout_settings(request_type, transport: str = 'grpc'): + client = CheckoutSettingsServiceClient( + 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_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = checkoutsettings.DeleteCheckoutSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( + 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 = checkoutsettings.DeleteCheckoutSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_checkout_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == checkoutsettings.DeleteCheckoutSettingsRequest( + name='name_value', + ) + +def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( + 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_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_checkout_settings] = mock_rpc + request = {} + client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_checkout_settings(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_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( + 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_checkout_settings 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_checkout_settings] = mock_rpc + + request = {} + await client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_checkout_settings(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_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.DeleteCheckoutSettingsRequest): + client = CheckoutSettingsServiceAsyncClient( + 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_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = checkoutsettings.DeleteCheckoutSettingsRequest() + 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_checkout_settings_async_from_dict(): + await test_delete_checkout_settings_async(request_type=dict) + +def test_delete_checkout_settings_field_headers(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.DeleteCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value = None + client.delete_checkout_settings(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_checkout_settings_field_headers_async(): + client = CheckoutSettingsServiceAsyncClient( + 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 = checkoutsettings.DeleteCheckoutSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_checkout_settings(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_checkout_settings_flattened(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__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_checkout_settings( + 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_checkout_settings_flattened_error(): + client = CheckoutSettingsServiceClient( + 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_checkout_settings( + checkoutsettings.DeleteCheckoutSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_checkout_settings_flattened_async(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__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_checkout_settings( + 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_checkout_settings_flattened_error_async(): + client = CheckoutSettingsServiceAsyncClient( + 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_checkout_settings( + checkoutsettings.DeleteCheckoutSettingsRequest(), + name='name_value', + ) + + +def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.get_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc + + request = {} + client.get_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_checkout_settings(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_get_checkout_settings_rest_required_fields(request_type=checkoutsettings.GetCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + 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()).get_checkout_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_checkout_settings._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 = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = checkoutsettings.CheckoutSettings() + # 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 = checkoutsettings.CheckoutSettings.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.get_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CheckoutSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + + # 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 + # Convert return value to protobuf type + return_value = checkoutsettings.CheckoutSettings.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.get_checkout_settings(**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/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + + +def test_get_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_checkout_settings( + checkoutsettings.GetCheckoutSettingsRequest(), + name='name_value', + ) + + +def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.create_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc + + request = {} + client.create_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_checkout_settings(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_create_checkout_settings_rest_required_fields(request_type=checkoutsettings.CreateCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + 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()).create_checkout_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_checkout_settings._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 = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = checkoutsettings.CheckoutSettings() + # 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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "checkoutSettings", ))) + + +def test_create_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CheckoutSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/programs/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(**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/accounts/v1beta/{parent=accounts/*/programs/*}/checkoutSettings" % client.transport._host, args[1]) + + +def test_create_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + 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.create_checkout_settings( + checkoutsettings.CreateCheckoutSettingsRequest(), + parent='parent_value', + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + ) + + +def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( + 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.update_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc + + request = {} + client.update_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_checkout_settings(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_update_checkout_settings_rest_required_fields(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = checkoutsettings.CheckoutSettings() + # 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': "patch", + '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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("checkoutSettings", "updateMask", ))) + + +def test_update_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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 = checkoutsettings.CheckoutSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(**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/accounts/v1beta/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + + +def test_update_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + 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.update_checkout_settings( + checkoutsettings.UpdateCheckoutSettingsRequest(), + checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( + 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_checkout_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_checkout_settings] = mock_rpc + + request = {} + client.delete_checkout_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_checkout_settings(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_checkout_settings_rest_required_fields(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): + transport_class = transports.CheckoutSettingsServiceRestTransport + + 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_checkout_settings._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_checkout_settings._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 = CheckoutSettingsServiceClient( + 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_checkout_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_checkout_settings_rest_unset_required_fields(): + transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_checkout_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_checkout_settings_rest_flattened(): + client = CheckoutSettingsServiceClient( + 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/programs/sample2/checkoutSettings'} + + # 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_checkout_settings(**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/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + + +def test_delete_checkout_settings_rest_flattened_error(transport: str = 'rest'): + client = CheckoutSettingsServiceClient( + 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_checkout_settings( + checkoutsettings.DeleteCheckoutSettingsRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + 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 = CheckoutSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CheckoutSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CheckoutSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CheckoutSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CheckoutSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + transports.CheckoutSettingsServiceRestTransport, +]) +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 = CheckoutSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = CheckoutSettingsServiceClient( + 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_get_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.get_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.GetCheckoutSettingsRequest() + + 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_create_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.create_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.CreateCheckoutSettingsRequest() + + 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_update_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + call.return_value = checkoutsettings.CheckoutSettings() + client.update_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() + + 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_checkout_settings_empty_call_grpc(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + call.return_value = None + client.delete_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = CheckoutSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + 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_get_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + await client.get_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.GetCheckoutSettingsRequest() + + 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_create_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + await client.create_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.CreateCheckoutSettingsRequest() + + 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_update_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + )) + await client.update_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() + + 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_checkout_settings_empty_call_grpc_asyncio(): + client = CheckoutSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = CheckoutSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_checkout_settings_rest_bad_request(request_type=checkoutsettings.GetCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + 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.get_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.GetCheckoutSettingsRequest, + dict, +]) +def test_get_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request = request_type(**request_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 = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + + # 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 = checkoutsettings.CheckoutSettings.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.get_checkout_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings") as post, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_get_checkout_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = checkoutsettings.GetCheckoutSettingsRequest.pb(checkoutsettings.GetCheckoutSettingsRequest()) + 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + req.return_value.content = return_value + + request = checkoutsettings.GetCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checkoutsettings.CheckoutSettings() + post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata + + client.get_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_checkout_settings_rest_bad_request(request_type=checkoutsettings.CreateCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/programs/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.create_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.CreateCheckoutSettingsRequest, + dict, +]) +def test_create_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/programs/sample2'} + request_init["checkout_settings"] = {'name': 'name_value', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 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 = checkoutsettings.CreateCheckoutSettingsRequest.meta.fields["checkout_settings"] + + 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["checkout_settings"].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["checkout_settings"][field])): + del request_init["checkout_settings"][field][i][subfield] + else: + del request_init["checkout_settings"][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 = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + + # 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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings") as post, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_create_checkout_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = checkoutsettings.CreateCheckoutSettingsRequest.pb(checkoutsettings.CreateCheckoutSettingsRequest()) + 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + req.return_value.content = return_value + + request = checkoutsettings.CreateCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checkoutsettings.CheckoutSettings() + post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata + + client.create_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_checkout_settings_rest_bad_request(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + 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.update_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.UpdateCheckoutSettingsRequest, + dict, +]) +def test_update_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + request_init["checkout_settings"] = {'name': 'accounts/sample1/programs/sample2/checkoutSettings', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 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 = checkoutsettings.UpdateCheckoutSettingsRequest.meta.fields["checkout_settings"] + + 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["checkout_settings"].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["checkout_settings"][field])): + del request_init["checkout_settings"][field][i][subfield] + else: + del request_init["checkout_settings"][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 = checkoutsettings.CheckoutSettings( + name='name_value', + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + + # 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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, checkoutsettings.CheckoutSettings) + assert response.name == 'name_value' + assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] + assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings") as post, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_update_checkout_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = checkoutsettings.UpdateCheckoutSettingsRequest.pb(checkoutsettings.UpdateCheckoutSettingsRequest()) + 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + req.return_value.content = return_value + + request = checkoutsettings.UpdateCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = checkoutsettings.CheckoutSettings() + post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata + + client.update_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_checkout_settings_rest_bad_request(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + 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_checkout_settings(request) + + +@pytest.mark.parametrize("request_type", [ + checkoutsettings.DeleteCheckoutSettingsRequest, + dict, +]) +def test_delete_checkout_settings_rest_call_success(request_type): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request = request_type(**request_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_checkout_settings(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_checkout_settings_rest_interceptors(null_interceptor): + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), + ) + client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "pre_delete_checkout_settings") as pre: + pre.assert_not_called() + pb_message = checkoutsettings.DeleteCheckoutSettingsRequest.pb(checkoutsettings.DeleteCheckoutSettingsRequest()) + 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 = checkoutsettings.DeleteCheckoutSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = CheckoutSettingsServiceClient( + 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_get_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_checkout_settings), + '__call__') as call: + client.get_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.GetCheckoutSettingsRequest() + + 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_create_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_checkout_settings), + '__call__') as call: + client.create_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.CreateCheckoutSettingsRequest() + + 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_update_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_checkout_settings), + '__call__') as call: + client.update_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() + + 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_checkout_settings_empty_call_rest(): + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_checkout_settings), + '__call__') as call: + client.delete_checkout_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CheckoutSettingsServiceGrpcTransport, + ) + +def test_checkout_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CheckoutSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_checkout_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CheckoutSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_checkout_settings', + 'create_checkout_settings', + 'update_checkout_settings', + 'delete_checkout_settings', + ) + 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_checkout_settings_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_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CheckoutSettingsServiceTransport( + 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_checkout_settings_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_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CheckoutSettingsServiceTransport() + adc.assert_called_once() + + +def test_checkout_settings_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) + CheckoutSettingsServiceClient() + 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.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + transports.CheckoutSettingsServiceRestTransport, + ], +) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, grpc_helpers), + (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +def test_checkout_settings_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_checkout_settings_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.CheckoutSettingsServiceRestTransport ( + 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_checkout_settings_service_host_no_port(transport_name): + client = CheckoutSettingsServiceClient( + 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_checkout_settings_service_host_with_port(transport_name): + client = CheckoutSettingsServiceClient( + 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_checkout_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CheckoutSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CheckoutSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_checkout_settings._session + session2 = client2.transport.get_checkout_settings._session + assert session1 != session2 + session1 = client1.transport.create_checkout_settings._session + session2 = client2.transport.create_checkout_settings._session + assert session1 != session2 + session1 = client1.transport.update_checkout_settings._session + session2 = client2.transport.update_checkout_settings._session + assert session1 != session2 + session1 = client1.transport.delete_checkout_settings._session + session2 = client2.transport.delete_checkout_settings._session + assert session1 != session2 +def test_checkout_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CheckoutSettingsServiceGrpcTransport( + 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_checkout_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CheckoutSettingsServiceGrpcAsyncIOTransport( + 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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +def test_checkout_settings_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_checkout_settings_path(): + account = "squid" + program = "clam" + expected = "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) + actual = CheckoutSettingsServiceClient.checkout_settings_path(account, program) + assert expected == actual + + +def test_parse_checkout_settings_path(): + expected = { + "account": "whelk", + "program": "octopus", + } + path = CheckoutSettingsServiceClient.checkout_settings_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_checkout_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CheckoutSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = CheckoutSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = CheckoutSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = CheckoutSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CheckoutSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = CheckoutSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = CheckoutSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = CheckoutSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CheckoutSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = CheckoutSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CheckoutSettingsServiceClient.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.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = CheckoutSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CheckoutSettingsServiceClient.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 = CheckoutSettingsServiceClient( + 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 = CheckoutSettingsServiceAsyncClient( + 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 = CheckoutSettingsServiceClient( + 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 = CheckoutSettingsServiceClient( + 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", [ + (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport), + (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py new file mode 100644 index 000000000000..52282fdb4e6a --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py @@ -0,0 +1,2878 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.email_preferences_service import EmailPreferencesServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.email_preferences_service import EmailPreferencesServiceClient +from google.shopping.merchant_accounts_v1beta.services.email_preferences_service import transports +from google.shopping.merchant_accounts_v1beta.types import emailpreferences +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 EmailPreferencesServiceClient._get_default_mtls_endpoint(None) is None + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EmailPreferencesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, False) is None + assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EmailPreferencesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EmailPreferencesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EmailPreferencesServiceClient._get_universe_domain(None, None) == EmailPreferencesServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient(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 = EmailPreferencesServiceClient(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", [ + (EmailPreferencesServiceClient, "grpc"), + (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), + (EmailPreferencesServiceClient, "rest"), +]) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, "grpc"), + (transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EmailPreferencesServiceRestTransport, "rest"), +]) +def test_email_preferences_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", [ + (EmailPreferencesServiceClient, "grpc"), + (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), + (EmailPreferencesServiceClient, "rest"), +]) +def test_email_preferences_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_email_preferences_service_client_get_transport_class(): + transport = EmailPreferencesServiceClient.get_transport_class() + available_transports = [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceRestTransport, + ] + assert transport in available_transports + + transport = EmailPreferencesServiceClient.get_transport_class("grpc") + assert transport == transports.EmailPreferencesServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), +]) +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +def test_email_preferences_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(EmailPreferencesServiceClient, '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(EmailPreferencesServiceClient, '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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "true"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "false"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "true"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_email_preferences_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", [ + EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient +]) +@mock.patch.object(EmailPreferencesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceAsyncClient)) +def test_email_preferences_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", [ + EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient +]) +@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) +@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +def test_email_preferences_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE + default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EmailPreferencesServiceClient._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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), +]) +def test_email_preferences_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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", None), +]) +def test_email_preferences_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_email_preferences_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EmailPreferencesServiceClient( + 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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_email_preferences_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", [ + emailpreferences.GetEmailPreferencesRequest, + dict, +]) +def test_get_email_preferences(request_type, transport: str = 'grpc'): + client = EmailPreferencesServiceClient( + 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.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + response = client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = emailpreferences.GetEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +def test_get_email_preferences_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 = EmailPreferencesServiceClient( + 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 = emailpreferences.GetEmailPreferencesRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_email_preferences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == emailpreferences.GetEmailPreferencesRequest( + name='name_value', + ) + +def test_get_email_preferences_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 = EmailPreferencesServiceClient( + 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.get_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc + request = {} + client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_email_preferences(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_get_email_preferences_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 = EmailPreferencesServiceAsyncClient( + 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.get_email_preferences in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_email_preferences] = mock_rpc + + request = {} + await client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_email_preferences(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_get_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.GetEmailPreferencesRequest): + client = EmailPreferencesServiceAsyncClient( + 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.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + response = await client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = emailpreferences.GetEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.asyncio +async def test_get_email_preferences_async_from_dict(): + await test_get_email_preferences_async(request_type=dict) + +def test_get_email_preferences_field_headers(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.GetEmailPreferencesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.get_email_preferences(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_get_email_preferences_field_headers_async(): + client = EmailPreferencesServiceAsyncClient( + 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 = emailpreferences.GetEmailPreferencesRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + await client.get_email_preferences(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_get_email_preferences_flattened(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_email_preferences( + 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_get_email_preferences_flattened_error(): + client = EmailPreferencesServiceClient( + 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.get_email_preferences( + emailpreferences.GetEmailPreferencesRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_email_preferences_flattened_async(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_email_preferences( + 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_get_email_preferences_flattened_error_async(): + client = EmailPreferencesServiceAsyncClient( + 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.get_email_preferences( + emailpreferences.GetEmailPreferencesRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + emailpreferences.UpdateEmailPreferencesRequest, + dict, +]) +def test_update_email_preferences(request_type, transport: str = 'grpc'): + client = EmailPreferencesServiceClient( + 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.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + response = client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = emailpreferences.UpdateEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +def test_update_email_preferences_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 = EmailPreferencesServiceClient( + 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 = emailpreferences.UpdateEmailPreferencesRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_email_preferences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == emailpreferences.UpdateEmailPreferencesRequest( + ) + +def test_update_email_preferences_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 = EmailPreferencesServiceClient( + 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.update_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc + request = {} + client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_email_preferences(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_update_email_preferences_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 = EmailPreferencesServiceAsyncClient( + 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.update_email_preferences in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_email_preferences] = mock_rpc + + request = {} + await client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_email_preferences(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_update_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.UpdateEmailPreferencesRequest): + client = EmailPreferencesServiceAsyncClient( + 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.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + response = await client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = emailpreferences.UpdateEmailPreferencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.asyncio +async def test_update_email_preferences_async_from_dict(): + await test_update_email_preferences_async(request_type=dict) + +def test_update_email_preferences_field_headers(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.UpdateEmailPreferencesRequest() + + request.email_preferences.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.update_email_preferences(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', + 'email_preferences.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_email_preferences_field_headers_async(): + client = EmailPreferencesServiceAsyncClient( + 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 = emailpreferences.UpdateEmailPreferencesRequest() + + request.email_preferences.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + await client.update_email_preferences(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', + 'email_preferences.name=name_value', + ) in kw['metadata'] + + +def test_update_email_preferences_flattened(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_email_preferences( + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].email_preferences + mock_val = emailpreferences.EmailPreferences(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_email_preferences_flattened_error(): + client = EmailPreferencesServiceClient( + 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.update_email_preferences( + emailpreferences.UpdateEmailPreferencesRequest(), + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_email_preferences_flattened_async(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = emailpreferences.EmailPreferences() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_email_preferences( + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].email_preferences + mock_val = emailpreferences.EmailPreferences(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_email_preferences_flattened_error_async(): + client = EmailPreferencesServiceAsyncClient( + 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.update_email_preferences( + emailpreferences.UpdateEmailPreferencesRequest(), + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_email_preferences_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 = EmailPreferencesServiceClient( + 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.get_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc + + request = {} + client.get_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_email_preferences(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_get_email_preferences_rest_required_fields(request_type=emailpreferences.GetEmailPreferencesRequest): + transport_class = transports.EmailPreferencesServiceRestTransport + + 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()).get_email_preferences._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_email_preferences._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 = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = emailpreferences.EmailPreferences() + # 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 = emailpreferences.EmailPreferences.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.get_email_preferences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_email_preferences_rest_unset_required_fields(): + transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_email_preferences._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_email_preferences_rest_flattened(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.EmailPreferences() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + + # 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 + # Convert return value to protobuf type + return_value = emailpreferences.EmailPreferences.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.get_email_preferences(**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/accounts/v1beta/{name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) + + +def test_get_email_preferences_rest_flattened_error(transport: str = 'rest'): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_email_preferences( + emailpreferences.GetEmailPreferencesRequest(), + name='name_value', + ) + + +def test_update_email_preferences_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 = EmailPreferencesServiceClient( + 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.update_email_preferences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc + + request = {} + client.update_email_preferences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_email_preferences(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_update_email_preferences_rest_required_fields(request_type=emailpreferences.UpdateEmailPreferencesRequest): + transport_class = transports.EmailPreferencesServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = emailpreferences.EmailPreferences() + # 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': "patch", + '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 = emailpreferences.EmailPreferences.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.update_email_preferences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_email_preferences_rest_unset_required_fields(): + transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_email_preferences._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("emailPreferences", "updateMask", ))) + + +def test_update_email_preferences_rest_flattened(): + client = EmailPreferencesServiceClient( + 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 = emailpreferences.EmailPreferences() + + # get arguments that satisfy an http rule for this method + sample_request = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + + # get truthy value for each flattened field + mock_args = dict( + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = emailpreferences.EmailPreferences.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.update_email_preferences(**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/accounts/v1beta/{email_preferences.name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) + + +def test_update_email_preferences_rest_flattened_error(transport: str = 'rest'): + client = EmailPreferencesServiceClient( + 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.update_email_preferences( + emailpreferences.UpdateEmailPreferencesRequest(), + email_preferences=emailpreferences.EmailPreferences(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + 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 = EmailPreferencesServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EmailPreferencesServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EmailPreferencesServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EmailPreferencesServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EmailPreferencesServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + transports.EmailPreferencesServiceRestTransport, +]) +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 = EmailPreferencesServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EmailPreferencesServiceClient( + 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_get_email_preferences_empty_call_grpc(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.get_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.GetEmailPreferencesRequest() + + 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_update_email_preferences_empty_call_grpc(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + call.return_value = emailpreferences.EmailPreferences() + client.update_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.UpdateEmailPreferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EmailPreferencesServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EmailPreferencesServiceAsyncClient( + 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_get_email_preferences_empty_call_grpc_asyncio(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + await client.get_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.GetEmailPreferencesRequest() + + 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_update_email_preferences_empty_call_grpc_asyncio(): + client = EmailPreferencesServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + )) + await client.update_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.UpdateEmailPreferencesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EmailPreferencesServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_email_preferences_rest_bad_request(request_type=emailpreferences.GetEmailPreferencesRequest): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + 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.get_email_preferences(request) + + +@pytest.mark.parametrize("request_type", [ + emailpreferences.GetEmailPreferencesRequest, + dict, +]) +def test_get_email_preferences_rest_call_success(request_type): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + request = request_type(**request_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 = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + + # 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 = emailpreferences.EmailPreferences.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.get_email_preferences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_email_preferences_rest_interceptors(null_interceptor): + transport = transports.EmailPreferencesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), + ) + client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences") as post, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_get_email_preferences") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = emailpreferences.GetEmailPreferencesRequest.pb(emailpreferences.GetEmailPreferencesRequest()) + 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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) + req.return_value.content = return_value + + request = emailpreferences.GetEmailPreferencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = emailpreferences.EmailPreferences() + post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata + + client.get_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_email_preferences_rest_bad_request(request_type=emailpreferences.UpdateEmailPreferencesRequest): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + 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.update_email_preferences(request) + + +@pytest.mark.parametrize("request_type", [ + emailpreferences.UpdateEmailPreferencesRequest, + dict, +]) +def test_update_email_preferences_rest_call_success(request_type): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + request_init["email_preferences"] = {'name': 'accounts/sample1/users/sample2/emailPreferences', 'news_and_tips': 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 = emailpreferences.UpdateEmailPreferencesRequest.meta.fields["email_preferences"] + + 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["email_preferences"].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["email_preferences"][field])): + del request_init["email_preferences"][field][i][subfield] + else: + del request_init["email_preferences"][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 = emailpreferences.EmailPreferences( + name='name_value', + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + + # 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 = emailpreferences.EmailPreferences.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.update_email_preferences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, emailpreferences.EmailPreferences) + assert response.name == 'name_value' + assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_email_preferences_rest_interceptors(null_interceptor): + transport = transports.EmailPreferencesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), + ) + client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences") as post, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_update_email_preferences") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = emailpreferences.UpdateEmailPreferencesRequest.pb(emailpreferences.UpdateEmailPreferencesRequest()) + 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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) + req.return_value.content = return_value + + request = emailpreferences.UpdateEmailPreferencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = emailpreferences.EmailPreferences() + post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata + + client.update_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = EmailPreferencesServiceClient( + 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_get_email_preferences_empty_call_rest(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_email_preferences), + '__call__') as call: + client.get_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.GetEmailPreferencesRequest() + + 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_update_email_preferences_empty_call_rest(): + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_email_preferences), + '__call__') as call: + client.update_email_preferences(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = emailpreferences.UpdateEmailPreferencesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EmailPreferencesServiceGrpcTransport, + ) + +def test_email_preferences_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EmailPreferencesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_email_preferences_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EmailPreferencesServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_email_preferences', + 'update_email_preferences', + ) + 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_email_preferences_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_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EmailPreferencesServiceTransport( + 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_email_preferences_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_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EmailPreferencesServiceTransport() + adc.assert_called_once() + + +def test_email_preferences_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) + EmailPreferencesServiceClient() + 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.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + ], +) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + transports.EmailPreferencesServiceRestTransport, + ], +) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, grpc_helpers), + (transports.EmailPreferencesServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +def test_email_preferences_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_email_preferences_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.EmailPreferencesServiceRestTransport ( + 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_email_preferences_service_host_no_port(transport_name): + client = EmailPreferencesServiceClient( + 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_email_preferences_service_host_with_port(transport_name): + client = EmailPreferencesServiceClient( + 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_email_preferences_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EmailPreferencesServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EmailPreferencesServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_email_preferences._session + session2 = client2.transport.get_email_preferences._session + assert session1 != session2 + session1 = client1.transport.update_email_preferences._session + session2 = client2.transport.update_email_preferences._session + assert session1 != session2 +def test_email_preferences_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EmailPreferencesServiceGrpcTransport( + 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_email_preferences_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EmailPreferencesServiceGrpcAsyncIOTransport( + 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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +def test_email_preferences_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_email_preferences_path(): + account = "squid" + email = "clam" + expected = "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) + actual = EmailPreferencesServiceClient.email_preferences_path(account, email) + assert expected == actual + + +def test_parse_email_preferences_path(): + expected = { + "account": "whelk", + "email": "octopus", + } + path = EmailPreferencesServiceClient.email_preferences_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_email_preferences_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EmailPreferencesServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = EmailPreferencesServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = EmailPreferencesServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = EmailPreferencesServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EmailPreferencesServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = EmailPreferencesServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = EmailPreferencesServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = EmailPreferencesServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EmailPreferencesServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = EmailPreferencesServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EmailPreferencesServiceClient.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.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: + client = EmailPreferencesServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = EmailPreferencesServiceClient.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 = EmailPreferencesServiceClient( + 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 = EmailPreferencesServiceAsyncClient( + 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 = EmailPreferencesServiceClient( + 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 = EmailPreferencesServiceClient( + 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", [ + (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport), + (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py new file mode 100644 index 000000000000..0bd0f6a1ae38 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py @@ -0,0 +1,3072 @@ +# -*- 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 empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import GbpAccountsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import GbpAccountsServiceClient +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import pagers +from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import transports +from google.shopping.merchant_accounts_v1beta.types import gbpaccounts +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 GbpAccountsServiceClient._get_default_mtls_endpoint(None) is None + assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert GbpAccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert GbpAccountsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + GbpAccountsServiceClient._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 GbpAccountsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + GbpAccountsServiceClient._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 GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, False) is None + assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert GbpAccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + assert GbpAccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert GbpAccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert GbpAccountsServiceClient._get_universe_domain(None, None) == GbpAccountsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + GbpAccountsServiceClient._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 = GbpAccountsServiceClient(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 = GbpAccountsServiceClient(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", [ + (GbpAccountsServiceClient, "grpc"), + (GbpAccountsServiceAsyncClient, "grpc_asyncio"), + (GbpAccountsServiceClient, "rest"), +]) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, "grpc"), + (transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GbpAccountsServiceRestTransport, "rest"), +]) +def test_gbp_accounts_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", [ + (GbpAccountsServiceClient, "grpc"), + (GbpAccountsServiceAsyncClient, "grpc_asyncio"), + (GbpAccountsServiceClient, "rest"), +]) +def test_gbp_accounts_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_gbp_accounts_service_client_get_transport_class(): + transport = GbpAccountsServiceClient.get_transport_class() + available_transports = [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceRestTransport, + ] + assert transport in available_transports + + transport = GbpAccountsServiceClient.get_transport_class("grpc") + assert transport == transports.GbpAccountsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), +]) +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +def test_gbp_accounts_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(GbpAccountsServiceClient, '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(GbpAccountsServiceClient, '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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "true"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "false"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "true"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_gbp_accounts_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", [ + GbpAccountsServiceClient, GbpAccountsServiceAsyncClient +]) +@mock.patch.object(GbpAccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceAsyncClient)) +def test_gbp_accounts_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", [ + GbpAccountsServiceClient, GbpAccountsServiceAsyncClient +]) +@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) +@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +def test_gbp_accounts_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE + default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = GbpAccountsServiceClient._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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), +]) +def test_gbp_accounts_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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", None), +]) +def test_gbp_accounts_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_gbp_accounts_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = GbpAccountsServiceClient( + 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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_gbp_accounts_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", [ + gbpaccounts.ListGbpAccountsRequest, + dict, +]) +def test_list_gbp_accounts(request_type, transport: str = 'grpc'): + client = GbpAccountsServiceClient( + 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_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.ListGbpAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gbpaccounts.ListGbpAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGbpAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_gbp_accounts_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 = GbpAccountsServiceClient( + 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 = gbpaccounts.ListGbpAccountsRequest( + 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_gbp_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_gbp_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gbpaccounts.ListGbpAccountsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_gbp_accounts_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 = GbpAccountsServiceClient( + 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_gbp_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_gbp_accounts] = mock_rpc + request = {} + client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_gbp_accounts(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_gbp_accounts_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 = GbpAccountsServiceAsyncClient( + 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_gbp_accounts 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_gbp_accounts] = mock_rpc + + request = {} + await client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_gbp_accounts(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_gbp_accounts_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.ListGbpAccountsRequest): + client = GbpAccountsServiceAsyncClient( + 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_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gbpaccounts.ListGbpAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGbpAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_gbp_accounts_async_from_dict(): + await test_list_gbp_accounts_async(request_type=dict) + +def test_list_gbp_accounts_field_headers(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.ListGbpAccountsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + call.return_value = gbpaccounts.ListGbpAccountsResponse() + client.list_gbp_accounts(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_gbp_accounts_field_headers_async(): + client = GbpAccountsServiceAsyncClient( + 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 = gbpaccounts.ListGbpAccountsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) + await client.list_gbp_accounts(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_gbp_accounts_flattened(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.ListGbpAccountsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_gbp_accounts( + 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_gbp_accounts_flattened_error(): + client = GbpAccountsServiceClient( + 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_gbp_accounts( + gbpaccounts.ListGbpAccountsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_gbp_accounts_flattened_async(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.ListGbpAccountsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_gbp_accounts( + 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_gbp_accounts_flattened_error_async(): + client = GbpAccountsServiceAsyncClient( + 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_gbp_accounts( + gbpaccounts.ListGbpAccountsRequest(), + parent='parent_value', + ) + + +def test_list_gbp_accounts_pager(transport_name: str = "grpc"): + client = GbpAccountsServiceClient( + 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_gbp_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_gbp_accounts(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, gbpaccounts.GbpAccount) + for i in results) +def test_list_gbp_accounts_pages(transport_name: str = "grpc"): + client = GbpAccountsServiceClient( + 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_gbp_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + RuntimeError, + ) + pages = list(client.list_gbp_accounts(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_gbp_accounts_async_pager(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_gbp_accounts(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, gbpaccounts.GbpAccount) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_gbp_accounts_async_pages(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + 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_gbp_accounts(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", [ + gbpaccounts.LinkGbpAccountRequest, + dict, +]) +def test_link_gbp_account(request_type, transport: str = 'grpc'): + client = GbpAccountsServiceClient( + 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.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.LinkGbpAccountResponse( + ) + response = client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gbpaccounts.LinkGbpAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) + + +def test_link_gbp_account_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 = GbpAccountsServiceClient( + 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 = gbpaccounts.LinkGbpAccountRequest( + parent='parent_value', + gbp_email='gbp_email_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.link_gbp_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gbpaccounts.LinkGbpAccountRequest( + parent='parent_value', + gbp_email='gbp_email_value', + ) + +def test_link_gbp_account_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 = GbpAccountsServiceClient( + 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.link_gbp_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc + request = {} + client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_gbp_account(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_link_gbp_account_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 = GbpAccountsServiceAsyncClient( + 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.link_gbp_account 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.link_gbp_account] = mock_rpc + + request = {} + await client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.link_gbp_account(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_link_gbp_account_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.LinkGbpAccountRequest): + client = GbpAccountsServiceAsyncClient( + 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.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( + )) + response = await client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gbpaccounts.LinkGbpAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) + + +@pytest.mark.asyncio +async def test_link_gbp_account_async_from_dict(): + await test_link_gbp_account_async(request_type=dict) + +def test_link_gbp_account_field_headers(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.LinkGbpAccountRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value = gbpaccounts.LinkGbpAccountResponse() + client.link_gbp_account(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_link_gbp_account_field_headers_async(): + client = GbpAccountsServiceAsyncClient( + 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 = gbpaccounts.LinkGbpAccountRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) + await client.link_gbp_account(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_link_gbp_account_flattened(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.LinkGbpAccountResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.link_gbp_account( + 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_link_gbp_account_flattened_error(): + client = GbpAccountsServiceClient( + 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.link_gbp_account( + gbpaccounts.LinkGbpAccountRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_link_gbp_account_flattened_async(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gbpaccounts.LinkGbpAccountResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.link_gbp_account( + 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_link_gbp_account_flattened_error_async(): + client = GbpAccountsServiceAsyncClient( + 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.link_gbp_account( + gbpaccounts.LinkGbpAccountRequest(), + parent='parent_value', + ) + + +def test_list_gbp_accounts_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 = GbpAccountsServiceClient( + 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_gbp_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_gbp_accounts] = mock_rpc + + request = {} + client.list_gbp_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_gbp_accounts(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_gbp_accounts_rest_required_fields(request_type=gbpaccounts.ListGbpAccountsRequest): + transport_class = transports.GbpAccountsServiceRestTransport + + 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_gbp_accounts._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_gbp_accounts._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 = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.ListGbpAccountsResponse() + # 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_gbp_accounts_rest_unset_required_fields(): + transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_gbp_accounts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_gbp_accounts_rest_flattened(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.ListGbpAccountsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(**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/accounts/v1beta/{parent=accounts/*}/gbpAccounts" % client.transport._host, args[1]) + + +def test_list_gbp_accounts_rest_flattened_error(transport: str = 'rest'): + client = GbpAccountsServiceClient( + 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_gbp_accounts( + gbpaccounts.ListGbpAccountsRequest(), + parent='parent_value', + ) + + +def test_list_gbp_accounts_rest_pager(transport: str = 'rest'): + client = GbpAccountsServiceClient( + 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 = ( + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + next_page_token='abc', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[], + next_page_token='def', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + ], + next_page_token='ghi', + ), + gbpaccounts.ListGbpAccountsResponse( + gbp_accounts=[ + gbpaccounts.GbpAccount(), + gbpaccounts.GbpAccount(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(gbpaccounts.ListGbpAccountsResponse.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'} + + pager = client.list_gbp_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, gbpaccounts.GbpAccount) + for i in results) + + pages = list(client.list_gbp_accounts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_link_gbp_account_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 = GbpAccountsServiceClient( + 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.link_gbp_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc + + request = {} + client.link_gbp_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_gbp_account(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_link_gbp_account_rest_required_fields(request_type=gbpaccounts.LinkGbpAccountRequest): + transport_class = transports.GbpAccountsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["gbp_email"] = "" + 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()).link_gbp_account._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["gbpEmail"] = 'gbp_email_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_gbp_account._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 "gbpEmail" in jsonified_request + assert jsonified_request["gbpEmail"] == 'gbp_email_value' + + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.LinkGbpAccountResponse() + # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_link_gbp_account_rest_unset_required_fields(): + transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.link_gbp_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "gbpEmail", ))) + + +def test_link_gbp_account_rest_flattened(): + client = GbpAccountsServiceClient( + 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 = gbpaccounts.LinkGbpAccountResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(**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/accounts/v1beta/{parent=accounts/*}/gbpAccounts:linkGbpAccount" % client.transport._host, args[1]) + + +def test_link_gbp_account_rest_flattened_error(transport: str = 'rest'): + client = GbpAccountsServiceClient( + 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.link_gbp_account( + gbpaccounts.LinkGbpAccountRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + 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 = GbpAccountsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GbpAccountsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GbpAccountsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GbpAccountsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GbpAccountsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + transports.GbpAccountsServiceRestTransport, +]) +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 = GbpAccountsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GbpAccountsServiceClient( + 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_gbp_accounts_empty_call_grpc(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + call.return_value = gbpaccounts.ListGbpAccountsResponse() + client.list_gbp_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.ListGbpAccountsRequest() + + 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_link_gbp_account_empty_call_grpc(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + call.return_value = gbpaccounts.LinkGbpAccountResponse() + client.link_gbp_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.LinkGbpAccountRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GbpAccountsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GbpAccountsServiceAsyncClient( + 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_gbp_accounts_empty_call_grpc_asyncio(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( + next_page_token='next_page_token_value', + )) + await client.list_gbp_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.ListGbpAccountsRequest() + + 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_link_gbp_account_empty_call_grpc_asyncio(): + client = GbpAccountsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( + )) + await client.link_gbp_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.LinkGbpAccountRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GbpAccountsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_gbp_accounts_rest_bad_request(request_type=gbpaccounts.ListGbpAccountsRequest): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_gbp_accounts(request) + + +@pytest.mark.parametrize("request_type", [ + gbpaccounts.ListGbpAccountsRequest, + dict, +]) +def test_list_gbp_accounts_rest_call_success(request_type): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.ListGbpAccountsResponse( + 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGbpAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_gbp_accounts_rest_interceptors(null_interceptor): + transport = transports.GbpAccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), + ) + client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts") as post, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_list_gbp_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gbpaccounts.ListGbpAccountsRequest.pb(gbpaccounts.ListGbpAccountsRequest()) + 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 = gbpaccounts.ListGbpAccountsResponse.to_json(gbpaccounts.ListGbpAccountsResponse()) + req.return_value.content = return_value + + request = gbpaccounts.ListGbpAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gbpaccounts.ListGbpAccountsResponse() + post_with_metadata.return_value = gbpaccounts.ListGbpAccountsResponse(), metadata + + client.list_gbp_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_link_gbp_account_rest_bad_request(request_type=gbpaccounts.LinkGbpAccountRequest): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.link_gbp_account(request) + + +@pytest.mark.parametrize("request_type", [ + gbpaccounts.LinkGbpAccountRequest, + dict, +]) +def test_link_gbp_account_rest_call_success(request_type): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gbpaccounts.LinkGbpAccountResponse( + ) + + # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_link_gbp_account_rest_interceptors(null_interceptor): + transport = transports.GbpAccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), + ) + client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_link_gbp_account") as post, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_link_gbp_account_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_link_gbp_account") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gbpaccounts.LinkGbpAccountRequest.pb(gbpaccounts.LinkGbpAccountRequest()) + 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 = gbpaccounts.LinkGbpAccountResponse.to_json(gbpaccounts.LinkGbpAccountResponse()) + req.return_value.content = return_value + + request = gbpaccounts.LinkGbpAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gbpaccounts.LinkGbpAccountResponse() + post_with_metadata.return_value = gbpaccounts.LinkGbpAccountResponse(), metadata + + client.link_gbp_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = GbpAccountsServiceClient( + 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_gbp_accounts_empty_call_rest(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_gbp_accounts), + '__call__') as call: + client.list_gbp_accounts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.ListGbpAccountsRequest() + + 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_link_gbp_account_empty_call_rest(): + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_gbp_account), + '__call__') as call: + client.link_gbp_account(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gbpaccounts.LinkGbpAccountRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GbpAccountsServiceGrpcTransport, + ) + +def test_gbp_accounts_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GbpAccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_gbp_accounts_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.GbpAccountsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_gbp_accounts', + 'link_gbp_account', + ) + 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_gbp_accounts_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_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GbpAccountsServiceTransport( + 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_gbp_accounts_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_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GbpAccountsServiceTransport() + adc.assert_called_once() + + +def test_gbp_accounts_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) + GbpAccountsServiceClient() + 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.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + ], +) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + transports.GbpAccountsServiceRestTransport, + ], +) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, grpc_helpers), + (transports.GbpAccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +def test_gbp_accounts_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_gbp_accounts_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.GbpAccountsServiceRestTransport ( + 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_gbp_accounts_service_host_no_port(transport_name): + client = GbpAccountsServiceClient( + 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_gbp_accounts_service_host_with_port(transport_name): + client = GbpAccountsServiceClient( + 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_gbp_accounts_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GbpAccountsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GbpAccountsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_gbp_accounts._session + session2 = client2.transport.list_gbp_accounts._session + assert session1 != session2 + session1 = client1.transport.link_gbp_account._session + session2 = client2.transport.link_gbp_account._session + assert session1 != session2 +def test_gbp_accounts_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GbpAccountsServiceGrpcTransport( + 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_gbp_accounts_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GbpAccountsServiceGrpcAsyncIOTransport( + 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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +def test_gbp_accounts_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = GbpAccountsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = GbpAccountsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_account_path(path) + assert expected == actual + +def test_gbp_account_path(): + account = "whelk" + gbp_account = "octopus" + expected = "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) + actual = GbpAccountsServiceClient.gbp_account_path(account, gbp_account) + assert expected == actual + + +def test_parse_gbp_account_path(): + expected = { + "account": "oyster", + "gbp_account": "nudibranch", + } + path = GbpAccountsServiceClient.gbp_account_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_gbp_account_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = GbpAccountsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = GbpAccountsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = GbpAccountsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = GbpAccountsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = GbpAccountsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = GbpAccountsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = GbpAccountsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = GbpAccountsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = GbpAccountsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GbpAccountsServiceClient.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.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: + client = GbpAccountsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = GbpAccountsServiceClient.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 = GbpAccountsServiceClient( + 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 = GbpAccountsServiceAsyncClient( + 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 = GbpAccountsServiceClient( + 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 = GbpAccountsServiceClient( + 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", [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport), + (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py new file mode 100644 index 000000000000..942d0a7a36a6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py @@ -0,0 +1,3965 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.homepage_service import HomepageServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.homepage_service import HomepageServiceClient +from google.shopping.merchant_accounts_v1beta.services.homepage_service import transports +from google.shopping.merchant_accounts_v1beta.types import homepage +from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage +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 HomepageServiceClient._get_default_mtls_endpoint(None) is None + assert HomepageServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert HomepageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HomepageServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + HomepageServiceClient._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 HomepageServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert HomepageServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + HomepageServiceClient._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 HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, False) is None + assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = HomepageServiceClient._DEFAULT_UNIVERSE + default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert HomepageServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + assert HomepageServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + HomepageServiceClient._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 HomepageServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert HomepageServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert HomepageServiceClient._get_universe_domain(None, None) == HomepageServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + HomepageServiceClient._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 = HomepageServiceClient(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 = HomepageServiceClient(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", [ + (HomepageServiceClient, "grpc"), + (HomepageServiceAsyncClient, "grpc_asyncio"), + (HomepageServiceClient, "rest"), +]) +def test_homepage_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.HomepageServiceGrpcTransport, "grpc"), + (transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.HomepageServiceRestTransport, "rest"), +]) +def test_homepage_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", [ + (HomepageServiceClient, "grpc"), + (HomepageServiceAsyncClient, "grpc_asyncio"), + (HomepageServiceClient, "rest"), +]) +def test_homepage_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_homepage_service_client_get_transport_class(): + transport = HomepageServiceClient.get_transport_class() + available_transports = [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceRestTransport, + ] + assert transport in available_transports + + transport = HomepageServiceClient.get_transport_class("grpc") + assert transport == transports.HomepageServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), +]) +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +def test_homepage_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(HomepageServiceClient, '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(HomepageServiceClient, '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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "true"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "false"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "true"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_homepage_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", [ + HomepageServiceClient, HomepageServiceAsyncClient +]) +@mock.patch.object(HomepageServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceAsyncClient)) +def test_homepage_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", [ + HomepageServiceClient, HomepageServiceAsyncClient +]) +@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) +@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +def test_homepage_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = HomepageServiceClient._DEFAULT_UNIVERSE + default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = HomepageServiceClient._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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), +]) +def test_homepage_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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", None), +]) +def test_homepage_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_homepage_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.homepage_service.transports.HomepageServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = HomepageServiceClient( + 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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_homepage_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", [ + homepage.GetHomepageRequest, + dict, +]) +def test_get_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = homepage.GetHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_get_homepage_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 = HomepageServiceClient( + 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 = homepage.GetHomepageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == homepage.GetHomepageRequest( + name='name_value', + ) + +def test_get_homepage_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 = HomepageServiceClient( + 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.get_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc + request = {} + client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_homepage(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_get_homepage_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 = HomepageServiceAsyncClient( + 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.get_homepage in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_homepage] = mock_rpc + + request = {} + await client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_homepage(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_get_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.GetHomepageRequest): + client = HomepageServiceAsyncClient( + 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.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = homepage.GetHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_get_homepage_async_from_dict(): + await test_get_homepage_async(request_type=dict) + +def test_get_homepage_field_headers(): + client = HomepageServiceClient( + 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 = homepage.GetHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.get_homepage(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_get_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = homepage.GetHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + await client.get_homepage(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_get_homepage_flattened(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_homepage( + 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_get_homepage_flattened_error(): + client = HomepageServiceClient( + 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.get_homepage( + homepage.GetHomepageRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_homepage_flattened_async(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_homepage( + 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_get_homepage_flattened_error_async(): + client = HomepageServiceAsyncClient( + 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.get_homepage( + homepage.GetHomepageRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_homepage.UpdateHomepageRequest, + dict, +]) +def test_update_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_homepage.UpdateHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_update_homepage_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 = HomepageServiceClient( + 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 = gsma_homepage.UpdateHomepageRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_homepage.UpdateHomepageRequest( + ) + +def test_update_homepage_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 = HomepageServiceClient( + 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.update_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc + request = {} + client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_homepage(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_update_homepage_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 = HomepageServiceAsyncClient( + 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.update_homepage in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_homepage] = mock_rpc + + request = {} + await client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_homepage(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_update_homepage_async(transport: str = 'grpc_asyncio', request_type=gsma_homepage.UpdateHomepageRequest): + client = HomepageServiceAsyncClient( + 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.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_homepage.UpdateHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_update_homepage_async_from_dict(): + await test_update_homepage_async(request_type=dict) + +def test_update_homepage_field_headers(): + client = HomepageServiceClient( + 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 = gsma_homepage.UpdateHomepageRequest() + + request.homepage.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value = gsma_homepage.Homepage() + client.update_homepage(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', + 'homepage.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = gsma_homepage.UpdateHomepageRequest() + + request.homepage.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) + await client.update_homepage(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', + 'homepage.name=name_value', + ) in kw['metadata'] + + +def test_update_homepage_flattened(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_homepage.Homepage() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_homepage( + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].homepage + mock_val = gsma_homepage.Homepage(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_homepage_flattened_error(): + client = HomepageServiceClient( + 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.update_homepage( + gsma_homepage.UpdateHomepageRequest(), + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_homepage_flattened_async(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_homepage.Homepage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_homepage( + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].homepage + mock_val = gsma_homepage.Homepage(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_homepage_flattened_error_async(): + client = HomepageServiceAsyncClient( + 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.update_homepage( + gsma_homepage.UpdateHomepageRequest(), + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + homepage.ClaimHomepageRequest, + dict, +]) +def test_claim_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.claim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = homepage.ClaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_claim_homepage_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 = HomepageServiceClient( + 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 = homepage.ClaimHomepageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.claim_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == homepage.ClaimHomepageRequest( + name='name_value', + ) + +def test_claim_homepage_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 = HomepageServiceClient( + 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.claim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc + request = {} + client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.claim_homepage(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_claim_homepage_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 = HomepageServiceAsyncClient( + 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.claim_homepage 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.claim_homepage] = mock_rpc + + request = {} + await client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.claim_homepage(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_claim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.ClaimHomepageRequest): + client = HomepageServiceAsyncClient( + 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.claim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = homepage.ClaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_claim_homepage_async_from_dict(): + await test_claim_homepage_async(request_type=dict) + +def test_claim_homepage_field_headers(): + client = HomepageServiceClient( + 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 = homepage.ClaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.claim_homepage(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_claim_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = homepage.ClaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + await client.claim_homepage(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'] + + +@pytest.mark.parametrize("request_type", [ + homepage.UnclaimHomepageRequest, + dict, +]) +def test_unclaim_homepage(request_type, transport: str = 'grpc'): + client = HomepageServiceClient( + 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.unclaim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + response = client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = homepage.UnclaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +def test_unclaim_homepage_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 = HomepageServiceClient( + 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 = homepage.UnclaimHomepageRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.unclaim_homepage(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == homepage.UnclaimHomepageRequest( + name='name_value', + ) + +def test_unclaim_homepage_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 = HomepageServiceClient( + 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.unclaim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc + request = {} + client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.unclaim_homepage(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_unclaim_homepage_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 = HomepageServiceAsyncClient( + 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.unclaim_homepage 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.unclaim_homepage] = mock_rpc + + request = {} + await client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.unclaim_homepage(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_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.UnclaimHomepageRequest): + client = HomepageServiceAsyncClient( + 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.unclaim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + response = await client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = homepage.UnclaimHomepageRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.asyncio +async def test_unclaim_homepage_async_from_dict(): + await test_unclaim_homepage_async(request_type=dict) + +def test_unclaim_homepage_field_headers(): + client = HomepageServiceClient( + 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 = homepage.UnclaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.unclaim_homepage(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_unclaim_homepage_field_headers_async(): + client = HomepageServiceAsyncClient( + 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 = homepage.UnclaimHomepageRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) + await client.unclaim_homepage(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_get_homepage_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 = HomepageServiceClient( + 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.get_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc + + request = {} + client.get_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_homepage(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_get_homepage_rest_required_fields(request_type=homepage.GetHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + 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()).get_homepage._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_homepage._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 = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = homepage.Homepage() + # 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 = homepage.Homepage.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.get_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_homepage_rest_flattened(): + client = HomepageServiceClient( + 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 = homepage.Homepage() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/homepage'} + + # 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 + # Convert return value to protobuf type + return_value = homepage.Homepage.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.get_homepage(**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/accounts/v1beta/{name=accounts/*/homepage}" % client.transport._host, args[1]) + + +def test_get_homepage_rest_flattened_error(transport: str = 'rest'): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_homepage( + homepage.GetHomepageRequest(), + name='name_value', + ) + + +def test_update_homepage_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 = HomepageServiceClient( + 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.update_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc + + request = {} + client.update_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_homepage(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_update_homepage_rest_required_fields(request_type=gsma_homepage.UpdateHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_homepage.Homepage() + # 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': "patch", + '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 = gsma_homepage.Homepage.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.update_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("homepage", "updateMask", ))) + + +def test_update_homepage_rest_flattened(): + client = HomepageServiceClient( + 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 = gsma_homepage.Homepage() + + # get arguments that satisfy an http rule for this method + sample_request = {'homepage': {'name': 'accounts/sample1/homepage'}} + + # get truthy value for each flattened field + mock_args = dict( + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_homepage.Homepage.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.update_homepage(**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/accounts/v1beta/{homepage.name=accounts/*/homepage}" % client.transport._host, args[1]) + + +def test_update_homepage_rest_flattened_error(transport: str = 'rest'): + client = HomepageServiceClient( + 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.update_homepage( + gsma_homepage.UpdateHomepageRequest(), + homepage=gsma_homepage.Homepage(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_claim_homepage_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 = HomepageServiceClient( + 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.claim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc + + request = {} + client.claim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.claim_homepage(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_claim_homepage_rest_required_fields(request_type=homepage.ClaimHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + 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()).claim_homepage._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()).claim_homepage._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 = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = homepage.Homepage() + # 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 = homepage.Homepage.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.claim_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_claim_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.claim_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_unclaim_homepage_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 = HomepageServiceClient( + 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.unclaim_homepage in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc + + request = {} + client.unclaim_homepage(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.unclaim_homepage(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_unclaim_homepage_rest_required_fields(request_type=homepage.UnclaimHomepageRequest): + transport_class = transports.HomepageServiceRestTransport + + 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()).unclaim_homepage._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()).unclaim_homepage._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 = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = homepage.Homepage() + # 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 = homepage.Homepage.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.unclaim_homepage(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_unclaim_homepage_rest_unset_required_fields(): + transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.unclaim_homepage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HomepageServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HomepageServiceClient( + 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 = HomepageServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HomepageServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = HomepageServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.HomepageServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.HomepageServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + transports.HomepageServiceRestTransport, +]) +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 = HomepageServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = HomepageServiceClient( + 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_get_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.get_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.GetHomepageRequest() + + 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_update_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + call.return_value = gsma_homepage.Homepage() + client.update_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_homepage.UpdateHomepageRequest() + + 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_claim_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.claim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.ClaimHomepageRequest() + + 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_unclaim_homepage_empty_call_grpc(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + call.return_value = homepage.Homepage() + client.unclaim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.UnclaimHomepageRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = HomepageServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = HomepageServiceAsyncClient( + 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_get_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.get_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.GetHomepageRequest() + + 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_update_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.update_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_homepage.UpdateHomepageRequest() + + 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_claim_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.claim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.ClaimHomepageRequest() + + 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_unclaim_homepage_empty_call_grpc_asyncio(): + client = HomepageServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + )) + await client.unclaim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.UnclaimHomepageRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = HomepageServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_homepage_rest_bad_request(request_type=homepage.GetHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + 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.get_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + homepage.GetHomepageRequest, + dict, +]) +def test_get_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + request = request_type(**request_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 = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = homepage.Homepage.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.get_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_get_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_get_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_get_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = homepage.GetHomepageRequest.pb(homepage.GetHomepageRequest()) + 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 = homepage.Homepage.to_json(homepage.Homepage()) + req.return_value.content = return_value + + request = homepage.GetHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = homepage.Homepage() + post_with_metadata.return_value = homepage.Homepage(), metadata + + client.get_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_homepage_rest_bad_request(request_type=gsma_homepage.UpdateHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} + 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.update_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_homepage.UpdateHomepageRequest, + dict, +]) +def test_update_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} + request_init["homepage"] = {'name': 'accounts/sample1/homepage', 'uri': 'uri_value', 'claimed': True} + # 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 = gsma_homepage.UpdateHomepageRequest.meta.fields["homepage"] + + 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["homepage"].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["homepage"][field])): + del request_init["homepage"][field][i][subfield] + else: + del request_init["homepage"][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 = gsma_homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = gsma_homepage.Homepage.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.update_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_update_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_update_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_update_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_homepage.UpdateHomepageRequest.pb(gsma_homepage.UpdateHomepageRequest()) + 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 = gsma_homepage.Homepage.to_json(gsma_homepage.Homepage()) + req.return_value.content = return_value + + request = gsma_homepage.UpdateHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_homepage.Homepage() + post_with_metadata.return_value = gsma_homepage.Homepage(), metadata + + client.update_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_claim_homepage_rest_bad_request(request_type=homepage.ClaimHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + 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.claim_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + homepage.ClaimHomepageRequest, + dict, +]) +def test_claim_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + request = request_type(**request_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 = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = homepage.Homepage.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.claim_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_claim_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_claim_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_claim_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_claim_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = homepage.ClaimHomepageRequest.pb(homepage.ClaimHomepageRequest()) + 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 = homepage.Homepage.to_json(homepage.Homepage()) + req.return_value.content = return_value + + request = homepage.ClaimHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = homepage.Homepage() + post_with_metadata.return_value = homepage.Homepage(), metadata + + client.claim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_unclaim_homepage_rest_bad_request(request_type=homepage.UnclaimHomepageRequest): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + 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.unclaim_homepage(request) + + +@pytest.mark.parametrize("request_type", [ + homepage.UnclaimHomepageRequest, + dict, +]) +def test_unclaim_homepage_rest_call_success(request_type): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/homepage'} + request = request_type(**request_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 = homepage.Homepage( + name='name_value', + uri='uri_value', + claimed=True, + ) + + # 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 = homepage.Homepage.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.unclaim_homepage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, homepage.Homepage) + assert response.name == 'name_value' + assert response.uri == 'uri_value' + assert response.claimed is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_unclaim_homepage_rest_interceptors(null_interceptor): + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), + ) + client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_unclaim_homepage") as post, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "post_unclaim_homepage_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_unclaim_homepage") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = homepage.UnclaimHomepageRequest.pb(homepage.UnclaimHomepageRequest()) + 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 = homepage.Homepage.to_json(homepage.Homepage()) + req.return_value.content = return_value + + request = homepage.UnclaimHomepageRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = homepage.Homepage() + post_with_metadata.return_value = homepage.Homepage(), metadata + + client.unclaim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = HomepageServiceClient( + 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_get_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_homepage), + '__call__') as call: + client.get_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.GetHomepageRequest() + + 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_update_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_homepage), + '__call__') as call: + client.update_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_homepage.UpdateHomepageRequest() + + 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_claim_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.claim_homepage), + '__call__') as call: + client.claim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.ClaimHomepageRequest() + + 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_unclaim_homepage_empty_call_rest(): + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unclaim_homepage), + '__call__') as call: + client.unclaim_homepage(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = homepage.UnclaimHomepageRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.HomepageServiceGrpcTransport, + ) + +def test_homepage_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.HomepageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_homepage_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.homepage_service.transports.HomepageServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.HomepageServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_homepage', + 'update_homepage', + 'claim_homepage', + 'unclaim_homepage', + ) + 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_homepage_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_accounts_v1beta.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HomepageServiceTransport( + 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_homepage_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_accounts_v1beta.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HomepageServiceTransport() + adc.assert_called_once() + + +def test_homepage_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) + HomepageServiceClient() + 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.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + ], +) +def test_homepage_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.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + transports.HomepageServiceRestTransport, + ], +) +def test_homepage_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.HomepageServiceGrpcTransport, grpc_helpers), + (transports.HomepageServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +def test_homepage_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_homepage_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.HomepageServiceRestTransport ( + 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_homepage_service_host_no_port(transport_name): + client = HomepageServiceClient( + 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_homepage_service_host_with_port(transport_name): + client = HomepageServiceClient( + 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_homepage_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = HomepageServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = HomepageServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_homepage._session + session2 = client2.transport.get_homepage._session + assert session1 != session2 + session1 = client1.transport.update_homepage._session + session2 = client2.transport.update_homepage._session + assert session1 != session2 + session1 = client1.transport.claim_homepage._session + session2 = client2.transport.claim_homepage._session + assert session1 != session2 + session1 = client1.transport.unclaim_homepage._session + session2 = client2.transport.unclaim_homepage._session + assert session1 != session2 +def test_homepage_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HomepageServiceGrpcTransport( + 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_homepage_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HomepageServiceGrpcAsyncIOTransport( + 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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +def test_homepage_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_homepage_path(): + account = "squid" + expected = "accounts/{account}/homepage".format(account=account, ) + actual = HomepageServiceClient.homepage_path(account) + assert expected == actual + + +def test_parse_homepage_path(): + expected = { + "account": "clam", + } + path = HomepageServiceClient.homepage_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_homepage_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = HomepageServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = HomepageServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = HomepageServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = HomepageServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = HomepageServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = HomepageServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = HomepageServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = HomepageServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = HomepageServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = HomepageServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = HomepageServiceClient.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.HomepageServiceTransport, '_prep_wrapped_messages') as prep: + client = HomepageServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.HomepageServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = HomepageServiceClient.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 = HomepageServiceClient( + 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 = HomepageServiceAsyncClient( + 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 = HomepageServiceClient( + 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 = HomepageServiceClient( + 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", [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py new file mode 100644 index 000000000000..1062b5e21719 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py @@ -0,0 +1,3076 @@ +# -*- 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 empty_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import LfpProvidersServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import LfpProvidersServiceClient +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import pagers +from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import transports +from google.shopping.merchant_accounts_v1beta.types import lfpproviders +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 LfpProvidersServiceClient._get_default_mtls_endpoint(None) is None + assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert LfpProvidersServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert LfpProvidersServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + LfpProvidersServiceClient._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 LfpProvidersServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpProvidersServiceClient._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 LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, False) is None + assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert LfpProvidersServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + assert LfpProvidersServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert LfpProvidersServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert LfpProvidersServiceClient._get_universe_domain(None, None) == LfpProvidersServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + LfpProvidersServiceClient._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 = LfpProvidersServiceClient(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 = LfpProvidersServiceClient(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", [ + (LfpProvidersServiceClient, "grpc"), + (LfpProvidersServiceAsyncClient, "grpc_asyncio"), + (LfpProvidersServiceClient, "rest"), +]) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, "grpc"), + (transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LfpProvidersServiceRestTransport, "rest"), +]) +def test_lfp_providers_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", [ + (LfpProvidersServiceClient, "grpc"), + (LfpProvidersServiceAsyncClient, "grpc_asyncio"), + (LfpProvidersServiceClient, "rest"), +]) +def test_lfp_providers_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_lfp_providers_service_client_get_transport_class(): + transport = LfpProvidersServiceClient.get_transport_class() + available_transports = [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceRestTransport, + ] + assert transport in available_transports + + transport = LfpProvidersServiceClient.get_transport_class("grpc") + assert transport == transports.LfpProvidersServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), +]) +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +def test_lfp_providers_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(LfpProvidersServiceClient, '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(LfpProvidersServiceClient, '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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "true"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "false"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "true"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lfp_providers_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", [ + LfpProvidersServiceClient, LfpProvidersServiceAsyncClient +]) +@mock.patch.object(LfpProvidersServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceAsyncClient)) +def test_lfp_providers_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", [ + LfpProvidersServiceClient, LfpProvidersServiceAsyncClient +]) +@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) +@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +def test_lfp_providers_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE + default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = LfpProvidersServiceClient._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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), +]) +def test_lfp_providers_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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", None), +]) +def test_lfp_providers_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_lfp_providers_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = LfpProvidersServiceClient( + 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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_lfp_providers_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", [ + lfpproviders.FindLfpProvidersRequest, + dict, +]) +def test_find_lfp_providers(request_type, transport: str = 'grpc'): + client = LfpProvidersServiceClient( + 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.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.FindLfpProvidersResponse( + next_page_token='next_page_token_value', + ) + response = client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpproviders.FindLfpProvidersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FindLfpProvidersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_find_lfp_providers_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 = LfpProvidersServiceClient( + 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 = lfpproviders.FindLfpProvidersRequest( + 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.find_lfp_providers), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.find_lfp_providers(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpproviders.FindLfpProvidersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_find_lfp_providers_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 = LfpProvidersServiceClient( + 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.find_lfp_providers in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc + request = {} + client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_lfp_providers(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_find_lfp_providers_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 = LfpProvidersServiceAsyncClient( + 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.find_lfp_providers 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.find_lfp_providers] = mock_rpc + + request = {} + await client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.find_lfp_providers(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_find_lfp_providers_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.FindLfpProvidersRequest): + client = LfpProvidersServiceAsyncClient( + 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.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( + next_page_token='next_page_token_value', + )) + response = await client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpproviders.FindLfpProvidersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FindLfpProvidersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_find_lfp_providers_async_from_dict(): + await test_find_lfp_providers_async(request_type=dict) + +def test_find_lfp_providers_field_headers(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.FindLfpProvidersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + call.return_value = lfpproviders.FindLfpProvidersResponse() + client.find_lfp_providers(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_find_lfp_providers_field_headers_async(): + client = LfpProvidersServiceAsyncClient( + 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 = lfpproviders.FindLfpProvidersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) + await client.find_lfp_providers(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_find_lfp_providers_flattened(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.FindLfpProvidersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.find_lfp_providers( + 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_find_lfp_providers_flattened_error(): + client = LfpProvidersServiceClient( + 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.find_lfp_providers( + lfpproviders.FindLfpProvidersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_find_lfp_providers_flattened_async(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.FindLfpProvidersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.find_lfp_providers( + 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_find_lfp_providers_flattened_error_async(): + client = LfpProvidersServiceAsyncClient( + 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.find_lfp_providers( + lfpproviders.FindLfpProvidersRequest(), + parent='parent_value', + ) + + +def test_find_lfp_providers_pager(transport_name: str = "grpc"): + client = LfpProvidersServiceClient( + 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.find_lfp_providers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.find_lfp_providers(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, lfpproviders.LfpProvider) + for i in results) +def test_find_lfp_providers_pages(transport_name: str = "grpc"): + client = LfpProvidersServiceClient( + 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.find_lfp_providers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + RuntimeError, + ) + pages = list(client.find_lfp_providers(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_find_lfp_providers_async_pager(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + RuntimeError, + ) + async_pager = await client.find_lfp_providers(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, lfpproviders.LfpProvider) + for i in responses) + + +@pytest.mark.asyncio +async def test_find_lfp_providers_async_pages(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + 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.find_lfp_providers(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", [ + lfpproviders.LinkLfpProviderRequest, + dict, +]) +def test_link_lfp_provider(request_type, transport: str = 'grpc'): + client = LfpProvidersServiceClient( + 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.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.LinkLfpProviderResponse( + ) + response = client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = lfpproviders.LinkLfpProviderRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpproviders.LinkLfpProviderResponse) + + +def test_link_lfp_provider_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 = LfpProvidersServiceClient( + 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 = lfpproviders.LinkLfpProviderRequest( + name='name_value', + external_account_id='external_account_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.link_lfp_provider(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == lfpproviders.LinkLfpProviderRequest( + name='name_value', + external_account_id='external_account_id_value', + ) + +def test_link_lfp_provider_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 = LfpProvidersServiceClient( + 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.link_lfp_provider in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc + request = {} + client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_lfp_provider(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_link_lfp_provider_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 = LfpProvidersServiceAsyncClient( + 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.link_lfp_provider 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.link_lfp_provider] = mock_rpc + + request = {} + await client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.link_lfp_provider(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_link_lfp_provider_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.LinkLfpProviderRequest): + client = LfpProvidersServiceAsyncClient( + 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.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( + )) + response = await client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = lfpproviders.LinkLfpProviderRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpproviders.LinkLfpProviderResponse) + + +@pytest.mark.asyncio +async def test_link_lfp_provider_async_from_dict(): + await test_link_lfp_provider_async(request_type=dict) + +def test_link_lfp_provider_field_headers(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.LinkLfpProviderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value = lfpproviders.LinkLfpProviderResponse() + client.link_lfp_provider(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_link_lfp_provider_field_headers_async(): + client = LfpProvidersServiceAsyncClient( + 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 = lfpproviders.LinkLfpProviderRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) + await client.link_lfp_provider(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_link_lfp_provider_flattened(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.LinkLfpProviderResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.link_lfp_provider( + 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_link_lfp_provider_flattened_error(): + client = LfpProvidersServiceClient( + 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.link_lfp_provider( + lfpproviders.LinkLfpProviderRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_link_lfp_provider_flattened_async(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = lfpproviders.LinkLfpProviderResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.link_lfp_provider( + 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_link_lfp_provider_flattened_error_async(): + client = LfpProvidersServiceAsyncClient( + 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.link_lfp_provider( + lfpproviders.LinkLfpProviderRequest(), + name='name_value', + ) + + +def test_find_lfp_providers_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 = LfpProvidersServiceClient( + 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.find_lfp_providers in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc + + request = {} + client.find_lfp_providers(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.find_lfp_providers(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_find_lfp_providers_rest_required_fields(request_type=lfpproviders.FindLfpProvidersRequest): + transport_class = transports.LfpProvidersServiceRestTransport + + 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()).find_lfp_providers._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()).find_lfp_providers._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 = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpproviders.FindLfpProvidersResponse() + # 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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_find_lfp_providers_rest_unset_required_fields(): + transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.find_lfp_providers._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_find_lfp_providers_rest_flattened(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.FindLfpProvidersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(**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/accounts/v1beta/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find" % client.transport._host, args[1]) + + +def test_find_lfp_providers_rest_flattened_error(transport: str = 'rest'): + client = LfpProvidersServiceClient( + 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.find_lfp_providers( + lfpproviders.FindLfpProvidersRequest(), + parent='parent_value', + ) + + +def test_find_lfp_providers_rest_pager(transport: str = 'rest'): + client = LfpProvidersServiceClient( + 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 = ( + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + next_page_token='abc', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[], + next_page_token='def', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + ], + next_page_token='ghi', + ), + lfpproviders.FindLfpProvidersResponse( + lfp_providers=[ + lfpproviders.LfpProvider(), + lfpproviders.LfpProvider(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lfpproviders.FindLfpProvidersResponse.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/omnichannelSettings/sample2'} + + pager = client.find_lfp_providers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lfpproviders.LfpProvider) + for i in results) + + pages = list(client.find_lfp_providers(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_link_lfp_provider_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 = LfpProvidersServiceClient( + 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.link_lfp_provider in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc + + request = {} + client.link_lfp_provider(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.link_lfp_provider(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_link_lfp_provider_rest_required_fields(request_type=lfpproviders.LinkLfpProviderRequest): + transport_class = transports.LfpProvidersServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["external_account_id"] = "" + 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()).link_lfp_provider._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["externalAccountId"] = 'external_account_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_lfp_provider._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 "externalAccountId" in jsonified_request + assert jsonified_request["externalAccountId"] == 'external_account_id_value' + + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lfpproviders.LinkLfpProviderResponse() + # 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 = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_link_lfp_provider_rest_unset_required_fields(): + transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.link_lfp_provider._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "externalAccountId", ))) + + +def test_link_lfp_provider_rest_flattened(): + client = LfpProvidersServiceClient( + 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 = lfpproviders.LinkLfpProviderResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 + # Convert return value to protobuf type + return_value = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(**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/accounts/v1beta/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider" % client.transport._host, args[1]) + + +def test_link_lfp_provider_rest_flattened_error(transport: str = 'rest'): + client = LfpProvidersServiceClient( + 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.link_lfp_provider( + lfpproviders.LinkLfpProviderRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + 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 = LfpProvidersServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LfpProvidersServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = LfpProvidersServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LfpProvidersServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LfpProvidersServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + transports.LfpProvidersServiceRestTransport, +]) +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 = LfpProvidersServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = LfpProvidersServiceClient( + 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_find_lfp_providers_empty_call_grpc(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + call.return_value = lfpproviders.FindLfpProvidersResponse() + client.find_lfp_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.FindLfpProvidersRequest() + + 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_link_lfp_provider_empty_call_grpc(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + call.return_value = lfpproviders.LinkLfpProviderResponse() + client.link_lfp_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.LinkLfpProviderRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = LfpProvidersServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = LfpProvidersServiceAsyncClient( + 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_find_lfp_providers_empty_call_grpc_asyncio(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( + next_page_token='next_page_token_value', + )) + await client.find_lfp_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.FindLfpProvidersRequest() + + 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_link_lfp_provider_empty_call_grpc_asyncio(): + client = LfpProvidersServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( + )) + await client.link_lfp_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.LinkLfpProviderRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = LfpProvidersServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_find_lfp_providers_rest_bad_request(request_type=lfpproviders.FindLfpProvidersRequest): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/omnichannelSettings/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.find_lfp_providers(request) + + +@pytest.mark.parametrize("request_type", [ + lfpproviders.FindLfpProvidersRequest, + dict, +]) +def test_find_lfp_providers_rest_call_success(request_type): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse( + 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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FindLfpProvidersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_find_lfp_providers_rest_interceptors(null_interceptor): + transport = transports.LfpProvidersServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), + ) + client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers") as post, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_find_lfp_providers") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = lfpproviders.FindLfpProvidersRequest.pb(lfpproviders.FindLfpProvidersRequest()) + 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 = lfpproviders.FindLfpProvidersResponse.to_json(lfpproviders.FindLfpProvidersResponse()) + req.return_value.content = return_value + + request = lfpproviders.FindLfpProvidersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpproviders.FindLfpProvidersResponse() + post_with_metadata.return_value = lfpproviders.FindLfpProvidersResponse(), metadata + + client.find_lfp_providers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_link_lfp_provider_rest_bad_request(request_type=lfpproviders.LinkLfpProviderRequest): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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.link_lfp_provider(request) + + +@pytest.mark.parametrize("request_type", [ + lfpproviders.LinkLfpProviderRequest, + dict, +]) +def test_link_lfp_provider_rest_call_success(request_type): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 = lfpproviders.LinkLfpProviderResponse( + ) + + # 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 = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lfpproviders.LinkLfpProviderResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_link_lfp_provider_rest_interceptors(null_interceptor): + transport = transports.LfpProvidersServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), + ) + client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider") as post, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_link_lfp_provider") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = lfpproviders.LinkLfpProviderRequest.pb(lfpproviders.LinkLfpProviderRequest()) + 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 = lfpproviders.LinkLfpProviderResponse.to_json(lfpproviders.LinkLfpProviderResponse()) + req.return_value.content = return_value + + request = lfpproviders.LinkLfpProviderRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lfpproviders.LinkLfpProviderResponse() + post_with_metadata.return_value = lfpproviders.LinkLfpProviderResponse(), metadata + + client.link_lfp_provider(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = LfpProvidersServiceClient( + 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_find_lfp_providers_empty_call_rest(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.find_lfp_providers), + '__call__') as call: + client.find_lfp_providers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.FindLfpProvidersRequest() + + 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_link_lfp_provider_empty_call_rest(): + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.link_lfp_provider), + '__call__') as call: + client.link_lfp_provider(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = lfpproviders.LinkLfpProviderRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.LfpProvidersServiceGrpcTransport, + ) + +def test_lfp_providers_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.LfpProvidersServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_lfp_providers_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.LfpProvidersServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'find_lfp_providers', + 'link_lfp_provider', + ) + 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_lfp_providers_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_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpProvidersServiceTransport( + 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_lfp_providers_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_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.LfpProvidersServiceTransport() + adc.assert_called_once() + + +def test_lfp_providers_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) + LfpProvidersServiceClient() + 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.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + ], +) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + transports.LfpProvidersServiceRestTransport, + ], +) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, grpc_helpers), + (transports.LfpProvidersServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +def test_lfp_providers_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_lfp_providers_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.LfpProvidersServiceRestTransport ( + 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_lfp_providers_service_host_no_port(transport_name): + client = LfpProvidersServiceClient( + 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_lfp_providers_service_host_with_port(transport_name): + client = LfpProvidersServiceClient( + 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_lfp_providers_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = LfpProvidersServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = LfpProvidersServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.find_lfp_providers._session + session2 = client2.transport.find_lfp_providers._session + assert session1 != session2 + session1 = client1.transport.link_lfp_provider._session + session2 = client2.transport.link_lfp_provider._session + assert session1 != session2 +def test_lfp_providers_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpProvidersServiceGrpcTransport( + 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_lfp_providers_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.LfpProvidersServiceGrpcAsyncIOTransport( + 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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +def test_lfp_providers_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_lfp_provider_path(): + account = "squid" + omnichannel_setting = "clam" + lfp_provider = "whelk" + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) + actual = LfpProvidersServiceClient.lfp_provider_path(account, omnichannel_setting, lfp_provider) + assert expected == actual + + +def test_parse_lfp_provider_path(): + expected = { + "account": "octopus", + "omnichannel_setting": "oyster", + "lfp_provider": "nudibranch", + } + path = LfpProvidersServiceClient.lfp_provider_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_lfp_provider_path(path) + assert expected == actual + +def test_omnichannel_setting_path(): + account = "cuttlefish" + omnichannel_setting = "mussel" + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + actual = LfpProvidersServiceClient.omnichannel_setting_path(account, omnichannel_setting) + assert expected == actual + + +def test_parse_omnichannel_setting_path(): + expected = { + "account": "winkle", + "omnichannel_setting": "nautilus", + } + path = LfpProvidersServiceClient.omnichannel_setting_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_omnichannel_setting_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = LfpProvidersServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = LfpProvidersServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = LfpProvidersServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = LfpProvidersServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = LfpProvidersServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = LfpProvidersServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = LfpProvidersServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = LfpProvidersServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = LfpProvidersServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = LfpProvidersServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LfpProvidersServiceClient.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.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: + client = LfpProvidersServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = LfpProvidersServiceClient.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 = LfpProvidersServiceClient( + 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 = LfpProvidersServiceAsyncClient( + 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 = LfpProvidersServiceClient( + 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 = LfpProvidersServiceClient( + 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", [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport), + (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py new file mode 100644 index 000000000000..ffb35c285cf6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py @@ -0,0 +1,5231 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import OmnichannelSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import pagers +from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import transports +from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings +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 OmnichannelSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, False) is None + assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert OmnichannelSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert OmnichannelSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert OmnichannelSettingsServiceClient._get_universe_domain(None, None) == OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient(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 = OmnichannelSettingsServiceClient(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", [ + (OmnichannelSettingsServiceClient, "grpc"), + (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, "rest"), +]) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OmnichannelSettingsServiceRestTransport, "rest"), +]) +def test_omnichannel_settings_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", [ + (OmnichannelSettingsServiceClient, "grpc"), + (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, "rest"), +]) +def test_omnichannel_settings_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_omnichannel_settings_service_client_get_transport_class(): + transport = OmnichannelSettingsServiceClient.get_transport_class() + available_transports = [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = OmnichannelSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.OmnichannelSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +def test_omnichannel_settings_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(OmnichannelSettingsServiceClient, '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(OmnichannelSettingsServiceClient, '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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "true"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "false"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "true"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_omnichannel_settings_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", [ + OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceAsyncClient)) +def test_omnichannel_settings_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", [ + OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient +]) +@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) +@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +def test_omnichannel_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OmnichannelSettingsServiceClient._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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), +]) +def test_omnichannel_settings_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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", None), +]) +def test_omnichannel_settings_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_omnichannel_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OmnichannelSettingsServiceClient( + 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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_omnichannel_settings_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", [ + omnichannelsettings.GetOmnichannelSettingRequest, + dict, +]) +def test_get_omnichannel_setting(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + response = client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.GetOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.GetOmnichannelSettingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_omnichannel_setting(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.GetOmnichannelSettingRequest( + name='name_value', + ) + +def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc + request = {} + client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_omnichannel_setting(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_get_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( + 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.get_omnichannel_setting in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_omnichannel_setting] = mock_rpc + + request = {} + await client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_omnichannel_setting(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_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.GetOmnichannelSettingRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + response = await client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.GetOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.asyncio +async def test_get_omnichannel_setting_async_from_dict(): + await test_get_omnichannel_setting_async(request_type=dict) + +def test_get_omnichannel_setting_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.GetOmnichannelSettingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.get_omnichannel_setting(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_get_omnichannel_setting_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.GetOmnichannelSettingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + await client.get_omnichannel_setting(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_get_omnichannel_setting_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_omnichannel_setting( + 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_get_omnichannel_setting_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting( + omnichannelsettings.GetOmnichannelSettingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_omnichannel_setting_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_omnichannel_setting( + 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_get_omnichannel_setting_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.get_omnichannel_setting( + omnichannelsettings.GetOmnichannelSettingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.ListOmnichannelSettingsRequest, + dict, +]) +def test_list_omnichannel_settings(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.ListOmnichannelSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOmnichannelSettingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.ListOmnichannelSettingsRequest( + 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_omnichannel_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_omnichannel_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.ListOmnichannelSettingsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( + 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_omnichannel_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_omnichannel_settings] = mock_rpc + request = {} + client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_omnichannel_settings(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_omnichannel_settings_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 = OmnichannelSettingsServiceAsyncClient( + 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_omnichannel_settings 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_omnichannel_settings] = mock_rpc + + request = {} + await client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_omnichannel_settings(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_omnichannel_settings_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.ListOmnichannelSettingsRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.ListOmnichannelSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOmnichannelSettingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_omnichannel_settings_async_from_dict(): + await test_list_omnichannel_settings_async(request_type=dict) + +def test_list_omnichannel_settings_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.ListOmnichannelSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + client.list_omnichannel_settings(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_omnichannel_settings_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.ListOmnichannelSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) + await client.list_omnichannel_settings(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_omnichannel_settings_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_omnichannel_settings( + 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_omnichannel_settings_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings( + omnichannelsettings.ListOmnichannelSettingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_omnichannel_settings_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_omnichannel_settings( + 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_omnichannel_settings_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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_omnichannel_settings( + omnichannelsettings.ListOmnichannelSettingsRequest(), + parent='parent_value', + ) + + +def test_list_omnichannel_settings_pager(transport_name: str = "grpc"): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_omnichannel_settings(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, omnichannelsettings.OmnichannelSetting) + for i in results) +def test_list_omnichannel_settings_pages(transport_name: str = "grpc"): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + RuntimeError, + ) + pages = list(client.list_omnichannel_settings(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_omnichannel_settings_async_pager(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_omnichannel_settings(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, omnichannelsettings.OmnichannelSetting) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_omnichannel_settings_async_pages(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + 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_omnichannel_settings(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", [ + omnichannelsettings.CreateOmnichannelSettingRequest, + dict, +]) +def test_create_omnichannel_setting(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + response = client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.CreateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.CreateOmnichannelSettingRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_omnichannel_setting(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.CreateOmnichannelSettingRequest( + parent='parent_value', + ) + +def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc + request = {} + client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_omnichannel_setting(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_create_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( + 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.create_omnichannel_setting in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_omnichannel_setting] = mock_rpc + + request = {} + await client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_omnichannel_setting(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_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.CreateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + response = await client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.CreateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.asyncio +async def test_create_omnichannel_setting_async_from_dict(): + await test_create_omnichannel_setting_async(request_type=dict) + +def test_create_omnichannel_setting_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.CreateOmnichannelSettingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.create_omnichannel_setting(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_create_omnichannel_setting_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.CreateOmnichannelSettingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + await client.create_omnichannel_setting(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_create_omnichannel_setting_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_omnichannel_setting( + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + + +def test_create_omnichannel_setting_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting( + omnichannelsettings.CreateOmnichannelSettingRequest(), + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_omnichannel_setting_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_omnichannel_setting( + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_omnichannel_setting_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.create_omnichannel_setting( + omnichannelsettings.CreateOmnichannelSettingRequest(), + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.UpdateOmnichannelSettingRequest, + dict, +]) +def test_update_omnichannel_setting(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + response = client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.UpdateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.UpdateOmnichannelSettingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_omnichannel_setting(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.UpdateOmnichannelSettingRequest( + ) + +def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc + request = {} + client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_omnichannel_setting(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_update_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( + 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.update_omnichannel_setting in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_omnichannel_setting] = mock_rpc + + request = {} + await client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_omnichannel_setting(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_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + response = await client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.UpdateOmnichannelSettingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_async_from_dict(): + await test_update_omnichannel_setting_async(request_type=dict) + +def test_update_omnichannel_setting_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.UpdateOmnichannelSettingRequest() + + request.omnichannel_setting.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.update_omnichannel_setting(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', + 'omnichannel_setting.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.UpdateOmnichannelSettingRequest() + + request.omnichannel_setting.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + await client.update_omnichannel_setting(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', + 'omnichannel_setting.name=name_value', + ) in kw['metadata'] + + +def test_update_omnichannel_setting_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_omnichannel_setting( + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_omnichannel_setting_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting( + omnichannelsettings.UpdateOmnichannelSettingRequest(), + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.OmnichannelSetting() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_omnichannel_setting( + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].omnichannel_setting + mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_omnichannel_setting_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.update_omnichannel_setting( + omnichannelsettings.UpdateOmnichannelSettingRequest(), + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.RequestInventoryVerificationRequest, + dict, +]) +def test_request_inventory_verification(request_type, transport: str = 'grpc'): + client = OmnichannelSettingsServiceClient( + 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.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse( + ) + response = client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.RequestInventoryVerificationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + + +def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.RequestInventoryVerificationRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.request_inventory_verification(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == omnichannelsettings.RequestInventoryVerificationRequest( + name='name_value', + ) + +def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( + 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.request_inventory_verification in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc + request = {} + client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.request_inventory_verification(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_request_inventory_verification_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 = OmnichannelSettingsServiceAsyncClient( + 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.request_inventory_verification 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.request_inventory_verification] = mock_rpc + + request = {} + await client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.request_inventory_verification(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_request_inventory_verification_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.RequestInventoryVerificationRequest): + client = OmnichannelSettingsServiceAsyncClient( + 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.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( + )) + response = await client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = omnichannelsettings.RequestInventoryVerificationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + + +@pytest.mark.asyncio +async def test_request_inventory_verification_async_from_dict(): + await test_request_inventory_verification_async(request_type=dict) + +def test_request_inventory_verification_field_headers(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.RequestInventoryVerificationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + client.request_inventory_verification(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_request_inventory_verification_field_headers_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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 = omnichannelsettings.RequestInventoryVerificationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) + await client.request_inventory_verification(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_request_inventory_verification_flattened(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.request_inventory_verification( + 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_request_inventory_verification_flattened_error(): + client = OmnichannelSettingsServiceClient( + 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.request_inventory_verification( + omnichannelsettings.RequestInventoryVerificationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_request_inventory_verification_flattened_async(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.request_inventory_verification( + 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_request_inventory_verification_flattened_error_async(): + client = OmnichannelSettingsServiceAsyncClient( + 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.request_inventory_verification( + omnichannelsettings.RequestInventoryVerificationRequest(), + name='name_value', + ) + + +def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.get_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc + + request = {} + client.get_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_omnichannel_setting(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_get_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.GetOmnichannelSettingRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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()).get_omnichannel_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_omnichannel_setting._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.OmnichannelSetting() + # 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 = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_omnichannel_setting_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_omnichannel_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_omnichannel_setting_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.OmnichannelSetting() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(**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/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) + + +def test_get_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_omnichannel_setting( + omnichannelsettings.GetOmnichannelSettingRequest(), + name='name_value', + ) + + +def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( + 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_omnichannel_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_omnichannel_settings] = mock_rpc + + request = {} + client.list_omnichannel_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_omnichannel_settings(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_omnichannel_settings_rest_required_fields(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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_omnichannel_settings._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_omnichannel_settings._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + # 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_omnichannel_settings_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_omnichannel_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_omnichannel_settings_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.ListOmnichannelSettingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(**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/accounts/v1beta/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) + + +def test_list_omnichannel_settings_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings( + omnichannelsettings.ListOmnichannelSettingsRequest(), + parent='parent_value', + ) + + +def test_list_omnichannel_settings_rest_pager(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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 = ( + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='abc', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[], + next_page_token='def', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + ], + next_page_token='ghi', + ), + omnichannelsettings.ListOmnichannelSettingsResponse( + omnichannel_settings=[ + omnichannelsettings.OmnichannelSetting(), + omnichannelsettings.OmnichannelSetting(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(omnichannelsettings.ListOmnichannelSettingsResponse.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'} + + pager = client.list_omnichannel_settings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, omnichannelsettings.OmnichannelSetting) + for i in results) + + pages = list(client.list_omnichannel_settings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc + + request = {} + client.create_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_omnichannel_setting(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_create_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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()).create_omnichannel_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_omnichannel_setting._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.OmnichannelSetting() + # 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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_omnichannel_setting_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_omnichannel_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "omnichannelSetting", ))) + + +def test_create_omnichannel_setting_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.OmnichannelSetting() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(**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/accounts/v1beta/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) + + +def test_create_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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.create_omnichannel_setting( + omnichannelsettings.CreateOmnichannelSettingRequest(), + parent='parent_value', + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + ) + + +def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc + + request = {} + client.update_omnichannel_setting(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_omnichannel_setting(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_update_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.OmnichannelSetting() + # 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': "patch", + '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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_omnichannel_setting_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_omnichannel_setting._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("omnichannelSetting", "updateMask", ))) + + +def test_update_omnichannel_setting_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.OmnichannelSetting() + + # get arguments that satisfy an http rule for this method + sample_request = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(**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/accounts/v1beta/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) + + +def test_update_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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.update_omnichannel_setting( + omnichannelsettings.UpdateOmnichannelSettingRequest(), + omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( + 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.request_inventory_verification in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc + + request = {} + client.request_inventory_verification(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.request_inventory_verification(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_request_inventory_verification_rest_required_fields(request_type=omnichannelsettings.RequestInventoryVerificationRequest): + transport_class = transports.OmnichannelSettingsServiceRestTransport + + 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()).request_inventory_verification._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()).request_inventory_verification._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 = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.RequestInventoryVerificationResponse() + # 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 = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_request_inventory_verification_rest_unset_required_fields(): + transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.request_inventory_verification._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_request_inventory_verification_rest_flattened(): + client = OmnichannelSettingsServiceClient( + 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 = omnichannelsettings.RequestInventoryVerificationResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(**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/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification" % client.transport._host, args[1]) + + +def test_request_inventory_verification_rest_flattened_error(transport: str = 'rest'): + client = OmnichannelSettingsServiceClient( + 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.request_inventory_verification( + omnichannelsettings.RequestInventoryVerificationRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + 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 = OmnichannelSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OmnichannelSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OmnichannelSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OmnichannelSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + transports.OmnichannelSettingsServiceRestTransport, +]) +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 = OmnichannelSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OmnichannelSettingsServiceClient( + 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_get_omnichannel_setting_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.get_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.GetOmnichannelSettingRequest() + + 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_list_omnichannel_settings_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + client.list_omnichannel_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() + + 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_create_omnichannel_setting_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.create_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() + + 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_update_omnichannel_setting_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + call.return_value = omnichannelsettings.OmnichannelSetting() + client.update_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() + + 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_request_inventory_verification_empty_call_grpc(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + client.request_inventory_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.RequestInventoryVerificationRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OmnichannelSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + 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_get_omnichannel_setting_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + await client.get_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.GetOmnichannelSettingRequest() + + 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_list_omnichannel_settings_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token='next_page_token_value', + )) + await client.list_omnichannel_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() + + 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_create_omnichannel_setting_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + await client.create_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() + + 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_update_omnichannel_setting_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + )) + await client.update_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() + + 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_request_inventory_verification_empty_call_grpc_asyncio(): + client = OmnichannelSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( + )) + await client.request_inventory_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.RequestInventoryVerificationRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OmnichannelSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.GetOmnichannelSettingRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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.get_omnichannel_setting(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.GetOmnichannelSettingRequest, + dict, +]) +def test_get_omnichannel_setting_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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 = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + + # 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 = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_omnichannel_setting_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_get_omnichannel_setting") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.GetOmnichannelSettingRequest.pb(omnichannelsettings.GetOmnichannelSettingRequest()) + 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + req.return_value.content = return_value + + request = omnichannelsettings.GetOmnichannelSettingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.OmnichannelSetting() + post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + + client.get_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_omnichannel_settings_rest_bad_request(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_omnichannel_settings(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.ListOmnichannelSettingsRequest, + dict, +]) +def test_list_omnichannel_settings_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = omnichannelsettings.ListOmnichannelSettingsResponse( + 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOmnichannelSettingsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_omnichannel_settings_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_list_omnichannel_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.ListOmnichannelSettingsRequest.pb(omnichannelsettings.ListOmnichannelSettingsRequest()) + 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 = omnichannelsettings.ListOmnichannelSettingsResponse.to_json(omnichannelsettings.ListOmnichannelSettingsResponse()) + req.return_value.content = return_value + + request = omnichannelsettings.ListOmnichannelSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() + post_with_metadata.return_value = omnichannelsettings.ListOmnichannelSettingsResponse(), metadata + + client.list_omnichannel_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_omnichannel_setting(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.CreateOmnichannelSettingRequest, + dict, +]) +def test_create_omnichannel_setting_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["omnichannel_setting"] = {'name': 'name_value', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 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 = omnichannelsettings.CreateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] + + 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["omnichannel_setting"].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["omnichannel_setting"][field])): + del request_init["omnichannel_setting"][field][i][subfield] + else: + del request_init["omnichannel_setting"][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 = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + + # 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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_omnichannel_setting_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_create_omnichannel_setting") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.CreateOmnichannelSettingRequest.pb(omnichannelsettings.CreateOmnichannelSettingRequest()) + 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + req.return_value.content = return_value + + request = omnichannelsettings.CreateOmnichannelSettingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.OmnichannelSetting() + post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + + client.create_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/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.update_omnichannel_setting(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.UpdateOmnichannelSettingRequest, + dict, +]) +def test_update_omnichannel_setting_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} + request_init["omnichannel_setting"] = {'name': 'accounts/sample1/omnichannelSettings/sample2', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 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 = omnichannelsettings.UpdateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] + + 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["omnichannel_setting"].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["omnichannel_setting"][field])): + del request_init["omnichannel_setting"][field][i][subfield] + else: + del request_init["omnichannel_setting"][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 = omnichannelsettings.OmnichannelSetting( + name='name_value', + region_code='region_code_value', + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + + # 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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.OmnichannelSetting) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_omnichannel_setting_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_update_omnichannel_setting") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.UpdateOmnichannelSettingRequest.pb(omnichannelsettings.UpdateOmnichannelSettingRequest()) + 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + req.return_value.content = return_value + + request = omnichannelsettings.UpdateOmnichannelSettingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.OmnichannelSetting() + post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + + client.update_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_request_inventory_verification_rest_bad_request(request_type=omnichannelsettings.RequestInventoryVerificationRequest): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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.request_inventory_verification(request) + + +@pytest.mark.parametrize("request_type", [ + omnichannelsettings.RequestInventoryVerificationRequest, + dict, +]) +def test_request_inventory_verification_rest_call_success(request_type): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/omnichannelSettings/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 = omnichannelsettings.RequestInventoryVerificationResponse( + ) + + # 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 = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_request_inventory_verification_rest_interceptors(null_interceptor): + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), + ) + client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification") as post, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_request_inventory_verification") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = omnichannelsettings.RequestInventoryVerificationRequest.pb(omnichannelsettings.RequestInventoryVerificationRequest()) + 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 = omnichannelsettings.RequestInventoryVerificationResponse.to_json(omnichannelsettings.RequestInventoryVerificationResponse()) + req.return_value.content = return_value + + request = omnichannelsettings.RequestInventoryVerificationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = omnichannelsettings.RequestInventoryVerificationResponse() + post_with_metadata.return_value = omnichannelsettings.RequestInventoryVerificationResponse(), metadata + + client.request_inventory_verification(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = OmnichannelSettingsServiceClient( + 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_get_omnichannel_setting_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_omnichannel_setting), + '__call__') as call: + client.get_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.GetOmnichannelSettingRequest() + + 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_list_omnichannel_settings_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_omnichannel_settings), + '__call__') as call: + client.list_omnichannel_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() + + 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_create_omnichannel_setting_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_omnichannel_setting), + '__call__') as call: + client.create_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() + + 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_update_omnichannel_setting_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_omnichannel_setting), + '__call__') as call: + client.update_omnichannel_setting(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() + + 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_request_inventory_verification_empty_call_rest(): + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.request_inventory_verification), + '__call__') as call: + client.request_inventory_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = omnichannelsettings.RequestInventoryVerificationRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OmnichannelSettingsServiceGrpcTransport, + ) + +def test_omnichannel_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OmnichannelSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_omnichannel_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OmnichannelSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_omnichannel_setting', + 'list_omnichannel_settings', + 'create_omnichannel_setting', + 'update_omnichannel_setting', + 'request_inventory_verification', + ) + 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_omnichannel_settings_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_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OmnichannelSettingsServiceTransport( + 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_omnichannel_settings_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_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OmnichannelSettingsServiceTransport() + adc.assert_called_once() + + +def test_omnichannel_settings_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) + OmnichannelSettingsServiceClient() + 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.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + transports.OmnichannelSettingsServiceRestTransport, + ], +) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, grpc_helpers), + (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +def test_omnichannel_settings_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_omnichannel_settings_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.OmnichannelSettingsServiceRestTransport ( + 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_omnichannel_settings_service_host_no_port(transport_name): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings_service_host_with_port(transport_name): + client = OmnichannelSettingsServiceClient( + 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_omnichannel_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OmnichannelSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OmnichannelSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_omnichannel_setting._session + session2 = client2.transport.get_omnichannel_setting._session + assert session1 != session2 + session1 = client1.transport.list_omnichannel_settings._session + session2 = client2.transport.list_omnichannel_settings._session + assert session1 != session2 + session1 = client1.transport.create_omnichannel_setting._session + session2 = client2.transport.create_omnichannel_setting._session + assert session1 != session2 + session1 = client1.transport.update_omnichannel_setting._session + session2 = client2.transport.update_omnichannel_setting._session + assert session1 != session2 + session1 = client1.transport.request_inventory_verification._session + session2 = client2.transport.request_inventory_verification._session + assert session1 != session2 +def test_omnichannel_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OmnichannelSettingsServiceGrpcTransport( + 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_omnichannel_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OmnichannelSettingsServiceGrpcAsyncIOTransport( + 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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +def test_omnichannel_settings_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = OmnichannelSettingsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = OmnichannelSettingsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_account_path(path) + assert expected == actual + +def test_omnichannel_setting_path(): + account = "whelk" + omnichannel_setting = "octopus" + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + actual = OmnichannelSettingsServiceClient.omnichannel_setting_path(account, omnichannel_setting) + assert expected == actual + + +def test_parse_omnichannel_setting_path(): + expected = { + "account": "oyster", + "omnichannel_setting": "nudibranch", + } + path = OmnichannelSettingsServiceClient.omnichannel_setting_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_omnichannel_setting_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OmnichannelSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = OmnichannelSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = OmnichannelSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = OmnichannelSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OmnichannelSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = OmnichannelSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = OmnichannelSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = OmnichannelSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = OmnichannelSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OmnichannelSettingsServiceClient.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.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = OmnichannelSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient( + 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 = OmnichannelSettingsServiceAsyncClient( + 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 = OmnichannelSettingsServiceClient( + 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 = OmnichannelSettingsServiceClient( + 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", [ + (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport), + (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py new file mode 100644 index 000000000000..e58a8e9072ca --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py @@ -0,0 +1,5362 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import OnlineReturnPolicyServiceClient +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import transports +from google.shopping.merchant_accounts_v1beta.types import online_return_policy +from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy +from google.shopping.type.types import types +from google.type import date_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 OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(None) is None + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, False) is None + assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert OnlineReturnPolicyServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert OnlineReturnPolicyServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert OnlineReturnPolicyServiceClient._get_universe_domain(None, None) == OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient(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 = OnlineReturnPolicyServiceClient(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", [ + (OnlineReturnPolicyServiceClient, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, "rest"), +]) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +def test_online_return_policy_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", [ + (OnlineReturnPolicyServiceClient, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, "rest"), +]) +def test_online_return_policy_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_online_return_policy_service_client_get_transport_class(): + transport = OnlineReturnPolicyServiceClient.get_transport_class() + available_transports = [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceRestTransport, + ] + assert transport in available_transports + + transport = OnlineReturnPolicyServiceClient.get_transport_class("grpc") + assert transport == transports.OnlineReturnPolicyServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +def test_online_return_policy_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(OnlineReturnPolicyServiceClient, '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(OnlineReturnPolicyServiceClient, '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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "true"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "false"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "true"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_online_return_policy_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", [ + OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceAsyncClient)) +def test_online_return_policy_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", [ + OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient +]) +@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) +@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +def test_online_return_policy_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = OnlineReturnPolicyServiceClient._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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), +]) +def test_online_return_policy_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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", None), +]) +def test_online_return_policy_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_online_return_policy_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = OnlineReturnPolicyServiceClient( + 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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_online_return_policy_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", [ + online_return_policy.GetOnlineReturnPolicyRequest, + dict, +]) +def test_get_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + response = client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = online_return_policy.GetOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.GetOnlineReturnPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == online_return_policy.GetOnlineReturnPolicyRequest( + name='name_value', + ) + +def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc + request = {} + client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_online_return_policy(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_get_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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.get_online_return_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_online_return_policy] = mock_rpc + + request = {} + await client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_online_return_policy(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_get_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.GetOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + response = await client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = online_return_policy.GetOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.asyncio +async def test_get_online_return_policy_async_from_dict(): + await test_get_online_return_policy_async(request_type=dict) + +def test_get_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.GetOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value = online_return_policy.OnlineReturnPolicy() + client.get_online_return_policy(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_get_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = online_return_policy.GetOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) + await client.get_online_return_policy(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_get_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.OnlineReturnPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_online_return_policy( + 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_get_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy( + online_return_policy.GetOnlineReturnPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.OnlineReturnPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_online_return_policy( + 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_get_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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.get_online_return_policy( + online_return_policy.GetOnlineReturnPolicyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.ListOnlineReturnPoliciesRequest, + dict, +]) +def test_list_online_return_policies(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = online_return_policy.ListOnlineReturnPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.ListOnlineReturnPoliciesRequest( + 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_online_return_policies), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_online_return_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == online_return_policy.ListOnlineReturnPoliciesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policies] = mock_rpc + request = {} + client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_online_return_policies(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_online_return_policies_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 = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policies 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_online_return_policies] = mock_rpc + + request = {} + await client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_online_return_policies(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_online_return_policies_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.ListOnlineReturnPoliciesRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = online_return_policy.ListOnlineReturnPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOnlineReturnPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_online_return_policies_async_from_dict(): + await test_list_online_return_policies_async(request_type=dict) + +def test_list_online_return_policies_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.ListOnlineReturnPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + client.list_online_return_policies(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_online_return_policies_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = online_return_policy.ListOnlineReturnPoliciesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) + await client.list_online_return_policies(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_online_return_policies_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_online_return_policies( + 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_online_return_policies_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies( + online_return_policy.ListOnlineReturnPoliciesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_online_return_policies_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_online_return_policies( + 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_online_return_policies_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policies( + online_return_policy.ListOnlineReturnPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_online_return_policies_pager(transport_name: str = "grpc"): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_online_return_policies(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, online_return_policy.OnlineReturnPolicy) + for i in results) +def test_list_online_return_policies_pages(transport_name: str = "grpc"): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_online_return_policies(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_online_return_policies_async_pager(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_online_return_policies(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, online_return_policy.OnlineReturnPolicy) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_online_return_policies_async_pages(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + 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_online_return_policies(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", [ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + dict, +]) +def test_create_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + response = client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_online_return_policy.CreateOnlineReturnPolicyRequest( + parent='parent_value', + ) + +def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc + request = {} + client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_online_return_policy(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_create_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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.create_online_return_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_online_return_policy] = mock_rpc + + request = {} + await client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_online_return_policy(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_create_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + response = await client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.asyncio +async def test_create_online_return_policy_async_from_dict(): + await test_create_online_return_policy_async(request_type=dict) + +def test_create_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + client.create_online_return_policy(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_create_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + await client.create_online_return_policy(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_create_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_online_return_policy( + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].online_return_policy + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + assert arg == mock_val + + +def test_create_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_online_return_policy( + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].online_return_policy + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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.create_online_return_policy( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, + dict, +]) +def test_update_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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.update_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + response = client.update_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +def test_update_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_online_return_policy.UpdateOnlineReturnPolicyRequest( + ) + +def test_update_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.update_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_online_return_policy] = mock_rpc + request = {} + client.update_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_online_return_policy(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_update_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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.update_online_return_policy in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_online_return_policy] = mock_rpc + + request = {} + await client.update_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_online_return_policy(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_update_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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.update_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + response = await client.update_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.asyncio +async def test_update_online_return_policy_async_from_dict(): + await test_update_online_return_policy_async(request_type=dict) + +def test_update_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + + request.online_return_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + client.update_online_return_policy(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', + 'online_return_policy.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + + request.online_return_policy.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + await client.update_online_return_policy(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', + 'online_return_policy.name=name_value', + ) in kw['metadata'] + + +def test_update_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_online_return_policy( + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].online_return_policy + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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.update_online_return_policy( + gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(), + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_online_return_policy( + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].online_return_policy + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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.update_online_return_policy( + gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(), + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.DeleteOnlineReturnPolicyRequest, + dict, +]) +def test_delete_online_return_policy(request_type, transport: str = 'grpc'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = online_return_policy.DeleteOnlineReturnPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_online_return_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == online_return_policy.DeleteOnlineReturnPolicyRequest( + name='name_value', + ) + +def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policy] = mock_rpc + request = {} + client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_online_return_policy(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_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policy 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_online_return_policy] = mock_rpc + + request = {} + await client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_online_return_policy(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_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = online_return_policy.DeleteOnlineReturnPolicyRequest() + 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_online_return_policy_async_from_dict(): + await test_delete_online_return_policy_async(request_type=dict) + +def test_delete_online_return_policy_field_headers(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value = None + client.delete_online_return_policy(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_online_return_policy_field_headers_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_online_return_policy(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_online_return_policy_flattened(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__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_online_return_policy( + 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_online_return_policy_flattened_error(): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy( + online_return_policy.DeleteOnlineReturnPolicyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_online_return_policy_flattened_async(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__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_online_return_policy( + 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_online_return_policy_flattened_error_async(): + client = OnlineReturnPolicyServiceAsyncClient( + 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_online_return_policy( + online_return_policy.DeleteOnlineReturnPolicyRequest(), + name='name_value', + ) + + +def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.get_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc + + request = {} + client.get_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_online_return_policy(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_get_online_return_policy_rest_required_fields(request_type=online_return_policy.GetOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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()).get_online_return_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_online_return_policy._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 = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = online_return_policy.OnlineReturnPolicy() + # 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 = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.OnlineReturnPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(**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/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + + +def test_get_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_online_return_policy( + online_return_policy.GetOnlineReturnPolicyRequest(), + name='name_value', + ) + + +def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policies in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policies] = mock_rpc + + request = {} + client.list_online_return_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_online_return_policies(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_online_return_policies_rest_required_fields(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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_online_return_policies._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_online_return_policies._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 = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + # 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_online_return_policies_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_online_return_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_online_return_policies_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = online_return_policy.ListOnlineReturnPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(**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/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) + + +def test_list_online_return_policies_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policies( + online_return_policy.ListOnlineReturnPoliciesRequest(), + parent='parent_value', + ) + + +def test_list_online_return_policies_rest_pager(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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 = ( + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='abc', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[], + next_page_token='def', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + ], + next_page_token='ghi', + ), + online_return_policy.ListOnlineReturnPoliciesResponse( + online_return_policies=[ + online_return_policy.OnlineReturnPolicy(), + online_return_policy.OnlineReturnPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(online_return_policy.ListOnlineReturnPoliciesResponse.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'} + + pager = client.list_online_return_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, online_return_policy.OnlineReturnPolicy) + for i in results) + + pages = list(client.list_online_return_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc + + request = {} + client.create_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_online_return_policy(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_create_online_return_policy_rest_required_fields(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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()).create_online_return_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_online_return_policy._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 = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_online_return_policy.OnlineReturnPolicy() + # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "onlineReturnPolicy", ))) + + +def test_create_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.OnlineReturnPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(**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/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) + + +def test_create_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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.create_online_return_policy( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), + parent='parent_value', + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + ) + + +def test_update_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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.update_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_online_return_policy] = mock_rpc + + request = {} + client.update_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_online_return_policy(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_update_online_return_policy_rest_required_fields(request_type=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_online_return_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_online_return_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_online_return_policy.OnlineReturnPolicy() + # 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': "patch", + '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 = gsma_online_return_policy.OnlineReturnPolicy.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.update_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("onlineReturnPolicy", ))) + + +def test_update_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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 = gsma_online_return_policy.OnlineReturnPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = {'online_return_policy': {'name': 'accounts/sample1/onlineReturnPolicies/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_online_return_policy.OnlineReturnPolicy.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.update_online_return_policy(**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/accounts/v1beta/{online_return_policy.name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + + +def test_update_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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.update_online_return_policy( + gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(), + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( + 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_online_return_policy in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_online_return_policy] = mock_rpc + + request = {} + client.delete_online_return_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_online_return_policy(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_online_return_policy_rest_required_fields(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): + transport_class = transports.OnlineReturnPolicyServiceRestTransport + + 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_online_return_policy._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_online_return_policy._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 = OnlineReturnPolicyServiceClient( + 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_online_return_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_online_return_policy_rest_unset_required_fields(): + transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_online_return_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_online_return_policy_rest_flattened(): + client = OnlineReturnPolicyServiceClient( + 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/onlineReturnPolicies/sample2'} + + # 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_online_return_policy(**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/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + + +def test_delete_online_return_policy_rest_flattened_error(transport: str = 'rest'): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy( + online_return_policy.DeleteOnlineReturnPolicyRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + 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 = OnlineReturnPolicyServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OnlineReturnPolicyServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OnlineReturnPolicyServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + transports.OnlineReturnPolicyServiceRestTransport, +]) +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 = OnlineReturnPolicyServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = OnlineReturnPolicyServiceClient( + 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_get_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + call.return_value = online_return_policy.OnlineReturnPolicy() + client.get_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.GetOnlineReturnPolicyRequest() + + 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_list_online_return_policies_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + client.list_online_return_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() + + 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_create_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + client.create_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + 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_update_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + call.return_value = gsma_online_return_policy.OnlineReturnPolicy() + client.update_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + + 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_online_return_policy_empty_call_grpc(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + call.return_value = None + client.delete_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = OnlineReturnPolicyServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + 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_get_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + await client.get_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.GetOnlineReturnPolicyRequest() + + 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_list_online_return_policies_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token='next_page_token_value', + )) + await client.list_online_return_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() + + 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_create_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + await client.create_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + 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_update_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + )) + await client.update_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + + 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_online_return_policy_empty_call_grpc_asyncio(): + client = OnlineReturnPolicyServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = OnlineReturnPolicyServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_online_return_policy_rest_bad_request(request_type=online_return_policy.GetOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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.get_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.GetOnlineReturnPolicyRequest, + dict, +]) +def test_get_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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 = online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + + # 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 = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_get_online_return_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = online_return_policy.GetOnlineReturnPolicyRequest.pb(online_return_policy.GetOnlineReturnPolicyRequest()) + 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 = online_return_policy.OnlineReturnPolicy.to_json(online_return_policy.OnlineReturnPolicy()) + req.return_value.content = return_value + + request = online_return_policy.GetOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = online_return_policy.OnlineReturnPolicy() + post_with_metadata.return_value = online_return_policy.OnlineReturnPolicy(), metadata + + client.get_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_online_return_policies_rest_bad_request(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_online_return_policies(request) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.ListOnlineReturnPoliciesRequest, + dict, +]) +def test_list_online_return_policies_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = online_return_policy.ListOnlineReturnPoliciesResponse( + 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_online_return_policies_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_list_online_return_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = online_return_policy.ListOnlineReturnPoliciesRequest.pb(online_return_policy.ListOnlineReturnPoliciesRequest()) + 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 = online_return_policy.ListOnlineReturnPoliciesResponse.to_json(online_return_policy.ListOnlineReturnPoliciesResponse()) + req.return_value.content = return_value + + request = online_return_policy.ListOnlineReturnPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() + post_with_metadata.return_value = online_return_policy.ListOnlineReturnPoliciesResponse(), metadata + + client.list_online_return_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_online_return_policy_rest_bad_request(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + dict, +]) +def test_create_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["online_return_policy"] = {'name': 'name_value', 'return_policy_id': 'return_policy_id_value', 'label': 'label_value', 'countries': ['countries_value1', 'countries_value2'], 'policy': {'type_': 1, 'days': 433}, 'seasonal_overrides': [{'return_days': 1200, 'return_until_date': {'year': 433, 'month': 550, 'day': 318}, 'label': 'label_value', 'start_date': {}, 'end_date': {}}], 'restocking_fee': {'fixed_fee': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'micro_percent': 1386}, 'return_methods': [1], 'item_conditions': [1], 'return_shipping_fee': {'type_': 1, 'fixed_fee': {}}, 'return_policy_uri': 'return_policy_uri_value', 'accept_defective_only': True, 'process_refund_days': 2034, 'accept_exchange': True, 'return_label_source': 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.meta.fields["online_return_policy"] + + 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["online_return_policy"].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["online_return_policy"][field])): + del request_init["online_return_policy"][field][i][subfield] + else: + del request_init["online_return_policy"][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 = gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + + # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_create_online_return_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb(gsma_online_return_policy.CreateOnlineReturnPolicyRequest()) + 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 = gsma_online_return_policy.OnlineReturnPolicy.to_json(gsma_online_return_policy.OnlineReturnPolicy()) + req.return_value.content = return_value + + request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_online_return_policy.OnlineReturnPolicy() + post_with_metadata.return_value = gsma_online_return_policy.OnlineReturnPolicy(), metadata + + client.create_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_online_return_policy_rest_bad_request(request_type=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'online_return_policy': {'name': 'accounts/sample1/onlineReturnPolicies/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.update_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, + dict, +]) +def test_update_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'online_return_policy': {'name': 'accounts/sample1/onlineReturnPolicies/sample2'}} + request_init["online_return_policy"] = {'name': 'accounts/sample1/onlineReturnPolicies/sample2', 'return_policy_id': 'return_policy_id_value', 'label': 'label_value', 'countries': ['countries_value1', 'countries_value2'], 'policy': {'type_': 1, 'days': 433}, 'seasonal_overrides': [{'return_days': 1200, 'return_until_date': {'year': 433, 'month': 550, 'day': 318}, 'label': 'label_value', 'start_date': {}, 'end_date': {}}], 'restocking_fee': {'fixed_fee': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'micro_percent': 1386}, 'return_methods': [1], 'item_conditions': [1], 'return_shipping_fee': {'type_': 1, 'fixed_fee': {}}, 'return_policy_uri': 'return_policy_uri_value', 'accept_defective_only': True, 'process_refund_days': 2034, 'accept_exchange': True, 'return_label_source': 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.meta.fields["online_return_policy"] + + 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["online_return_policy"].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["online_return_policy"][field])): + del request_init["online_return_policy"][field][i][subfield] + else: + del request_init["online_return_policy"][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 = gsma_online_return_policy.OnlineReturnPolicy( + name='name_value', + return_policy_id='return_policy_id_value', + label='label_value', + countries=['countries_value'], + return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri='return_policy_uri_value', + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + + # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.update_online_return_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) + assert response.name == 'name_value' + assert response.return_policy_id == 'return_policy_id_value' + assert response.label == 'label_value' + assert response.countries == ['countries_value'] + assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] + assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] + assert response.return_policy_uri == 'return_policy_uri_value' + assert response.accept_defective_only is True + assert response.process_refund_days == 2034 + assert response.accept_exchange is True + assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_update_online_return_policy") as post, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_update_online_return_policy_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_update_online_return_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.pb(gsma_online_return_policy.UpdateOnlineReturnPolicyRequest()) + 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 = gsma_online_return_policy.OnlineReturnPolicy.to_json(gsma_online_return_policy.OnlineReturnPolicy()) + req.return_value.content = return_value + + request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_online_return_policy.OnlineReturnPolicy() + post_with_metadata.return_value = gsma_online_return_policy.OnlineReturnPolicy(), metadata + + client.update_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_online_return_policy_rest_bad_request(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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.delete_online_return_policy(request) + + +@pytest.mark.parametrize("request_type", [ + online_return_policy.DeleteOnlineReturnPolicyRequest, + dict, +]) +def test_delete_online_return_policy_rest_call_success(request_type): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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 = 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_online_return_policy(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_online_return_policy_rest_interceptors(null_interceptor): + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) + client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "pre_delete_online_return_policy") as pre: + pre.assert_not_called() + pb_message = online_return_policy.DeleteOnlineReturnPolicyRequest.pb(online_return_policy.DeleteOnlineReturnPolicyRequest()) + 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = OnlineReturnPolicyServiceClient( + 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_get_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_online_return_policy), + '__call__') as call: + client.get_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.GetOnlineReturnPolicyRequest() + + 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_list_online_return_policies_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_online_return_policies), + '__call__') as call: + client.list_online_return_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() + + 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_create_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_online_return_policy), + '__call__') as call: + client.create_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + + 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_update_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_online_return_policy), + '__call__') as call: + client.update_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() + + 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_online_return_policy_empty_call_rest(): + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_online_return_policy), + '__call__') as call: + client.delete_online_return_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.OnlineReturnPolicyServiceGrpcTransport, + ) + +def test_online_return_policy_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OnlineReturnPolicyServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_online_return_policy_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.OnlineReturnPolicyServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_online_return_policy', + 'list_online_return_policies', + 'create_online_return_policy', + 'update_online_return_policy', + 'delete_online_return_policy', + ) + 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_online_return_policy_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_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OnlineReturnPolicyServiceTransport( + 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_online_return_policy_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_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OnlineReturnPolicyServiceTransport() + adc.assert_called_once() + + +def test_online_return_policy_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) + OnlineReturnPolicyServiceClient() + 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.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + ], +) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + transports.OnlineReturnPolicyServiceRestTransport, + ], +) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, grpc_helpers), + (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +def test_online_return_policy_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_online_return_policy_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.OnlineReturnPolicyServiceRestTransport ( + 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_online_return_policy_service_host_no_port(transport_name): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy_service_host_with_port(transport_name): + client = OnlineReturnPolicyServiceClient( + 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_online_return_policy_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OnlineReturnPolicyServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OnlineReturnPolicyServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_online_return_policy._session + session2 = client2.transport.get_online_return_policy._session + assert session1 != session2 + session1 = client1.transport.list_online_return_policies._session + session2 = client2.transport.list_online_return_policies._session + assert session1 != session2 + session1 = client1.transport.create_online_return_policy._session + session2 = client2.transport.create_online_return_policy._session + assert session1 != session2 + session1 = client1.transport.update_online_return_policy._session + session2 = client2.transport.update_online_return_policy._session + assert session1 != session2 + session1 = client1.transport.delete_online_return_policy._session + session2 = client2.transport.delete_online_return_policy._session + assert session1 != session2 +def test_online_return_policy_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OnlineReturnPolicyServiceGrpcTransport( + 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_online_return_policy_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport( + 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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +def test_online_return_policy_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_online_return_policy_path(): + account = "squid" + return_policy = "clam" + expected = "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) + actual = OnlineReturnPolicyServiceClient.online_return_policy_path(account, return_policy) + assert expected == actual + + +def test_parse_online_return_policy_path(): + expected = { + "account": "whelk", + "return_policy": "octopus", + } + path = OnlineReturnPolicyServiceClient.online_return_policy_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_online_return_policy_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = OnlineReturnPolicyServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = OnlineReturnPolicyServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = OnlineReturnPolicyServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = OnlineReturnPolicyServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = OnlineReturnPolicyServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = OnlineReturnPolicyServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = OnlineReturnPolicyServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = OnlineReturnPolicyServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = OnlineReturnPolicyServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = OnlineReturnPolicyServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OnlineReturnPolicyServiceClient.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.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: + client = OnlineReturnPolicyServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = OnlineReturnPolicyServiceClient.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 = OnlineReturnPolicyServiceClient( + 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 = OnlineReturnPolicyServiceAsyncClient( + 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 = OnlineReturnPolicyServiceClient( + 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 = OnlineReturnPolicyServiceClient( + 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", [ + (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport), + (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py new file mode 100644 index 000000000000..b30cc1dc4bae --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py @@ -0,0 +1,4435 @@ +# -*- 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.shopping.merchant_accounts_v1beta.services.programs_service import ProgramsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.programs_service import ProgramsServiceClient +from google.shopping.merchant_accounts_v1beta.services.programs_service import pagers +from google.shopping.merchant_accounts_v1beta.services.programs_service import transports +from google.shopping.merchant_accounts_v1beta.types import programs +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 ProgramsServiceClient._get_default_mtls_endpoint(None) is None + assert ProgramsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProgramsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ProgramsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ProgramsServiceClient._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 ProgramsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ProgramsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ProgramsServiceClient._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 ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, False) is None + assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ProgramsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ProgramsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ProgramsServiceClient._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 ProgramsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ProgramsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ProgramsServiceClient._get_universe_domain(None, None) == ProgramsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ProgramsServiceClient._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 = ProgramsServiceClient(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 = ProgramsServiceClient(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", [ + (ProgramsServiceClient, "grpc"), + (ProgramsServiceAsyncClient, "grpc_asyncio"), + (ProgramsServiceClient, "rest"), +]) +def test_programs_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.ProgramsServiceGrpcTransport, "grpc"), + (transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProgramsServiceRestTransport, "rest"), +]) +def test_programs_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", [ + (ProgramsServiceClient, "grpc"), + (ProgramsServiceAsyncClient, "grpc_asyncio"), + (ProgramsServiceClient, "rest"), +]) +def test_programs_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_programs_service_client_get_transport_class(): + transport = ProgramsServiceClient.get_transport_class() + available_transports = [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceRestTransport, + ] + assert transport in available_transports + + transport = ProgramsServiceClient.get_transport_class("grpc") + assert transport == transports.ProgramsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), +]) +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +def test_programs_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(ProgramsServiceClient, '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(ProgramsServiceClient, '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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "true"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "false"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "true"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_programs_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", [ + ProgramsServiceClient, ProgramsServiceAsyncClient +]) +@mock.patch.object(ProgramsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceAsyncClient)) +def test_programs_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", [ + ProgramsServiceClient, ProgramsServiceAsyncClient +]) +@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) +@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +def test_programs_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ProgramsServiceClient._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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), +]) +def test_programs_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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", None), +]) +def test_programs_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_programs_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.programs_service.transports.ProgramsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProgramsServiceClient( + 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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_programs_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", [ + programs.GetProgramRequest, + dict, +]) +def test_get_program(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + ) + response = client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.GetProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +def test_get_program_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 = ProgramsServiceClient( + 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 = programs.GetProgramRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_program(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.GetProgramRequest( + name='name_value', + ) + +def test_get_program_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 = ProgramsServiceClient( + 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.get_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_program] = mock_rpc + request = {} + client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_program(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_get_program_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 = ProgramsServiceAsyncClient( + 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.get_program in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_program] = mock_rpc + + request = {} + await client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_program(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_get_program_async(transport: str = 'grpc_asyncio', request_type=programs.GetProgramRequest): + client = ProgramsServiceAsyncClient( + 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.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + response = await client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.GetProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.asyncio +async def test_get_program_async_from_dict(): + await test_get_program_async(request_type=dict) + +def test_get_program_field_headers(): + client = ProgramsServiceClient( + 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 = programs.GetProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value = programs.Program() + client.get_program(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_get_program_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.GetProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + await client.get_program(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_get_program_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_program( + 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_get_program_flattened_error(): + client = ProgramsServiceClient( + 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.get_program( + programs.GetProgramRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_program_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_program( + 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_get_program_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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.get_program( + programs.GetProgramRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + programs.ListProgramsRequest, + dict, +]) +def test_list_programs(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.ListProgramsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.ListProgramsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProgramsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_programs_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 = ProgramsServiceClient( + 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 = programs.ListProgramsRequest( + 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_programs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_programs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.ListProgramsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_programs_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 = ProgramsServiceClient( + 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_programs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_programs] = mock_rpc + request = {} + client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_programs(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_programs_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 = ProgramsServiceAsyncClient( + 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_programs 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_programs] = mock_rpc + + request = {} + await client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_programs(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_programs_async(transport: str = 'grpc_asyncio', request_type=programs.ListProgramsRequest): + client = ProgramsServiceAsyncClient( + 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_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.ListProgramsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProgramsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_programs_async_from_dict(): + await test_list_programs_async(request_type=dict) + +def test_list_programs_field_headers(): + client = ProgramsServiceClient( + 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 = programs.ListProgramsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + call.return_value = programs.ListProgramsResponse() + client.list_programs(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_programs_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.ListProgramsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) + await client.list_programs(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_programs_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.ListProgramsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_programs( + 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_programs_flattened_error(): + client = ProgramsServiceClient( + 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_programs( + programs.ListProgramsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_programs_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.ListProgramsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_programs( + 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_programs_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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_programs( + programs.ListProgramsRequest(), + parent='parent_value', + ) + + +def test_list_programs_pager(transport_name: str = "grpc"): + client = ProgramsServiceClient( + 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_programs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_programs(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, programs.Program) + for i in results) +def test_list_programs_pages(transport_name: str = "grpc"): + client = ProgramsServiceClient( + 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_programs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + RuntimeError, + ) + pages = list(client.list_programs(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_programs_async_pager(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_programs(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, programs.Program) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_programs_async_pages(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + 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_programs(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", [ + programs.EnableProgramRequest, + dict, +]) +def test_enable_program(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + ) + response = client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.EnableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +def test_enable_program_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 = ProgramsServiceClient( + 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 = programs.EnableProgramRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.enable_program(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.EnableProgramRequest( + name='name_value', + ) + +def test_enable_program_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 = ProgramsServiceClient( + 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.enable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc + request = {} + client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enable_program(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_enable_program_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 = ProgramsServiceAsyncClient( + 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.enable_program 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.enable_program] = mock_rpc + + request = {} + await client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.enable_program(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_enable_program_async(transport: str = 'grpc_asyncio', request_type=programs.EnableProgramRequest): + client = ProgramsServiceAsyncClient( + 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.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + response = await client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.EnableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.asyncio +async def test_enable_program_async_from_dict(): + await test_enable_program_async(request_type=dict) + +def test_enable_program_field_headers(): + client = ProgramsServiceClient( + 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 = programs.EnableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value = programs.Program() + client.enable_program(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_enable_program_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.EnableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + await client.enable_program(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_enable_program_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.enable_program( + 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_enable_program_flattened_error(): + client = ProgramsServiceClient( + 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.enable_program( + programs.EnableProgramRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_enable_program_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.enable_program( + 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_enable_program_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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.enable_program( + programs.EnableProgramRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + programs.DisableProgramRequest, + dict, +]) +def test_disable_program(request_type, transport: str = 'grpc'): + client = ProgramsServiceClient( + 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.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + ) + response = client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = programs.DisableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +def test_disable_program_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 = ProgramsServiceClient( + 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 = programs.DisableProgramRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.disable_program(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == programs.DisableProgramRequest( + name='name_value', + ) + +def test_disable_program_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 = ProgramsServiceClient( + 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.disable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc + request = {} + client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.disable_program(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_disable_program_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 = ProgramsServiceAsyncClient( + 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.disable_program 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.disable_program] = mock_rpc + + request = {} + await client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.disable_program(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_disable_program_async(transport: str = 'grpc_asyncio', request_type=programs.DisableProgramRequest): + client = ProgramsServiceAsyncClient( + 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.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + response = await client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = programs.DisableProgramRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.asyncio +async def test_disable_program_async_from_dict(): + await test_disable_program_async(request_type=dict) + +def test_disable_program_field_headers(): + client = ProgramsServiceClient( + 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 = programs.DisableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value = programs.Program() + client.disable_program(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_disable_program_field_headers_async(): + client = ProgramsServiceAsyncClient( + 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 = programs.DisableProgramRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + await client.disable_program(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_disable_program_flattened(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.disable_program( + 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_disable_program_flattened_error(): + client = ProgramsServiceClient( + 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.disable_program( + programs.DisableProgramRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_disable_program_flattened_async(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = programs.Program() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.disable_program( + 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_disable_program_flattened_error_async(): + client = ProgramsServiceAsyncClient( + 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.disable_program( + programs.DisableProgramRequest(), + name='name_value', + ) + + +def test_get_program_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 = ProgramsServiceClient( + 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.get_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_program] = mock_rpc + + request = {} + client.get_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_program(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_get_program_rest_required_fields(request_type=programs.GetProgramRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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()).get_program._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_program._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.Program() + # 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 = programs.Program.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.get_program(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_program_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_program._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_program_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.Program() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = programs.Program.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.get_program(**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/accounts/v1beta/{name=accounts/*/programs/*}" % client.transport._host, args[1]) + + +def test_get_program_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_program( + programs.GetProgramRequest(), + name='name_value', + ) + + +def test_list_programs_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 = ProgramsServiceClient( + 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_programs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_programs] = mock_rpc + + request = {} + client.list_programs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_programs(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_programs_rest_required_fields(request_type=programs.ListProgramsRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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_programs._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_programs._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.ListProgramsResponse() + # 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 = programs.ListProgramsResponse.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_programs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_programs_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_programs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_programs_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.ListProgramsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = programs.ListProgramsResponse.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_programs(**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/accounts/v1beta/{parent=accounts/*}/programs" % client.transport._host, args[1]) + + +def test_list_programs_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + 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_programs( + programs.ListProgramsRequest(), + parent='parent_value', + ) + + +def test_list_programs_rest_pager(transport: str = 'rest'): + client = ProgramsServiceClient( + 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 = ( + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + programs.Program(), + ], + next_page_token='abc', + ), + programs.ListProgramsResponse( + programs=[], + next_page_token='def', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + ], + next_page_token='ghi', + ), + programs.ListProgramsResponse( + programs=[ + programs.Program(), + programs.Program(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(programs.ListProgramsResponse.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'} + + pager = client.list_programs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, programs.Program) + for i in results) + + pages = list(client.list_programs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_enable_program_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 = ProgramsServiceClient( + 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.enable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc + + request = {} + client.enable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enable_program(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_enable_program_rest_required_fields(request_type=programs.EnableProgramRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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()).enable_program._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()).enable_program._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.Program() + # 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 = programs.Program.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.enable_program(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_enable_program_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.enable_program._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_enable_program_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.Program() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = programs.Program.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.enable_program(**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/accounts/v1beta/{name=accounts/*/programs/*}:enable" % client.transport._host, args[1]) + + +def test_enable_program_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + 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.enable_program( + programs.EnableProgramRequest(), + name='name_value', + ) + + +def test_disable_program_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 = ProgramsServiceClient( + 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.disable_program in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc + + request = {} + client.disable_program(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.disable_program(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_disable_program_rest_required_fields(request_type=programs.DisableProgramRequest): + transport_class = transports.ProgramsServiceRestTransport + + 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()).disable_program._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()).disable_program._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 = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = programs.Program() + # 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 = programs.Program.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.disable_program(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_disable_program_rest_unset_required_fields(): + transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.disable_program._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_disable_program_rest_flattened(): + client = ProgramsServiceClient( + 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 = programs.Program() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/programs/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = programs.Program.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.disable_program(**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/accounts/v1beta/{name=accounts/*/programs/*}:disable" % client.transport._host, args[1]) + + +def test_disable_program_rest_flattened_error(transport: str = 'rest'): + client = ProgramsServiceClient( + 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.disable_program( + programs.DisableProgramRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProgramsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProgramsServiceClient( + 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 = ProgramsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProgramsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProgramsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProgramsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProgramsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + transports.ProgramsServiceRestTransport, +]) +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 = ProgramsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ProgramsServiceClient( + 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_get_program_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + call.return_value = programs.Program() + client.get_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.GetProgramRequest() + + 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_list_programs_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + call.return_value = programs.ListProgramsResponse() + client.list_programs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.ListProgramsRequest() + + 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_enable_program_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + call.return_value = programs.Program() + client.enable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.EnableProgramRequest() + + 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_disable_program_empty_call_grpc(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + call.return_value = programs.Program() + client.disable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.DisableProgramRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ProgramsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + 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_get_program_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + await client.get_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.GetProgramRequest() + + 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_list_programs_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( + next_page_token='next_page_token_value', + )) + await client.list_programs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.ListProgramsRequest() + + 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_enable_program_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + await client.enable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.EnableProgramRequest() + + 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_disable_program_empty_call_grpc_asyncio(): + client = ProgramsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_value'], + )) + await client.disable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.DisableProgramRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ProgramsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_program_rest_bad_request(request_type=programs.GetProgramRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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.get_program(request) + + +@pytest.mark.parametrize("request_type", [ + programs.GetProgramRequest, + dict, +]) +def test_get_program_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_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 = programs.Program.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.get_program(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_program_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_get_program") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_get_program_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_get_program") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.GetProgramRequest.pb(programs.GetProgramRequest()) + 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 = programs.Program.to_json(programs.Program()) + req.return_value.content = return_value + + request = programs.GetProgramRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.Program() + post_with_metadata.return_value = programs.Program(), metadata + + client.get_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_programs_rest_bad_request(request_type=programs.ListProgramsRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_programs(request) + + +@pytest.mark.parametrize("request_type", [ + programs.ListProgramsRequest, + dict, +]) +def test_list_programs_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = programs.ListProgramsResponse( + 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 = programs.ListProgramsResponse.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_programs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProgramsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_programs_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_list_programs") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_list_programs_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_list_programs") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.ListProgramsRequest.pb(programs.ListProgramsRequest()) + 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 = programs.ListProgramsResponse.to_json(programs.ListProgramsResponse()) + req.return_value.content = return_value + + request = programs.ListProgramsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.ListProgramsResponse() + post_with_metadata.return_value = programs.ListProgramsResponse(), metadata + + client.list_programs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_enable_program_rest_bad_request(request_type=programs.EnableProgramRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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.enable_program(request) + + +@pytest.mark.parametrize("request_type", [ + programs.EnableProgramRequest, + dict, +]) +def test_enable_program_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_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 = programs.Program.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.enable_program(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_enable_program_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_enable_program") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_enable_program_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_enable_program") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.EnableProgramRequest.pb(programs.EnableProgramRequest()) + 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 = programs.Program.to_json(programs.Program()) + req.return_value.content = return_value + + request = programs.EnableProgramRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.Program() + post_with_metadata.return_value = programs.Program(), metadata + + client.enable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_disable_program_rest_bad_request(request_type=programs.DisableProgramRequest): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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.disable_program(request) + + +@pytest.mark.parametrize("request_type", [ + programs.DisableProgramRequest, + dict, +]) +def test_disable_program_rest_call_success(request_type): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( + name='name_value', + documentation_uri='documentation_uri_value', + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=['active_region_codes_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 = programs.Program.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.disable_program(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, programs.Program) + assert response.name == 'name_value' + assert response.documentation_uri == 'documentation_uri_value' + assert response.state == programs.Program.State.NOT_ELIGIBLE + assert response.active_region_codes == ['active_region_codes_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_disable_program_rest_interceptors(null_interceptor): + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), + ) + client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_disable_program") as post, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_disable_program_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_disable_program") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = programs.DisableProgramRequest.pb(programs.DisableProgramRequest()) + 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 = programs.Program.to_json(programs.Program()) + req.return_value.content = return_value + + request = programs.DisableProgramRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = programs.Program() + post_with_metadata.return_value = programs.Program(), metadata + + client.disable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = ProgramsServiceClient( + 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_get_program_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_program), + '__call__') as call: + client.get_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.GetProgramRequest() + + 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_list_programs_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_programs), + '__call__') as call: + client.list_programs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.ListProgramsRequest() + + 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_enable_program_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_program), + '__call__') as call: + client.enable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.EnableProgramRequest() + + 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_disable_program_empty_call_rest(): + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.disable_program), + '__call__') as call: + client.disable_program(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = programs.DisableProgramRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProgramsServiceGrpcTransport, + ) + +def test_programs_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProgramsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_programs_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.programs_service.transports.ProgramsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProgramsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_program', + 'list_programs', + 'enable_program', + 'disable_program', + ) + 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_programs_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_accounts_v1beta.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProgramsServiceTransport( + 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_programs_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_accounts_v1beta.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProgramsServiceTransport() + adc.assert_called_once() + + +def test_programs_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) + ProgramsServiceClient() + 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.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + ], +) +def test_programs_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.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + transports.ProgramsServiceRestTransport, + ], +) +def test_programs_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.ProgramsServiceGrpcTransport, grpc_helpers), + (transports.ProgramsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +def test_programs_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_programs_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.ProgramsServiceRestTransport ( + 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_programs_service_host_no_port(transport_name): + client = ProgramsServiceClient( + 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_programs_service_host_with_port(transport_name): + client = ProgramsServiceClient( + 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_programs_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProgramsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProgramsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_program._session + session2 = client2.transport.get_program._session + assert session1 != session2 + session1 = client1.transport.list_programs._session + session2 = client2.transport.list_programs._session + assert session1 != session2 + session1 = client1.transport.enable_program._session + session2 = client2.transport.enable_program._session + assert session1 != session2 + session1 = client1.transport.disable_program._session + session2 = client2.transport.disable_program._session + assert session1 != session2 +def test_programs_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProgramsServiceGrpcTransport( + 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_programs_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProgramsServiceGrpcAsyncIOTransport( + 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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +def test_programs_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_program_path(): + account = "squid" + program = "clam" + expected = "accounts/{account}/programs/{program}".format(account=account, program=program, ) + actual = ProgramsServiceClient.program_path(account, program) + assert expected == actual + + +def test_parse_program_path(): + expected = { + "account": "whelk", + "program": "octopus", + } + path = ProgramsServiceClient.program_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_program_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProgramsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = ProgramsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProgramsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = ProgramsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProgramsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = ProgramsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ProgramsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = ProgramsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProgramsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = ProgramsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProgramsServiceClient.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.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: + client = ProgramsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ProgramsServiceClient.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 = ProgramsServiceClient( + 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 = ProgramsServiceAsyncClient( + 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 = ProgramsServiceClient( + 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 = ProgramsServiceClient( + 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", [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py new file mode 100644 index 000000000000..1d304a338ce6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py @@ -0,0 +1,5216 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.regions_service import RegionsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.regions_service import RegionsServiceClient +from google.shopping.merchant_accounts_v1beta.services.regions_service import pagers +from google.shopping.merchant_accounts_v1beta.services.regions_service import transports +from google.shopping.merchant_accounts_v1beta.types import regions +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 RegionsServiceClient._get_default_mtls_endpoint(None) is None + assert RegionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + RegionsServiceClient._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 RegionsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionsServiceClient._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 RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, False) is None + assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionsServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert RegionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + assert RegionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionsServiceClient._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 RegionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert RegionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert RegionsServiceClient._get_universe_domain(None, None) == RegionsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + RegionsServiceClient._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 = RegionsServiceClient(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 = RegionsServiceClient(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", [ + (RegionsServiceClient, "grpc"), + (RegionsServiceAsyncClient, "grpc_asyncio"), + (RegionsServiceClient, "rest"), +]) +def test_regions_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.RegionsServiceGrpcTransport, "grpc"), + (transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionsServiceRestTransport, "rest"), +]) +def test_regions_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", [ + (RegionsServiceClient, "grpc"), + (RegionsServiceAsyncClient, "grpc_asyncio"), + (RegionsServiceClient, "rest"), +]) +def test_regions_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_regions_service_client_get_transport_class(): + transport = RegionsServiceClient.get_transport_class() + available_transports = [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceRestTransport, + ] + assert transport in available_transports + + transport = RegionsServiceClient.get_transport_class("grpc") + assert transport == transports.RegionsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), +]) +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +def test_regions_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(RegionsServiceClient, '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(RegionsServiceClient, '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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "true"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "false"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "true"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_regions_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", [ + RegionsServiceClient, RegionsServiceAsyncClient +]) +@mock.patch.object(RegionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceAsyncClient)) +def test_regions_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", [ + RegionsServiceClient, RegionsServiceAsyncClient +]) +@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) +@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +def test_regions_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionsServiceClient._DEFAULT_UNIVERSE + default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = RegionsServiceClient._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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), +]) +def test_regions_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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", None), +]) +def test_regions_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_regions_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.regions_service.transports.RegionsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegionsServiceClient( + 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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_regions_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", [ + regions.GetRegionRequest, + dict, +]) +def test_get_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region( + name='name_value', + display_name='display_name_value', + ) + response = client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.GetRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_get_region_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 = RegionsServiceClient( + 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 = regions.GetRegionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.GetRegionRequest( + name='name_value', + ) + +def test_get_region_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 = RegionsServiceClient( + 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.get_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_region] = mock_rpc + request = {} + client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_region(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_get_region_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 = RegionsServiceAsyncClient( + 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.get_region in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_region] = mock_rpc + + request = {} + await client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_region(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_get_region_async(transport: str = 'grpc_asyncio', request_type=regions.GetRegionRequest): + client = RegionsServiceAsyncClient( + 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.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + response = await client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.GetRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_region_async_from_dict(): + await test_get_region_async(request_type=dict) + +def test_get_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.GetRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value = regions.Region() + client.get_region(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_get_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.GetRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + await client.get_region(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_get_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_region( + 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_get_region_flattened_error(): + client = RegionsServiceClient( + 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.get_region( + regions.GetRegionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_region( + 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_get_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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.get_region( + regions.GetRegionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + regions.CreateRegionRequest, + dict, +]) +def test_create_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region( + name='name_value', + display_name='display_name_value', + ) + response = client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.CreateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_create_region_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 = RegionsServiceClient( + 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 = regions.CreateRegionRequest( + parent='parent_value', + region_id='region_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.CreateRegionRequest( + parent='parent_value', + region_id='region_id_value', + ) + +def test_create_region_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 = RegionsServiceClient( + 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.create_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_region] = mock_rpc + request = {} + client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_region(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_create_region_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 = RegionsServiceAsyncClient( + 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.create_region in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_region] = mock_rpc + + request = {} + await client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_region(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_create_region_async(transport: str = 'grpc_asyncio', request_type=regions.CreateRegionRequest): + client = RegionsServiceAsyncClient( + 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.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + response = await client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.CreateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_region_async_from_dict(): + await test_create_region_async(request_type=dict) + +def test_create_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.CreateRegionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value = regions.Region() + client.create_region(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_create_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.CreateRegionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + await client.create_region(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_create_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_region( + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_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 + arg = args[0].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].region_id + mock_val = 'region_id_value' + assert arg == mock_val + + +def test_create_region_flattened_error(): + client = RegionsServiceClient( + 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.create_region( + regions.CreateRegionRequest(), + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_value', + ) + +@pytest.mark.asyncio +async def test_create_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_region( + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_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 + arg = args[0].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].region_id + mock_val = 'region_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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.create_region( + regions.CreateRegionRequest(), + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + regions.UpdateRegionRequest, + dict, +]) +def test_update_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region( + name='name_value', + display_name='display_name_value', + ) + response = client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.UpdateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +def test_update_region_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 = RegionsServiceClient( + 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 = regions.UpdateRegionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.UpdateRegionRequest( + ) + +def test_update_region_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 = RegionsServiceClient( + 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.update_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_region] = mock_rpc + request = {} + client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_region(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_update_region_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 = RegionsServiceAsyncClient( + 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.update_region in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_region] = mock_rpc + + request = {} + await client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_region(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_update_region_async(transport: str = 'grpc_asyncio', request_type=regions.UpdateRegionRequest): + client = RegionsServiceAsyncClient( + 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.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + response = await client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.UpdateRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_region_async_from_dict(): + await test_update_region_async(request_type=dict) + +def test_update_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.UpdateRegionRequest() + + request.region.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value = regions.Region() + client.update_region(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', + 'region.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.UpdateRegionRequest() + + request.region.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + await client.update_region(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', + 'region.name=name_value', + ) in kw['metadata'] + + +def test_update_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_region( + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_region_flattened_error(): + client = RegionsServiceClient( + 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.update_region( + regions.UpdateRegionRequest(), + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.Region() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_region( + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].region + mock_val = regions.Region(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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.update_region( + regions.UpdateRegionRequest(), + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + regions.DeleteRegionRequest, + dict, +]) +def test_delete_region(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.DeleteRegionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_region_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 = RegionsServiceClient( + 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 = regions.DeleteRegionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_region(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.DeleteRegionRequest( + name='name_value', + ) + +def test_delete_region_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 = RegionsServiceClient( + 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_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_region] = mock_rpc + request = {} + client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_region(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_region_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 = RegionsServiceAsyncClient( + 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_region 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_region] = mock_rpc + + request = {} + await client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_region(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_region_async(transport: str = 'grpc_asyncio', request_type=regions.DeleteRegionRequest): + client = RegionsServiceAsyncClient( + 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_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.DeleteRegionRequest() + 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_region_async_from_dict(): + await test_delete_region_async(request_type=dict) + +def test_delete_region_field_headers(): + client = RegionsServiceClient( + 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 = regions.DeleteRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value = None + client.delete_region(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_region_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.DeleteRegionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_region(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_region_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__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_region( + 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_region_flattened_error(): + client = RegionsServiceClient( + 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_region( + regions.DeleteRegionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_region_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__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_region( + 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_region_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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_region( + regions.DeleteRegionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + regions.ListRegionsRequest, + dict, +]) +def test_list_regions(request_type, transport: str = 'grpc'): + client = RegionsServiceClient( + 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_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.ListRegionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = regions.ListRegionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_regions_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 = RegionsServiceClient( + 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 = regions.ListRegionsRequest( + 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_regions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_regions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == regions.ListRegionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_regions_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 = RegionsServiceClient( + 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_regions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regions] = mock_rpc + request = {} + client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regions(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_regions_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 = RegionsServiceAsyncClient( + 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_regions 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_regions] = mock_rpc + + request = {} + await client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_regions(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_regions_async(transport: str = 'grpc_asyncio', request_type=regions.ListRegionsRequest): + client = RegionsServiceAsyncClient( + 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_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = regions.ListRegionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_regions_async_from_dict(): + await test_list_regions_async(request_type=dict) + +def test_list_regions_field_headers(): + client = RegionsServiceClient( + 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 = regions.ListRegionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + call.return_value = regions.ListRegionsResponse() + client.list_regions(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_regions_field_headers_async(): + client = RegionsServiceAsyncClient( + 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 = regions.ListRegionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) + await client.list_regions(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_regions_flattened(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.ListRegionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_regions( + 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_regions_flattened_error(): + client = RegionsServiceClient( + 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_regions( + regions.ListRegionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_regions_flattened_async(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = regions.ListRegionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_regions( + 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_regions_flattened_error_async(): + client = RegionsServiceAsyncClient( + 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_regions( + regions.ListRegionsRequest(), + parent='parent_value', + ) + + +def test_list_regions_pager(transport_name: str = "grpc"): + client = RegionsServiceClient( + 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_regions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_regions(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, regions.Region) + for i in results) +def test_list_regions_pages(transport_name: str = "grpc"): + client = RegionsServiceClient( + 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_regions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + RuntimeError, + ) + pages = list(client.list_regions(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_regions_async_pager(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_regions(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, regions.Region) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_regions_async_pages(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + 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_regions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_region_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 = RegionsServiceClient( + 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.get_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_region] = mock_rpc + + request = {} + client.get_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_region(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_get_region_rest_required_fields(request_type=regions.GetRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + 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()).get_region._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_region._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 = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.Region() + # 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 = regions.Region.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.get_region(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_region_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.Region() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/regions/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = regions.Region.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.get_region(**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/accounts/v1beta/{name=accounts/*/regions/*}" % client.transport._host, args[1]) + + +def test_get_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_region( + regions.GetRegionRequest(), + name='name_value', + ) + + +def test_create_region_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 = RegionsServiceClient( + 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.create_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_region] = mock_rpc + + request = {} + client.create_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_region(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_create_region_rest_required_fields(request_type=regions.CreateRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["region_id"] = "" + 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 + assert "regionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "regionId" in jsonified_request + assert jsonified_request["regionId"] == request_init["region_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["regionId"] = 'region_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("region_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "regionId" in jsonified_request + assert jsonified_request["regionId"] == 'region_id_value' + + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.Region() + # 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 = regions.Region.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.create_region(request) + + expected_params = [ + ( + "regionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(("regionId", )) & set(("parent", "regionId", "region", ))) + + +def test_create_region_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.Region() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_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 = regions.Region.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.create_region(**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/accounts/v1beta/{parent=accounts/*}/regions" % client.transport._host, args[1]) + + +def test_create_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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.create_region( + regions.CreateRegionRequest(), + parent='parent_value', + region=regions.Region(name='name_value'), + region_id='region_id_value', + ) + + +def test_update_region_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 = RegionsServiceClient( + 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.update_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_region] = mock_rpc + + request = {} + client.update_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_region(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_update_region_rest_required_fields(request_type=regions.UpdateRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.Region() + # 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': "patch", + '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 = regions.Region.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.update_region(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("region", ))) + + +def test_update_region_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.Region() + + # get arguments that satisfy an http rule for this method + sample_request = {'region': {'name': 'accounts/sample1/regions/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = regions.Region.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.update_region(**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/accounts/v1beta/{region.name=accounts/*/regions/*}" % client.transport._host, args[1]) + + +def test_update_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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.update_region( + regions.UpdateRegionRequest(), + region=regions.Region(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_region_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 = RegionsServiceClient( + 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_region in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_region] = mock_rpc + + request = {} + client.delete_region(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_region(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_region_rest_required_fields(request_type=regions.DeleteRegionRequest): + transport_class = transports.RegionsServiceRestTransport + + 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_region._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_region._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 = RegionsServiceClient( + 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_region(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_region_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_region._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_region_rest_flattened(): + client = RegionsServiceClient( + 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/regions/sample2'} + + # 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_region(**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/accounts/v1beta/{name=accounts/*/regions/*}" % client.transport._host, args[1]) + + +def test_delete_region_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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_region( + regions.DeleteRegionRequest(), + name='name_value', + ) + + +def test_list_regions_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 = RegionsServiceClient( + 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_regions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_regions] = mock_rpc + + request = {} + client.list_regions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_regions(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_regions_rest_required_fields(request_type=regions.ListRegionsRequest): + transport_class = transports.RegionsServiceRestTransport + + 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_regions._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_regions._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 = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = regions.ListRegionsResponse() + # 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 = regions.ListRegionsResponse.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_regions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_regions_rest_unset_required_fields(): + transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_regions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_regions_rest_flattened(): + client = RegionsServiceClient( + 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 = regions.ListRegionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = regions.ListRegionsResponse.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_regions(**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/accounts/v1beta/{parent=accounts/*}/regions" % client.transport._host, args[1]) + + +def test_list_regions_rest_flattened_error(transport: str = 'rest'): + client = RegionsServiceClient( + 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_regions( + regions.ListRegionsRequest(), + parent='parent_value', + ) + + +def test_list_regions_rest_pager(transport: str = 'rest'): + client = RegionsServiceClient( + 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 = ( + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + regions.Region(), + ], + next_page_token='abc', + ), + regions.ListRegionsResponse( + regions=[], + next_page_token='def', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + ], + next_page_token='ghi', + ), + regions.ListRegionsResponse( + regions=[ + regions.Region(), + regions.Region(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(regions.ListRegionsResponse.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'} + + pager = client.list_regions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, regions.Region) + for i in results) + + pages = list(client.list_regions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionsServiceClient( + 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 = RegionsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegionsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + transports.RegionsServiceRestTransport, +]) +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 = RegionsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = RegionsServiceClient( + 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_get_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + call.return_value = regions.Region() + client.get_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.GetRegionRequest() + + 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_create_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + call.return_value = regions.Region() + client.create_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.CreateRegionRequest() + + 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_update_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + call.return_value = regions.Region() + client.update_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.UpdateRegionRequest() + + 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_region_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + call.return_value = None + client.delete_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.DeleteRegionRequest() + + 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_list_regions_empty_call_grpc(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + call.return_value = regions.ListRegionsResponse() + client.list_regions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.ListRegionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = RegionsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = RegionsServiceAsyncClient( + 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_get_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + await client.get_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.GetRegionRequest() + + 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_create_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + await client.create_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.CreateRegionRequest() + + 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_update_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( + name='name_value', + display_name='display_name_value', + )) + await client.update_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.UpdateRegionRequest() + + 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_region_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.DeleteRegionRequest() + + 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_list_regions_empty_call_grpc_asyncio(): + client = RegionsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( + next_page_token='next_page_token_value', + )) + await client.list_regions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.ListRegionsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = RegionsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_region_rest_bad_request(request_type=regions.GetRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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.get_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.GetRegionRequest, + dict, +]) +def test_get_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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 = regions.Region( + name='name_value', + display_name='display_name_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 = regions.Region.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.get_region(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_get_region") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_get_region_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_get_region") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.GetRegionRequest.pb(regions.GetRegionRequest()) + 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 = regions.Region.to_json(regions.Region()) + req.return_value.content = return_value + + request = regions.GetRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.Region() + post_with_metadata.return_value = regions.Region(), metadata + + client.get_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_region_rest_bad_request(request_type=regions.CreateRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.CreateRegionRequest, + dict, +]) +def test_create_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["region"] = {'name': 'name_value', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} + # 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 = regions.CreateRegionRequest.meta.fields["region"] + + 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["region"].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["region"][field])): + del request_init["region"][field][i][subfield] + else: + del request_init["region"][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 = regions.Region( + name='name_value', + display_name='display_name_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 = regions.Region.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.create_region(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_create_region") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_create_region_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_create_region") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.CreateRegionRequest.pb(regions.CreateRegionRequest()) + 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 = regions.Region.to_json(regions.Region()) + req.return_value.content = return_value + + request = regions.CreateRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.Region() + post_with_metadata.return_value = regions.Region(), metadata + + client.create_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_region_rest_bad_request(request_type=regions.UpdateRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'region': {'name': 'accounts/sample1/regions/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.update_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.UpdateRegionRequest, + dict, +]) +def test_update_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'region': {'name': 'accounts/sample1/regions/sample2'}} + request_init["region"] = {'name': 'accounts/sample1/regions/sample2', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} + # 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 = regions.UpdateRegionRequest.meta.fields["region"] + + 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["region"].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["region"][field])): + del request_init["region"][field][i][subfield] + else: + del request_init["region"][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 = regions.Region( + name='name_value', + display_name='display_name_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 = regions.Region.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.update_region(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, regions.Region) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_update_region") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_update_region_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_update_region") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.UpdateRegionRequest.pb(regions.UpdateRegionRequest()) + 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 = regions.Region.to_json(regions.Region()) + req.return_value.content = return_value + + request = regions.UpdateRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.Region() + post_with_metadata.return_value = regions.Region(), metadata + + client.update_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_region_rest_bad_request(request_type=regions.DeleteRegionRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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.delete_region(request) + + +@pytest.mark.parametrize("request_type", [ + regions.DeleteRegionRequest, + dict, +]) +def test_delete_region_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/regions/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 = 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_region(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_region_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "pre_delete_region") as pre: + pre.assert_not_called() + pb_message = regions.DeleteRegionRequest.pb(regions.DeleteRegionRequest()) + 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 = regions.DeleteRegionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_list_regions_rest_bad_request(request_type=regions.ListRegionsRequest): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_regions(request) + + +@pytest.mark.parametrize("request_type", [ + regions.ListRegionsRequest, + dict, +]) +def test_list_regions_rest_call_success(request_type): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = regions.ListRegionsResponse( + 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 = regions.ListRegionsResponse.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_regions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRegionsPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_regions_rest_interceptors(null_interceptor): + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), + ) + client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_list_regions") as post, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "post_list_regions_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_list_regions") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = regions.ListRegionsRequest.pb(regions.ListRegionsRequest()) + 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 = regions.ListRegionsResponse.to_json(regions.ListRegionsResponse()) + req.return_value.content = return_value + + request = regions.ListRegionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = regions.ListRegionsResponse() + post_with_metadata.return_value = regions.ListRegionsResponse(), metadata + + client.list_regions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = RegionsServiceClient( + 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_get_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_region), + '__call__') as call: + client.get_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.GetRegionRequest() + + 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_create_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_region), + '__call__') as call: + client.create_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.CreateRegionRequest() + + 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_update_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_region), + '__call__') as call: + client.update_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.UpdateRegionRequest() + + 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_region_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_region), + '__call__') as call: + client.delete_region(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.DeleteRegionRequest() + + 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_list_regions_empty_call_rest(): + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_regions), + '__call__') as call: + client.list_regions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = regions.ListRegionsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegionsServiceGrpcTransport, + ) + +def test_regions_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_regions_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.regions_service.transports.RegionsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegionsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_region', + 'create_region', + 'update_region', + 'delete_region', + 'list_regions', + ) + 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_regions_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_accounts_v1beta.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionsServiceTransport( + 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_regions_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_accounts_v1beta.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionsServiceTransport() + adc.assert_called_once() + + +def test_regions_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) + RegionsServiceClient() + 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.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + ], +) +def test_regions_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.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + transports.RegionsServiceRestTransport, + ], +) +def test_regions_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.RegionsServiceGrpcTransport, grpc_helpers), + (transports.RegionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +def test_regions_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_regions_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.RegionsServiceRestTransport ( + 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_regions_service_host_no_port(transport_name): + client = RegionsServiceClient( + 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_regions_service_host_with_port(transport_name): + client = RegionsServiceClient( + 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_regions_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_region._session + session2 = client2.transport.get_region._session + assert session1 != session2 + session1 = client1.transport.create_region._session + session2 = client2.transport.create_region._session + assert session1 != session2 + session1 = client1.transport.update_region._session + session2 = client2.transport.update_region._session + assert session1 != session2 + session1 = client1.transport.delete_region._session + session2 = client2.transport.delete_region._session + assert session1 != session2 + session1 = client1.transport.list_regions._session + session2 = client2.transport.list_regions._session + assert session1 != session2 +def test_regions_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionsServiceGrpcTransport( + 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_regions_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegionsServiceGrpcAsyncIOTransport( + 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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +def test_regions_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = RegionsServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = RegionsServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_account_path(path) + assert expected == actual + +def test_region_path(): + account = "whelk" + region = "octopus" + expected = "accounts/{account}/regions/{region}".format(account=account, region=region, ) + actual = RegionsServiceClient.region_path(account, region) + assert expected == actual + + +def test_parse_region_path(): + expected = { + "account": "oyster", + "region": "nudibranch", + } + path = RegionsServiceClient.region_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_region_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegionsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RegionsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegionsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RegionsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegionsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RegionsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RegionsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RegionsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.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 = RegionsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RegionsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionsServiceClient.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.RegionsServiceTransport, '_prep_wrapped_messages') as prep: + client = RegionsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegionsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RegionsServiceClient.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 = RegionsServiceClient( + 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 = RegionsServiceAsyncClient( + 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 = RegionsServiceClient( + 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 = RegionsServiceClient( + 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", [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py new file mode 100644 index 000000000000..f42327173207 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py @@ -0,0 +1,2733 @@ +# -*- 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.shopping.merchant_accounts_v1beta.services.shipping_settings_service import ShippingSettingsServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service import ShippingSettingsServiceClient +from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service import transports +from google.shopping.merchant_accounts_v1beta.types import shippingsettings +from google.shopping.type.types import types +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 ShippingSettingsServiceClient._get_default_mtls_endpoint(None) is None + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ShippingSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, False) is None + assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ShippingSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ShippingSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ShippingSettingsServiceClient._get_universe_domain(None, None) == ShippingSettingsServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient(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 = ShippingSettingsServiceClient(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", [ + (ShippingSettingsServiceClient, "grpc"), + (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), + (ShippingSettingsServiceClient, "rest"), +]) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, "grpc"), + (transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ShippingSettingsServiceRestTransport, "rest"), +]) +def test_shipping_settings_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", [ + (ShippingSettingsServiceClient, "grpc"), + (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), + (ShippingSettingsServiceClient, "rest"), +]) +def test_shipping_settings_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_shipping_settings_service_client_get_transport_class(): + transport = ShippingSettingsServiceClient.get_transport_class() + available_transports = [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceRestTransport, + ] + assert transport in available_transports + + transport = ShippingSettingsServiceClient.get_transport_class("grpc") + assert transport == transports.ShippingSettingsServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), +]) +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +def test_shipping_settings_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(ShippingSettingsServiceClient, '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(ShippingSettingsServiceClient, '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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "true"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "false"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "true"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_shipping_settings_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", [ + ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient +]) +@mock.patch.object(ShippingSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceAsyncClient)) +def test_shipping_settings_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", [ + ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient +]) +@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) +@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +def test_shipping_settings_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE + default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ShippingSettingsServiceClient._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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), +]) +def test_shipping_settings_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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", None), +]) +def test_shipping_settings_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_shipping_settings_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ShippingSettingsServiceClient( + 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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_shipping_settings_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", [ + shippingsettings.GetShippingSettingsRequest, + dict, +]) +def test_get_shipping_settings(request_type, transport: str = 'grpc'): + client = ShippingSettingsServiceClient( + 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.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + ) + response = client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = shippingsettings.GetShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_get_shipping_settings_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 = ShippingSettingsServiceClient( + 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 = shippingsettings.GetShippingSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_shipping_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == shippingsettings.GetShippingSettingsRequest( + name='name_value', + ) + +def test_get_shipping_settings_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 = ShippingSettingsServiceClient( + 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.get_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc + request = {} + client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_shipping_settings(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_get_shipping_settings_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 = ShippingSettingsServiceAsyncClient( + 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.get_shipping_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_shipping_settings] = mock_rpc + + request = {} + await client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_shipping_settings(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_get_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.GetShippingSettingsRequest): + client = ShippingSettingsServiceAsyncClient( + 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.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + response = await client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = shippingsettings.GetShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_get_shipping_settings_async_from_dict(): + await test_get_shipping_settings_async(request_type=dict) + +def test_get_shipping_settings_field_headers(): + client = ShippingSettingsServiceClient( + 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 = shippingsettings.GetShippingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.get_shipping_settings(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_get_shipping_settings_field_headers_async(): + client = ShippingSettingsServiceAsyncClient( + 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 = shippingsettings.GetShippingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + await client.get_shipping_settings(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_get_shipping_settings_flattened(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_shipping_settings( + 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_get_shipping_settings_flattened_error(): + client = ShippingSettingsServiceClient( + 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.get_shipping_settings( + shippingsettings.GetShippingSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_shipping_settings_flattened_async(): + client = ShippingSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_shipping_settings( + 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_get_shipping_settings_flattened_error_async(): + client = ShippingSettingsServiceAsyncClient( + 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.get_shipping_settings( + shippingsettings.GetShippingSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + shippingsettings.InsertShippingSettingsRequest, + dict, +]) +def test_insert_shipping_settings(request_type, transport: str = 'grpc'): + client = ShippingSettingsServiceClient( + 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_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + ) + response = client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = shippingsettings.InsertShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( + 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 = shippingsettings.InsertShippingSettingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.insert_shipping_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == shippingsettings.InsertShippingSettingsRequest( + parent='parent_value', + ) + +def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( + 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_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_shipping_settings] = mock_rpc + request = {} + client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_shipping_settings(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_shipping_settings_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 = ShippingSettingsServiceAsyncClient( + 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_shipping_settings 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_shipping_settings] = mock_rpc + + request = {} + await client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.insert_shipping_settings(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_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.InsertShippingSettingsRequest): + client = ShippingSettingsServiceAsyncClient( + 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_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + response = await client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = shippingsettings.InsertShippingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.asyncio +async def test_insert_shipping_settings_async_from_dict(): + await test_insert_shipping_settings_async(request_type=dict) + +def test_insert_shipping_settings_field_headers(): + client = ShippingSettingsServiceClient( + 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 = shippingsettings.InsertShippingSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.insert_shipping_settings(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_shipping_settings_field_headers_async(): + client = ShippingSettingsServiceAsyncClient( + 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 = shippingsettings.InsertShippingSettingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + await client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_get_shipping_settings_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 = ShippingSettingsServiceClient( + 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.get_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc + + request = {} + client.get_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_shipping_settings(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_get_shipping_settings_rest_required_fields(request_type=shippingsettings.GetShippingSettingsRequest): + transport_class = transports.ShippingSettingsServiceRestTransport + + 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()).get_shipping_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_shipping_settings._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 = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = shippingsettings.ShippingSettings() + # 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 = shippingsettings.ShippingSettings.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.get_shipping_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_shipping_settings_rest_unset_required_fields(): + transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_shipping_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_shipping_settings_rest_flattened(): + client = ShippingSettingsServiceClient( + 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 = shippingsettings.ShippingSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/shippingSettings'} + + # 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 + # Convert return value to protobuf type + return_value = shippingsettings.ShippingSettings.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.get_shipping_settings(**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/accounts/v1beta/{name=accounts/*/shippingSettings}" % client.transport._host, args[1]) + + +def test_get_shipping_settings_rest_flattened_error(transport: str = 'rest'): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_shipping_settings( + shippingsettings.GetShippingSettingsRequest(), + name='name_value', + ) + + +def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( + 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_shipping_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_shipping_settings] = mock_rpc + + request = {} + client.insert_shipping_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.insert_shipping_settings(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_shipping_settings_rest_required_fields(request_type=shippingsettings.InsertShippingSettingsRequest): + transport_class = transports.ShippingSettingsServiceRestTransport + + 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_shipping_settings._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_shipping_settings._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 = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = shippingsettings.ShippingSettings() + # 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 = shippingsettings.ShippingSettings.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_shipping_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_insert_shipping_settings_rest_unset_required_fields(): + transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.insert_shipping_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "shippingSetting", ))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + 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 = ShippingSettingsServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ShippingSettingsServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ShippingSettingsServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ShippingSettingsServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ShippingSettingsServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + transports.ShippingSettingsServiceRestTransport, +]) +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 = ShippingSettingsServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ShippingSettingsServiceClient( + 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_get_shipping_settings_empty_call_grpc(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.get_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.GetShippingSettingsRequest() + + 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_shipping_settings_empty_call_grpc(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + call.return_value = shippingsettings.ShippingSettings() + client.insert_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.InsertShippingSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ShippingSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ShippingSettingsServiceAsyncClient( + 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_get_shipping_settings_empty_call_grpc_asyncio(): + client = ShippingSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + await client.get_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.GetShippingSettingsRequest() + + 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_shipping_settings_empty_call_grpc_asyncio(): + client = ShippingSettingsServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( + name='name_value', + etag='etag_value', + )) + await client.insert_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.InsertShippingSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ShippingSettingsServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_shipping_settings_rest_bad_request(request_type=shippingsettings.GetShippingSettingsRequest): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/shippingSettings'} + 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.get_shipping_settings(request) + + +@pytest.mark.parametrize("request_type", [ + shippingsettings.GetShippingSettingsRequest, + dict, +]) +def test_get_shipping_settings_rest_call_success(request_type): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/shippingSettings'} + request = request_type(**request_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 = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_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 = shippingsettings.ShippingSettings.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.get_shipping_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_shipping_settings_rest_interceptors(null_interceptor): + transport = transports.ShippingSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), + ) + client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings") as post, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_get_shipping_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = shippingsettings.GetShippingSettingsRequest.pb(shippingsettings.GetShippingSettingsRequest()) + 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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) + req.return_value.content = return_value + + request = shippingsettings.GetShippingSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = shippingsettings.ShippingSettings() + post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata + + client.get_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_insert_shipping_settings_rest_bad_request(request_type=shippingsettings.InsertShippingSettingsRequest): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_shipping_settings(request) + + +@pytest.mark.parametrize("request_type", [ + shippingsettings.InsertShippingSettingsRequest, + dict, +]) +def test_insert_shipping_settings_rest_call_success(request_type): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["shipping_setting"] = {'name': 'name_value', 'services': [{'service_name': 'service_name_value', 'active': True, 'delivery_countries': ['delivery_countries_value1', 'delivery_countries_value2'], 'currency_code': 'currency_code_value', 'delivery_time': {'min_transit_days': 1720, 'max_transit_days': 1722, 'cutoff_time': {'hour': 446, 'minute': 658, 'time_zone': 'time_zone_value'}, 'min_handling_days': 1784, 'max_handling_days': 1786, 'transit_time_table': {'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'transit_time_labels': ['transit_time_labels_value1', 'transit_time_labels_value2'], 'rows': [{'values': [{'min_transit_days': 1720, 'max_transit_days': 1722}]}]}, 'handling_business_day_config': {'business_days': [1]}, 'transit_business_day_config': {}, 'warehouse_based_delivery_times': [{'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'warehouse': 'warehouse_value'}]}, 'rate_groups': [{'applicable_shipping_labels': ['applicable_shipping_labels_value1', 'applicable_shipping_labels_value2'], 'single_value': {'no_shipping': True, 'flat_rate': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'price_percentage': 'price_percentage_value', 'carrier_rate': 'carrier_rate_value', 'subtable': 'subtable_value'}, 'main_table': {'name': 'name_value', 'row_headers': {'prices': {}, 'weights': [{'amount_micros': 1408, 'unit': 1}], 'number_of_items': ['number_of_items_value1', 'number_of_items_value2'], 'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'locations': [{'location_ids': ['location_ids_value1', 'location_ids_value2']}]}, 'column_headers': {}, 'rows': [{'cells': {}}]}, 'subtables': {}, 'carrier_rates': [{'name': 'name_value', 'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'origin_postal_code': 'origin_postal_code_value', 'percentage_adjustment': 'percentage_adjustment_value', 'flat_adjustment': {}}], 'name': 'name_value'}], 'shipment_type': 1, 'minimum_order_value': {}, 'minimum_order_value_table': {'store_code_set_with_movs': [{'store_codes': ['store_codes_value1', 'store_codes_value2'], 'value': {}}]}, 'store_config': {'store_service_type': 1, 'store_codes': ['store_codes_value1', 'store_codes_value2'], 'cutoff_config': {'local_cutoff_time': {'hour': 446, 'minute': 658}, 'store_close_offset_hours': 2584, 'no_delivery_post_cutoff': True}, 'service_radius': {'value': 541, 'unit': 1}}, 'loyalty_programs': [{'program_label': 'program_label_value', 'loyalty_program_tiers': [{'tier_label': 'tier_label_value'}]}]}], 'warehouses': [{'name': 'name_value', 'shipping_address': {'street_address': 'street_address_value', 'city': 'city_value', 'administrative_area': 'administrative_area_value', 'postal_code': 'postal_code_value', 'region_code': 'region_code_value'}, 'cutoff_time': {'hour': 446, 'minute': 658}, 'handling_days': 1365, 'business_day_config': {}}], 'etag': 'etag_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 = shippingsettings.InsertShippingSettingsRequest.meta.fields["shipping_setting"] + + 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["shipping_setting"].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["shipping_setting"][field])): + del request_init["shipping_setting"][field][i][subfield] + else: + del request_init["shipping_setting"][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 = shippingsettings.ShippingSettings( + name='name_value', + etag='etag_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 = shippingsettings.ShippingSettings.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_shipping_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, shippingsettings.ShippingSettings) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_shipping_settings_rest_interceptors(null_interceptor): + transport = transports.ShippingSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), + ) + client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings") as post, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_insert_shipping_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = shippingsettings.InsertShippingSettingsRequest.pb(shippingsettings.InsertShippingSettingsRequest()) + 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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) + req.return_value.content = return_value + + request = shippingsettings.InsertShippingSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = shippingsettings.ShippingSettings() + post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata + + client.insert_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = ShippingSettingsServiceClient( + 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_get_shipping_settings_empty_call_rest(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shipping_settings), + '__call__') as call: + client.get_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.GetShippingSettingsRequest() + + 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_shipping_settings_empty_call_rest(): + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.insert_shipping_settings), + '__call__') as call: + client.insert_shipping_settings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = shippingsettings.InsertShippingSettingsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ShippingSettingsServiceGrpcTransport, + ) + +def test_shipping_settings_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ShippingSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_shipping_settings_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ShippingSettingsServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_shipping_settings', + 'insert_shipping_settings', + ) + 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_shipping_settings_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_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ShippingSettingsServiceTransport( + 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_shipping_settings_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_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ShippingSettingsServiceTransport() + adc.assert_called_once() + + +def test_shipping_settings_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) + ShippingSettingsServiceClient() + 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.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + transports.ShippingSettingsServiceRestTransport, + ], +) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, grpc_helpers), + (transports.ShippingSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +def test_shipping_settings_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_shipping_settings_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.ShippingSettingsServiceRestTransport ( + 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_shipping_settings_service_host_no_port(transport_name): + client = ShippingSettingsServiceClient( + 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_shipping_settings_service_host_with_port(transport_name): + client = ShippingSettingsServiceClient( + 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_shipping_settings_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ShippingSettingsServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ShippingSettingsServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_shipping_settings._session + session2 = client2.transport.get_shipping_settings._session + assert session1 != session2 + session1 = client1.transport.insert_shipping_settings._session + session2 = client2.transport.insert_shipping_settings._session + assert session1 != session2 +def test_shipping_settings_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ShippingSettingsServiceGrpcTransport( + 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_shipping_settings_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ShippingSettingsServiceGrpcAsyncIOTransport( + 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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +def test_shipping_settings_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_shipping_settings_path(): + account = "squid" + expected = "accounts/{account}/shippingSettings".format(account=account, ) + actual = ShippingSettingsServiceClient.shipping_settings_path(account) + assert expected == actual + + +def test_parse_shipping_settings_path(): + expected = { + "account": "clam", + } + path = ShippingSettingsServiceClient.shipping_settings_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_shipping_settings_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ShippingSettingsServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ShippingSettingsServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ShippingSettingsServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ShippingSettingsServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ShippingSettingsServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ShippingSettingsServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ShippingSettingsServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ShippingSettingsServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ShippingSettingsServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ShippingSettingsServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ShippingSettingsServiceClient.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.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: + client = ShippingSettingsServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ShippingSettingsServiceClient.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 = ShippingSettingsServiceClient( + 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 = ShippingSettingsServiceAsyncClient( + 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 = ShippingSettingsServiceClient( + 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 = ShippingSettingsServiceClient( + 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", [ + (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport), + (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py new file mode 100644 index 000000000000..643f85170d3b --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py @@ -0,0 +1,2854 @@ +# -*- 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.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service import transports +from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate +from google.shopping.merchant_accounts_v1beta.types import termsofservicekind +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 TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(None) is None + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, False) is None + assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, None) == TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + TermsOfServiceAgreementStateServiceClient._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 = TermsOfServiceAgreementStateServiceClient(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 = TermsOfServiceAgreementStateServiceClient(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", [ + (TermsOfServiceAgreementStateServiceClient, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, "rest"), +]) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +def test_terms_of_service_agreement_state_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", [ + (TermsOfServiceAgreementStateServiceClient, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, "rest"), +]) +def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_service_client_get_transport_class(): + transport = TermsOfServiceAgreementStateServiceClient.get_transport_class() + available_transports = [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, + ] + assert transport in available_transports + + transport = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc") + assert transport == transports.TermsOfServiceAgreementStateServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +def test_terms_of_service_agreement_state_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(TermsOfServiceAgreementStateServiceClient, '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(TermsOfServiceAgreementStateServiceClient, '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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "true"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "false"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "true"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_terms_of_service_agreement_state_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", [ + TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceAsyncClient)) +def test_terms_of_service_agreement_state_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", [ + TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) +@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +def test_terms_of_service_agreement_state_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceAgreementStateServiceClient._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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), +]) +def test_terms_of_service_agreement_state_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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", None), +]) +def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TermsOfServiceAgreementStateServiceClient( + 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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_terms_of_service_agreement_state_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", [ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, +]) +def test_get_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): + client = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + response = client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_terms_of_service_agreement_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + name='name_value', + ) + +def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc + request = {} + client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceAsyncClient( + 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.get_terms_of_service_agreement_state in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service_agreement_state] = mock_rpc + + request = {} + await client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + response = await client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.asyncio +async def test_get_terms_of_service_agreement_state_async_from_dict(): + await test_get_terms_of_service_agreement_state_async(request_type=dict) + +def test_get_terms_of_service_agreement_state_field_headers(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_field_headers_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + await client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_terms_of_service_agreement_state( + 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_get_terms_of_service_agreement_state_flattened_error(): + client = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_terms_of_service_agreement_state_flattened_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_terms_of_service_agreement_state( + 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_get_terms_of_service_agreement_state_flattened_error_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.get_terms_of_service_agreement_state( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + dict, +]) +def test_retrieve_for_application_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): + client = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + response = client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.retrieve_for_application_terms_of_service_agreement_state(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent='parent_value', + ) + +def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + request = {} + client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceAsyncClient( + 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.retrieve_for_application_terms_of_service_agreement_state 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.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + + request = {} + await client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + response = await client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.asyncio +async def test_retrieve_for_application_terms_of_service_agreement_state_async_from_dict(): + await test_retrieve_for_application_terms_of_service_agreement_state_async(request_type=dict) + +def test_retrieve_for_application_terms_of_service_agreement_state_field_headers(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_field_headers_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + await client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.retrieve_for_application_terms_of_service_agreement_state( + 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error(): + client = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_retrieve_for_application_terms_of_service_agreement_state_flattened_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.retrieve_for_application_terms_of_service_agreement_state( + 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error_async(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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.retrieve_for_application_terms_of_service_agreement_state( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), + parent='parent_value', + ) + + +def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.get_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc + + request = {} + client.get_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport + + 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()).get_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_terms_of_service_agreement_state_rest_unset_required_fields(): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_terms_of_service_agreement_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_terms_of_service_agreement_state_rest_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/termsOfServiceAgreementStates/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(**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/accounts/v1beta/{name=accounts/*/termsOfServiceAgreementStates/*}" % client.transport._host, args[1]) + + +def test_get_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_terms_of_service_agreement_state( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), + name='name_value', + ) + + +def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + + request = {} + client.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport + + 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()).retrieve_for_application_terms_of_service_agreement_state._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()).retrieve_for_application_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_unset_required_fields(): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened(): + client = TermsOfServiceAgreementStateServiceClient( + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(**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/accounts/v1beta/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication" % client.transport._host, args[1]) + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceAgreementStateServiceClient( + 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.retrieve_for_application_terms_of_service_agreement_state( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + 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 = TermsOfServiceAgreementStateServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceAgreementStateServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TermsOfServiceAgreementStateServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, +]) +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 = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TermsOfServiceAgreementStateServiceClient( + 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_get_terms_of_service_agreement_state_empty_call_grpc(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.get_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_grpc(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + client.retrieve_for_application_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TermsOfServiceAgreementStateServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + 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_get_terms_of_service_agreement_state_empty_call_grpc_asyncio(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + await client.get_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_grpc_asyncio(): + client = TermsOfServiceAgreementStateServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + )) + await client.retrieve_for_application_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TermsOfServiceAgreementStateServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/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.get_terms_of_service_agreement_state(request) + + +@pytest.mark.parametrize("request_type", [ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, +]) +def test_get_terms_of_service_agreement_state_rest_call_success(request_type): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/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 = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_terms_of_service_agreement_state_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), + ) + client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state") as post, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_get_terms_of_service_agreement_state") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest()) + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) + req.return_value.content = return_value + + request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata + + client.get_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.retrieve_for_application_terms_of_service_agreement_state(request) + + +@pytest.mark.parametrize("request_type", [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + dict, +]) +def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_success(request_type): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( + name='name_value', + region_code='region_code_value', + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + + # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_for_application_terms_of_service_agreement_state_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceAgreementStateServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), + ) + client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state") as post, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_retrieve_for_application_terms_of_service_agreement_state") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest()) + 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) + req.return_value.content = return_value + + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() + post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata + + client.retrieve_for_application_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = TermsOfServiceAgreementStateServiceClient( + 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_get_terms_of_service_agreement_state_empty_call_rest(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service_agreement_state), + '__call__') as call: + client.get_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + + 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_rest(): + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_for_application_terms_of_service_agreement_state), + '__call__') as call: + client.retrieve_for_application_terms_of_service_agreement_state(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + ) + +def test_terms_of_service_agreement_state_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TermsOfServiceAgreementStateServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_terms_of_service_agreement_state_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TermsOfServiceAgreementStateServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_terms_of_service_agreement_state', + 'retrieve_for_application_terms_of_service_agreement_state', + ) + 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_terms_of_service_agreement_state_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_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceAgreementStateServiceTransport( + 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_terms_of_service_agreement_state_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_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceAgreementStateServiceTransport() + adc.assert_called_once() + + +def test_terms_of_service_agreement_state_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) + TermsOfServiceAgreementStateServiceClient() + 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.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + ], +) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, + ], +) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, grpc_helpers), + (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceRestTransport ( + 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_terms_of_service_agreement_state_service_host_no_port(transport_name): + client = TermsOfServiceAgreementStateServiceClient( + 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_terms_of_service_agreement_state_service_host_with_port(transport_name): + client = TermsOfServiceAgreementStateServiceClient( + 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_terms_of_service_agreement_state_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TermsOfServiceAgreementStateServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TermsOfServiceAgreementStateServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_terms_of_service_agreement_state._session + session2 = client2.transport.get_terms_of_service_agreement_state._session + assert session1 != session2 + session1 = client1.transport.retrieve_for_application_terms_of_service_agreement_state._session + session2 = client2.transport.retrieve_for_application_terms_of_service_agreement_state._session + assert session1 != session2 +def test_terms_of_service_agreement_state_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( + 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_terms_of_service_agreement_state_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( + 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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +def test_terms_of_service_agreement_state_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = TermsOfServiceAgreementStateServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = TermsOfServiceAgreementStateServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_account_path(path) + assert expected == actual + +def test_terms_of_service_path(): + version = "whelk" + expected = "termsOfService/{version}".format(version=version, ) + actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(version) + assert expected == actual + + +def test_parse_terms_of_service_path(): + expected = { + "version": "octopus", + } + path = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path(path) + assert expected == actual + +def test_terms_of_service_agreement_state_path(): + account = "oyster" + identifier = "nudibranch" + expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(account, identifier) + assert expected == actual + + +def test_parse_terms_of_service_agreement_state_path(): + expected = { + "account": "cuttlefish", + "identifier": "mussel", + } + path = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = TermsOfServiceAgreementStateServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = TermsOfServiceAgreementStateServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TermsOfServiceAgreementStateServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = TermsOfServiceAgreementStateServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = TermsOfServiceAgreementStateServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = TermsOfServiceAgreementStateServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TermsOfServiceAgreementStateServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = TermsOfServiceAgreementStateServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceAgreementStateServiceClient.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.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: + client = TermsOfServiceAgreementStateServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TermsOfServiceAgreementStateServiceClient.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 = TermsOfServiceAgreementStateServiceClient( + 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 = TermsOfServiceAgreementStateServiceAsyncClient( + 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 = TermsOfServiceAgreementStateServiceClient( + 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 = TermsOfServiceAgreementStateServiceClient( + 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", [ + (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport), + (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py new file mode 100644 index 000000000000..efa214562c18 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py @@ -0,0 +1,3331 @@ +# -*- 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.shopping.merchant_accounts_v1beta.services.terms_of_service_service import TermsOfServiceServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service import TermsOfServiceServiceClient +from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service import transports +from google.shopping.merchant_accounts_v1beta.types import termsofservice +from google.shopping.merchant_accounts_v1beta.types import termsofservicekind +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 TermsOfServiceServiceClient._get_default_mtls_endpoint(None) is None + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert TermsOfServiceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, False) is None + assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert TermsOfServiceServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert TermsOfServiceServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert TermsOfServiceServiceClient._get_universe_domain(None, None) == TermsOfServiceServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient(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 = TermsOfServiceServiceClient(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", [ + (TermsOfServiceServiceClient, "grpc"), + (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceServiceClient, "rest"), +]) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, "grpc"), + (transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TermsOfServiceServiceRestTransport, "rest"), +]) +def test_terms_of_service_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", [ + (TermsOfServiceServiceClient, "grpc"), + (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceServiceClient, "rest"), +]) +def test_terms_of_service_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_terms_of_service_service_client_get_transport_class(): + transport = TermsOfServiceServiceClient.get_transport_class() + available_transports = [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceRestTransport, + ] + assert transport in available_transports + + transport = TermsOfServiceServiceClient.get_transport_class("grpc") + assert transport == transports.TermsOfServiceServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), +]) +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +def test_terms_of_service_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(TermsOfServiceServiceClient, '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(TermsOfServiceServiceClient, '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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "true"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "false"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "true"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_terms_of_service_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", [ + TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceAsyncClient)) +def test_terms_of_service_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", [ + TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient +]) +@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) +@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +def test_terms_of_service_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE + default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = TermsOfServiceServiceClient._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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), +]) +def test_terms_of_service_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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", None), +]) +def test_terms_of_service_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_terms_of_service_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = TermsOfServiceServiceClient( + 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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_terms_of_service_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", [ + termsofservice.GetTermsOfServiceRequest, + dict, +]) +def test_get_terms_of_service(request_type, transport: str = 'grpc'): + client = TermsOfServiceServiceClient( + 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.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + response = client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofservice.GetTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +def test_get_terms_of_service_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 = TermsOfServiceServiceClient( + 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 = termsofservice.GetTermsOfServiceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_terms_of_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofservice.GetTermsOfServiceRequest( + name='name_value', + ) + +def test_get_terms_of_service_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 = TermsOfServiceServiceClient( + 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.get_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc + request = {} + client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service(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_get_terms_of_service_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 = TermsOfServiceServiceAsyncClient( + 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.get_terms_of_service in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service] = mock_rpc + + request = {} + await client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_terms_of_service(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_get_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.GetTermsOfServiceRequest): + client = TermsOfServiceServiceAsyncClient( + 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.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + response = await client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofservice.GetTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.asyncio +async def test_get_terms_of_service_async_from_dict(): + await test_get_terms_of_service_async(request_type=dict) + +def test_get_terms_of_service_field_headers(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.GetTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.TermsOfService() + client.get_terms_of_service(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_get_terms_of_service_field_headers_async(): + client = TermsOfServiceServiceAsyncClient( + 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 = termsofservice.GetTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) + await client.get_terms_of_service(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_get_terms_of_service_flattened(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_terms_of_service( + 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_get_terms_of_service_flattened_error(): + client = TermsOfServiceServiceClient( + 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.get_terms_of_service( + termsofservice.GetTermsOfServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_terms_of_service_flattened_async(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_terms_of_service( + 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_get_terms_of_service_flattened_error_async(): + client = TermsOfServiceServiceAsyncClient( + 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.get_terms_of_service( + termsofservice.GetTermsOfServiceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.RetrieveLatestTermsOfServiceRequest, + dict, +]) +def test_retrieve_latest_terms_of_service(request_type, transport: str = 'grpc'): + client = TermsOfServiceServiceClient( + 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.retrieve_latest_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + response = client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofservice.RetrieveLatestTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( + 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 = termsofservice.RetrieveLatestTermsOfServiceRequest( + region_code='region_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.retrieve_latest_terms_of_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofservice.RetrieveLatestTermsOfServiceRequest( + region_code='region_code_value', + ) + +def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( + 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.retrieve_latest_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc + request = {} + client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceAsyncClient( + 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.retrieve_latest_terms_of_service 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.retrieve_latest_terms_of_service] = mock_rpc + + request = {} + await client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): + client = TermsOfServiceServiceAsyncClient( + 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.retrieve_latest_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + response = await client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofservice.RetrieveLatestTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.asyncio +async def test_retrieve_latest_terms_of_service_async_from_dict(): + await test_retrieve_latest_terms_of_service_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.AcceptTermsOfServiceRequest, + dict, +]) +def test_accept_terms_of_service(request_type, transport: str = 'grpc'): + client = TermsOfServiceServiceClient( + 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.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = termsofservice.AcceptTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( + 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 = termsofservice.AcceptTermsOfServiceRequest( + name='name_value', + account='account_value', + region_code='region_code_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.accept_terms_of_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == termsofservice.AcceptTermsOfServiceRequest( + name='name_value', + account='account_value', + region_code='region_code_value', + ) + +def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( + 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.accept_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc + request = {} + client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.accept_terms_of_service(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_accept_terms_of_service_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 = TermsOfServiceServiceAsyncClient( + 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.accept_terms_of_service 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.accept_terms_of_service] = mock_rpc + + request = {} + await client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.accept_terms_of_service(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_accept_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.AcceptTermsOfServiceRequest): + client = TermsOfServiceServiceAsyncClient( + 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.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = termsofservice.AcceptTermsOfServiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_accept_terms_of_service_async_from_dict(): + await test_accept_terms_of_service_async(request_type=dict) + +def test_accept_terms_of_service_field_headers(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.AcceptTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value = None + client.accept_terms_of_service(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_accept_terms_of_service_field_headers_async(): + client = TermsOfServiceServiceAsyncClient( + 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 = termsofservice.AcceptTermsOfServiceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.accept_terms_of_service(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_accept_terms_of_service_flattened(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__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.accept_terms_of_service( + 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_accept_terms_of_service_flattened_error(): + client = TermsOfServiceServiceClient( + 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.accept_terms_of_service( + termsofservice.AcceptTermsOfServiceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_accept_terms_of_service_flattened_async(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__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.accept_terms_of_service( + 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_accept_terms_of_service_flattened_error_async(): + client = TermsOfServiceServiceAsyncClient( + 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.accept_terms_of_service( + termsofservice.AcceptTermsOfServiceRequest(), + name='name_value', + ) + + +def test_get_terms_of_service_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 = TermsOfServiceServiceClient( + 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.get_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc + + request = {} + client.get_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terms_of_service(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_get_terms_of_service_rest_required_fields(request_type=termsofservice.GetTermsOfServiceRequest): + transport_class = transports.TermsOfServiceServiceRestTransport + + 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()).get_terms_of_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service._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 = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService() + # 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 = termsofservice.TermsOfService.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.get_terms_of_service(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_terms_of_service_rest_unset_required_fields(): + transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_terms_of_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_terms_of_service_rest_flattened(): + client = TermsOfServiceServiceClient( + 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 = termsofservice.TermsOfService() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'termsOfService/sample1'} + + # 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 + # Convert return value to protobuf type + return_value = termsofservice.TermsOfService.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.get_terms_of_service(**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/accounts/v1beta/{name=termsOfService/*}" % client.transport._host, args[1]) + + +def test_get_terms_of_service_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_terms_of_service( + termsofservice.GetTermsOfServiceRequest(), + name='name_value', + ) + + +def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( + 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.retrieve_latest_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc + + request = {} + client.retrieve_latest_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_rest_required_fields(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): + transport_class = transports.TermsOfServiceServiceRestTransport + + request_init = {} + request_init["region_code"] = "" + 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 + assert "regionCode" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == request_init["region_code"] + + jsonified_request["regionCode"] = 'region_code_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("kind", "region_code", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == 'region_code_value' + + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService() + # 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 = termsofservice.TermsOfService.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.retrieve_latest_terms_of_service(request) + + expected_params = [ + ( + "regionCode", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_retrieve_latest_terms_of_service_rest_unset_required_fields(): + transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.retrieve_latest_terms_of_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("kind", "regionCode", )) & set(("regionCode", "kind", ))) + + +def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( + 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.accept_terms_of_service in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc + + request = {} + client.accept_terms_of_service(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.accept_terms_of_service(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_accept_terms_of_service_rest_required_fields(request_type=termsofservice.AcceptTermsOfServiceRequest): + transport_class = transports.TermsOfServiceServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["account"] = "" + request_init["region_code"] = "" + 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 + assert "account" not in jsonified_request + assert "regionCode" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "account" in jsonified_request + assert jsonified_request["account"] == request_init["account"] + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == request_init["region_code"] + + jsonified_request["name"] = 'name_value' + jsonified_request["account"] = 'account_value' + jsonified_request["regionCode"] = 'region_code_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("account", "region_code", )) + 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 "account" in jsonified_request + assert jsonified_request["account"] == 'account_value' + assert "regionCode" in jsonified_request + assert jsonified_request["regionCode"] == 'region_code_value' + + client = TermsOfServiceServiceClient( + 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': "get", + '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.accept_terms_of_service(request) + + expected_params = [ + ( + "account", + "", + ), + ( + "regionCode", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_accept_terms_of_service_rest_unset_required_fields(): + transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.accept_terms_of_service._get_unset_required_fields({}) + assert set(unset_fields) == (set(("account", "regionCode", )) & set(("name", "account", "regionCode", ))) + + +def test_accept_terms_of_service_rest_flattened(): + client = TermsOfServiceServiceClient( + 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': 'termsOfService/sample1'} + + # 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.accept_terms_of_service(**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/accounts/v1beta/{name=termsOfService/*}:accept" % client.transport._host, args[1]) + + +def test_accept_terms_of_service_rest_flattened_error(transport: str = 'rest'): + client = TermsOfServiceServiceClient( + 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.accept_terms_of_service( + termsofservice.AcceptTermsOfServiceRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + 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 = TermsOfServiceServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = TermsOfServiceServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = TermsOfServiceServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.TermsOfServiceServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.TermsOfServiceServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + transports.TermsOfServiceServiceRestTransport, +]) +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 = TermsOfServiceServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = TermsOfServiceServiceClient( + 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_get_terms_of_service_empty_call_grpc(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.TermsOfService() + client.get_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.GetTermsOfServiceRequest() + + 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_retrieve_latest_terms_of_service_empty_call_grpc(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + call.return_value = termsofservice.TermsOfService() + client.retrieve_latest_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() + + 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_accept_terms_of_service_empty_call_grpc(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + call.return_value = None + client.accept_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.AcceptTermsOfServiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = TermsOfServiceServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + 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_get_terms_of_service_empty_call_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + await client.get_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.GetTermsOfServiceRequest() + + 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_retrieve_latest_terms_of_service_empty_call_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + )) + await client.retrieve_latest_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() + + 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_accept_terms_of_service_empty_call_grpc_asyncio(): + client = TermsOfServiceServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.accept_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.AcceptTermsOfServiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = TermsOfServiceServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_terms_of_service_rest_bad_request(request_type=termsofservice.GetTermsOfServiceRequest): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + 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.get_terms_of_service(request) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.GetTermsOfServiceRequest, + dict, +]) +def test_get_terms_of_service_rest_call_success(request_type): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + + # 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 = termsofservice.TermsOfService.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.get_terms_of_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_terms_of_service_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), + ) + client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service") as post, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_get_terms_of_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofservice.GetTermsOfServiceRequest.pb(termsofservice.GetTermsOfServiceRequest()) + 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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) + req.return_value.content = return_value + + request = termsofservice.GetTermsOfServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofservice.TermsOfService() + post_with_metadata.return_value = termsofservice.TermsOfService(), metadata + + client.get_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_retrieve_latest_terms_of_service_rest_bad_request(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # 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.retrieve_latest_terms_of_service(request) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.RetrieveLatestTermsOfServiceRequest, + dict, +]) +def test_retrieve_latest_terms_of_service_rest_call_success(request_type): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = termsofservice.TermsOfService( + name='name_value', + region_code='region_code_value', + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri='file_uri_value', + external=True, + ) + + # 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 = termsofservice.TermsOfService.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.retrieve_latest_terms_of_service(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, termsofservice.TermsOfService) + assert response.name == 'name_value' + assert response.region_code == 'region_code_value' + assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert response.file_uri == 'file_uri_value' + assert response.external is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_latest_terms_of_service_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), + ) + client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service") as post, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_retrieve_latest_terms_of_service") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = termsofservice.RetrieveLatestTermsOfServiceRequest.pb(termsofservice.RetrieveLatestTermsOfServiceRequest()) + 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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) + req.return_value.content = return_value + + request = termsofservice.RetrieveLatestTermsOfServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = termsofservice.TermsOfService() + post_with_metadata.return_value = termsofservice.TermsOfService(), metadata + + client.retrieve_latest_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_accept_terms_of_service_rest_bad_request(request_type=termsofservice.AcceptTermsOfServiceRequest): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + 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.accept_terms_of_service(request) + + +@pytest.mark.parametrize("request_type", [ + termsofservice.AcceptTermsOfServiceRequest, + dict, +]) +def test_accept_terms_of_service_rest_call_success(request_type): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'termsOfService/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = 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.accept_terms_of_service(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_accept_terms_of_service_rest_interceptors(null_interceptor): + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), + ) + client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "pre_accept_terms_of_service") as pre: + pre.assert_not_called() + pb_message = termsofservice.AcceptTermsOfServiceRequest.pb(termsofservice.AcceptTermsOfServiceRequest()) + 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 = termsofservice.AcceptTermsOfServiceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.accept_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + +def test_initialize_client_w_rest(): + client = TermsOfServiceServiceClient( + 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_get_terms_of_service_empty_call_rest(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terms_of_service), + '__call__') as call: + client.get_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.GetTermsOfServiceRequest() + + 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_retrieve_latest_terms_of_service_empty_call_rest(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_latest_terms_of_service), + '__call__') as call: + client.retrieve_latest_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() + + 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_accept_terms_of_service_empty_call_rest(): + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.accept_terms_of_service), + '__call__') as call: + client.accept_terms_of_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = termsofservice.AcceptTermsOfServiceRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.TermsOfServiceServiceGrpcTransport, + ) + +def test_terms_of_service_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.TermsOfServiceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_terms_of_service_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.TermsOfServiceServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_terms_of_service', + 'retrieve_latest_terms_of_service', + 'accept_terms_of_service', + ) + 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_terms_of_service_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_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceServiceTransport( + 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_terms_of_service_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_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.TermsOfServiceServiceTransport() + adc.assert_called_once() + + +def test_terms_of_service_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) + TermsOfServiceServiceClient() + 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.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + ], +) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + transports.TermsOfServiceServiceRestTransport, + ], +) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, grpc_helpers), + (transports.TermsOfServiceServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +def test_terms_of_service_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_terms_of_service_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.TermsOfServiceServiceRestTransport ( + 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_terms_of_service_service_host_no_port(transport_name): + client = TermsOfServiceServiceClient( + 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_terms_of_service_service_host_with_port(transport_name): + client = TermsOfServiceServiceClient( + 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_terms_of_service_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = TermsOfServiceServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = TermsOfServiceServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_terms_of_service._session + session2 = client2.transport.get_terms_of_service._session + assert session1 != session2 + session1 = client1.transport.retrieve_latest_terms_of_service._session + session2 = client2.transport.retrieve_latest_terms_of_service._session + assert session1 != session2 + session1 = client1.transport.accept_terms_of_service._session + session2 = client2.transport.accept_terms_of_service._session + assert session1 != session2 +def test_terms_of_service_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceServiceGrpcTransport( + 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_terms_of_service_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.TermsOfServiceServiceGrpcAsyncIOTransport( + 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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +def test_terms_of_service_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = TermsOfServiceServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = TermsOfServiceServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_account_path(path) + assert expected == actual + +def test_terms_of_service_path(): + version = "whelk" + expected = "termsOfService/{version}".format(version=version, ) + actual = TermsOfServiceServiceClient.terms_of_service_path(version) + assert expected == actual + + +def test_parse_terms_of_service_path(): + expected = { + "version": "octopus", + } + path = TermsOfServiceServiceClient.terms_of_service_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_terms_of_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = TermsOfServiceServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = TermsOfServiceServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = TermsOfServiceServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = TermsOfServiceServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = TermsOfServiceServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = TermsOfServiceServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = TermsOfServiceServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = TermsOfServiceServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = TermsOfServiceServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = TermsOfServiceServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = TermsOfServiceServiceClient.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.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: + client = TermsOfServiceServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = TermsOfServiceServiceClient.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 = TermsOfServiceServiceClient( + 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 = TermsOfServiceServiceAsyncClient( + 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 = TermsOfServiceServiceClient( + 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 = TermsOfServiceServiceClient( + 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", [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport), + (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport), +]) +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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py new file mode 100644 index 000000000000..089adfcb70e6 --- /dev/null +++ b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py @@ -0,0 +1,5226 @@ +# -*- 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 field_mask_pb2 # type: ignore +from google.shopping.merchant_accounts_v1beta.services.user_service import UserServiceAsyncClient +from google.shopping.merchant_accounts_v1beta.services.user_service import UserServiceClient +from google.shopping.merchant_accounts_v1beta.services.user_service import pagers +from google.shopping.merchant_accounts_v1beta.services.user_service import transports +from google.shopping.merchant_accounts_v1beta.types import accessright +from google.shopping.merchant_accounts_v1beta.types import user +from google.shopping.merchant_accounts_v1beta.types import user as gsma_user +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 UserServiceClient._get_default_mtls_endpoint(None) is None + assert UserServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert UserServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert UserServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert UserServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + UserServiceClient._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 UserServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert UserServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert UserServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + UserServiceClient._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 UserServiceClient._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 UserServiceClient._get_client_cert_source(None, False) is None + assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert UserServiceClient._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 UserServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = UserServiceClient._DEFAULT_UNIVERSE + default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert UserServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == UserServiceClient.DEFAULT_MTLS_ENDPOINT + assert UserServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert UserServiceClient._get_api_endpoint(None, None, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT + assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT + assert UserServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert UserServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + UserServiceClient._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 UserServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert UserServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert UserServiceClient._get_universe_domain(None, None) == UserServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + UserServiceClient._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 = UserServiceClient(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 = UserServiceClient(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", [ + (UserServiceClient, "grpc"), + (UserServiceAsyncClient, "grpc_asyncio"), + (UserServiceClient, "rest"), +]) +def test_user_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.UserServiceGrpcTransport, "grpc"), + (transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserServiceRestTransport, "rest"), +]) +def test_user_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", [ + (UserServiceClient, "grpc"), + (UserServiceAsyncClient, "grpc_asyncio"), + (UserServiceClient, "rest"), +]) +def test_user_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_user_service_client_get_transport_class(): + transport = UserServiceClient.get_transport_class() + available_transports = [ + transports.UserServiceGrpcTransport, + transports.UserServiceRestTransport, + ] + assert transport in available_transports + + transport = UserServiceClient.get_transport_class("grpc") + assert transport == transports.UserServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), +]) +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +def test_user_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(UserServiceClient, '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(UserServiceClient, '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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "true"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "false"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (UserServiceClient, transports.UserServiceRestTransport, "rest", "true"), + (UserServiceClient, transports.UserServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_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", [ + UserServiceClient, UserServiceAsyncClient +]) +@mock.patch.object(UserServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceAsyncClient)) +def test_user_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", [ + UserServiceClient, UserServiceAsyncClient +]) +@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) +@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +def test_user_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = UserServiceClient._DEFAULT_UNIVERSE + default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = UserServiceClient._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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), +]) +def test_user_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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (UserServiceClient, transports.UserServiceRestTransport, "rest", None), +]) +def test_user_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_user_service_client_client_options_from_dict(): + with mock.patch('google.shopping.merchant_accounts_v1beta.services.user_service.transports.UserServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserServiceClient( + 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", [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_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", [ + user.GetUserRequest, + dict, +]) +def test_get_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = user.GetUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, user.User) + assert response.name == 'name_value' + assert response.state == user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +def test_get_user_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 = UserServiceClient( + 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 = user.GetUserRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user.GetUserRequest( + name='name_value', + ) + +def test_get_user_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 = UserServiceClient( + 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.get_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_user] = mock_rpc + request = {} + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user(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_get_user_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 = UserServiceAsyncClient( + 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.get_user in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_user] = mock_rpc + + request = {} + await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_user(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_get_user_async(transport: str = 'grpc_asyncio', request_type=user.GetUserRequest): + client = UserServiceAsyncClient( + 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.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = user.GetUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, user.User) + assert response.name == 'name_value' + assert response.state == user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + +def test_get_user_field_headers(): + client = UserServiceClient( + 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 = user.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = user.User() + client.get_user(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_get_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = user.GetUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) + await client.get_user(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_get_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_user( + 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_get_user_flattened_error(): + client = UserServiceClient( + 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.get_user( + user.GetUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_user( + 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_get_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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.get_user( + user.GetUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.CreateUserRequest, + dict, +]) +def test_create_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + response = client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_user.CreateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +def test_create_user_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 = UserServiceClient( + 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 = gsma_user.CreateUserRequest( + parent='parent_value', + user_id='user_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_user.CreateUserRequest( + parent='parent_value', + user_id='user_id_value', + ) + +def test_create_user_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 = UserServiceClient( + 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.create_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_user] = mock_rpc + request = {} + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user(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_create_user_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 = UserServiceAsyncClient( + 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.create_user in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_user] = mock_rpc + + request = {} + await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_user(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_create_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.CreateUserRequest): + client = UserServiceAsyncClient( + 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.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + response = await client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_user.CreateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.asyncio +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) + +def test_create_user_field_headers(): + client = UserServiceClient( + 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 = gsma_user.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.create_user(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_create_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = gsma_user.CreateUserRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + await client.create_user(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_create_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_user( + parent='parent_value', + user=gsma_user.User(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + + +def test_create_user_flattened_error(): + client = UserServiceClient( + 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.create_user( + gsma_user.CreateUserRequest(), + parent='parent_value', + user=gsma_user.User(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_user( + parent='parent_value', + user=gsma_user.User(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].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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.create_user( + gsma_user.CreateUserRequest(), + parent='parent_value', + user=gsma_user.User(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + user.DeleteUserRequest, + dict, +]) +def test_delete_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = user.DeleteUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_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 = UserServiceClient( + 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 = user.DeleteUserRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user.DeleteUserRequest( + name='name_value', + ) + +def test_delete_user_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 = UserServiceClient( + 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_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_user] = mock_rpc + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(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_user_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 = UserServiceAsyncClient( + 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_user 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_user] = mock_rpc + + request = {} + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_user(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_user_async(transport: str = 'grpc_asyncio', request_type=user.DeleteUserRequest): + client = UserServiceAsyncClient( + 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_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = user.DeleteUserRequest() + 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_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + +def test_delete_user_field_headers(): + client = UserServiceClient( + 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 = user.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(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_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = user.DeleteUserRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(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_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__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_user( + 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_user_flattened_error(): + client = UserServiceClient( + 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_user( + user.DeleteUserRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__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_user( + 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_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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_user( + user.DeleteUserRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.UpdateUserRequest, + dict, +]) +def test_update_user(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + response = client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gsma_user.UpdateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +def test_update_user_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 = UserServiceClient( + 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 = gsma_user.UpdateUserRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gsma_user.UpdateUserRequest( + ) + +def test_update_user_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 = UserServiceClient( + 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.update_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_user] = mock_rpc + request = {} + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user(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_update_user_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 = UserServiceAsyncClient( + 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.update_user in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_user] = mock_rpc + + request = {} + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_user(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_update_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.UpdateUserRequest): + client = UserServiceAsyncClient( + 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.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + response = await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gsma_user.UpdateUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + +def test_update_user_field_headers(): + client = UserServiceClient( + 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 = gsma_user.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.update_user(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', + 'user.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = UserServiceAsyncClient( + 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 = gsma_user.UpdateUserRequest() + + request.user.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + await client.update_user(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', + 'user.name=name_value', + ) in kw['metadata'] + + +def test_update_user_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_user_flattened_error(): + client = UserServiceClient( + 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.update_user( + gsma_user.UpdateUserRequest(), + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gsma_user.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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].user + mock_val = gsma_user.User(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_user_flattened_error_async(): + client = UserServiceAsyncClient( + 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.update_user( + gsma_user.UpdateUserRequest(), + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + user.ListUsersRequest, + dict, +]) +def test_list_users(request_type, transport: str = 'grpc'): + client = UserServiceClient( + 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.ListUsersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = user.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_users_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 = UserServiceClient( + 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 = user.ListUsersRequest( + 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_users), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_users(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user.ListUsersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_users_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 = UserServiceClient( + 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_users in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_users] = mock_rpc + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_users(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_users_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 = UserServiceAsyncClient( + 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_users 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_users] = mock_rpc + + request = {} + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_users(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_users_async(transport: str = 'grpc_asyncio', request_type=user.ListUsersRequest): + client = UserServiceAsyncClient( + 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_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = user.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) + +def test_list_users_field_headers(): + client = UserServiceClient( + 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 = user.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = user.ListUsersResponse() + client.list_users(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_users_field_headers_async(): + client = UserServiceAsyncClient( + 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 = user.ListUsersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) + await client.list_users(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_users_flattened(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.ListUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_users( + 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_users_flattened_error(): + client = UserServiceClient( + 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_users( + user.ListUsersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_users_flattened_async(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user.ListUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_users( + 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_users_flattened_error_async(): + client = UserServiceAsyncClient( + 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_users( + user.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_pager(transport_name: str = "grpc"): + client = UserServiceClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_users(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, user.User) + for i in results) +def test_list_users_pages(transport_name: str = "grpc"): + client = UserServiceClient( + 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_users), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_users_async_pager(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users(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, user.User) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + 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_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_user_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 = UserServiceClient( + 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.get_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_user] = mock_rpc + + request = {} + client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_user(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_get_user_rest_required_fields(request_type=user.GetUserRequest): + transport_class = transports.UserServiceRestTransport + + 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()).get_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_user._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 = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user.User() + # 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 = user.User.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.get_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_user_rest_flattened(): + client = UserServiceClient( + 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 = user.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/users/sample2'} + + # 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 + # Convert return value to protobuf type + return_value = user.User.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.get_user(**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/accounts/v1beta/{name=accounts/*/users/*}" % client.transport._host, args[1]) + + +def test_get_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_user( + user.GetUserRequest(), + name='name_value', + ) + + +def test_create_user_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 = UserServiceClient( + 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.create_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_user] = mock_rpc + + request = {} + client.create_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_user(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_create_user_rest_required_fields(request_type=gsma_user.CreateUserRequest): + transport_class = transports.UserServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_id"] = "" + 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 + assert "userId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userId" in jsonified_request + assert jsonified_request["userId"] == request_init["user_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userId"] = 'user_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("user_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "userId" in jsonified_request + assert jsonified_request["userId"] == 'user_id_value' + + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_user.User() + # 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 = gsma_user.User.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.create_user(request) + + expected_params = [ + ( + "userId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("userId", )) & set(("parent", "userId", "user", ))) + + +def test_create_user_rest_flattened(): + client = UserServiceClient( + 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 = gsma_user.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + user=gsma_user.User(name='name_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 = gsma_user.User.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.create_user(**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/accounts/v1beta/{parent=accounts/*}/users" % client.transport._host, args[1]) + + +def test_create_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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.create_user( + gsma_user.CreateUserRequest(), + parent='parent_value', + user=gsma_user.User(name='name_value'), + ) + + +def test_delete_user_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 = UserServiceClient( + 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_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_user] = mock_rpc + + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(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_user_rest_required_fields(request_type=user.DeleteUserRequest): + transport_class = transports.UserServiceRestTransport + + 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_user._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_user._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 = UserServiceClient( + 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_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_delete_user_rest_flattened(): + client = UserServiceClient( + 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/users/sample2'} + + # 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_user(**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/accounts/v1beta/{name=accounts/*/users/*}" % client.transport._host, args[1]) + + +def test_delete_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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_user( + user.DeleteUserRequest(), + name='name_value', + ) + + +def test_update_user_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 = UserServiceClient( + 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.update_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_user] = mock_rpc + + request = {} + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_user(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_update_user_rest_required_fields(request_type=gsma_user.UpdateUserRequest): + transport_class = transports.UserServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gsma_user.User() + # 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': "patch", + '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 = gsma_user.User.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.update_user(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_user_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("user", "updateMask", ))) + + +def test_update_user_rest_flattened(): + client = UserServiceClient( + 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 = gsma_user.User() + + # get arguments that satisfy an http rule for this method + sample_request = {'user': {'name': 'accounts/sample1/users/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_user.User.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.update_user(**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/accounts/v1beta/{user.name=accounts/*/users/*}" % client.transport._host, args[1]) + + +def test_update_user_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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.update_user( + gsma_user.UpdateUserRequest(), + user=gsma_user.User(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_list_users_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 = UserServiceClient( + 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_users in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_users] = mock_rpc + + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_users(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_users_rest_required_fields(request_type=user.ListUsersRequest): + transport_class = transports.UserServiceRestTransport + + 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_users._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_users._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 = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user.ListUsersResponse() + # 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 = user.ListUsersResponse.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_users(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_users_rest_unset_required_fields(): + transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_users._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_users_rest_flattened(): + client = UserServiceClient( + 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 = user.ListUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # 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 = user.ListUsersResponse.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_users(**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/accounts/v1beta/{parent=accounts/*}/users" % client.transport._host, args[1]) + + +def test_list_users_rest_flattened_error(transport: str = 'rest'): + client = UserServiceClient( + 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_users( + user.ListUsersRequest(), + parent='parent_value', + ) + + +def test_list_users_rest_pager(transport: str = 'rest'): + client = UserServiceClient( + 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 = ( + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + user.User(), + ], + next_page_token='abc', + ), + user.ListUsersResponse( + users=[], + next_page_token='def', + ), + user.ListUsersResponse( + users=[ + user.User(), + ], + next_page_token='ghi', + ), + user.ListUsersResponse( + users=[ + user.User(), + user.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(user.ListUsersResponse.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'} + + pager = client.list_users(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, user.User) + for i in results) + + pages = list(client.list_users(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserServiceClient( + 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 = UserServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + transports.UserServiceRestTransport, +]) +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 = UserServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = UserServiceClient( + 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_get_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + call.return_value = user.User() + client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.GetUserRequest() + + 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_create_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.CreateUserRequest() + + 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_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + call.return_value = None + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.DeleteUserRequest() + + 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_update_user_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + call.return_value = gsma_user.User() + client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.UpdateUserRequest() + + 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_list_users_empty_call_grpc(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + call.return_value = user.ListUsersResponse() + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.ListUsersRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = UserServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = UserServiceAsyncClient( + 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_get_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + await client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.GetUserRequest() + + 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_create_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + await client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.CreateUserRequest() + + 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_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.DeleteUserRequest() + + 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_update_user_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + )) + await client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.UpdateUserRequest() + + 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_list_users_empty_call_grpc_asyncio(): + client = UserServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( + next_page_token='next_page_token_value', + )) + await client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.ListUsersRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = UserServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_user_rest_bad_request(request_type=user.GetUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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.get_user(request) + + +@pytest.mark.parametrize("request_type", [ + user.GetUserRequest, + dict, +]) +def test_get_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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 = user.User( + name='name_value', + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + + # 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 = user.User.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.get_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user.User) + assert response.name == 'name_value' + assert response.state == user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_get_user") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_get_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_get_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = user.GetUserRequest.pb(user.GetUserRequest()) + 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 = user.User.to_json(user.User()) + req.return_value.content = return_value + + request = user.GetUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user.User() + post_with_metadata.return_value = user.User(), metadata + + client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_user_rest_bad_request(request_type=gsma_user.CreateUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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.create_user(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.CreateUserRequest, + dict, +]) +def test_create_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["user"] = {'name': 'name_value', 'state': 1, 'access_rights': [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 = gsma_user.CreateUserRequest.meta.fields["user"] + + 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["user"].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["user"][field])): + del request_init["user"][field][i][subfield] + else: + del request_init["user"][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 = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + + # 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 = gsma_user.User.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.create_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_create_user") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_create_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_create_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_user.CreateUserRequest.pb(gsma_user.CreateUserRequest()) + 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 = gsma_user.User.to_json(gsma_user.User()) + req.return_value.content = return_value + + request = gsma_user.CreateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_user.User() + post_with_metadata.return_value = gsma_user.User(), metadata + + client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_user_rest_bad_request(request_type=user.DeleteUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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.delete_user(request) + + +@pytest.mark.parametrize("request_type", [ + user.DeleteUserRequest, + dict, +]) +def test_delete_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/users/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 = 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_user(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_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "pre_delete_user") as pre: + pre.assert_not_called() + pb_message = user.DeleteUserRequest.pb(user.DeleteUserRequest()) + 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 = user.DeleteUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_update_user_rest_bad_request(request_type=gsma_user.UpdateUserRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'accounts/sample1/users/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.update_user(request) + + +@pytest.mark.parametrize("request_type", [ + gsma_user.UpdateUserRequest, + dict, +]) +def test_update_user_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'user': {'name': 'accounts/sample1/users/sample2'}} + request_init["user"] = {'name': 'accounts/sample1/users/sample2', 'state': 1, 'access_rights': [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 = gsma_user.UpdateUserRequest.meta.fields["user"] + + 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["user"].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["user"][field])): + del request_init["user"][field][i][subfield] + else: + del request_init["user"][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 = gsma_user.User( + name='name_value', + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + + # 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 = gsma_user.User.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.update_user(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gsma_user.User) + assert response.name == 'name_value' + assert response.state == gsma_user.User.State.PENDING + assert response.access_rights == [accessright.AccessRight.STANDARD] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_user_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_update_user") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_update_user_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_update_user") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gsma_user.UpdateUserRequest.pb(gsma_user.UpdateUserRequest()) + 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 = gsma_user.User.to_json(gsma_user.User()) + req.return_value.content = return_value + + request = gsma_user.UpdateUserRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gsma_user.User() + post_with_metadata.return_value = gsma_user.User(), metadata + + client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_users_rest_bad_request(request_type=user.ListUsersRequest): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + 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_users(request) + + +@pytest.mark.parametrize("request_type", [ + user.ListUsersRequest, + dict, +]) +def test_list_users_rest_call_success(request_type): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = user.ListUsersResponse( + 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 = user.ListUsersResponse.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_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_users_rest_interceptors(null_interceptor): + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), + ) + client = UserServiceClient(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.UserServiceRestInterceptor, "post_list_users") as post, \ + mock.patch.object(transports.UserServiceRestInterceptor, "post_list_users_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.UserServiceRestInterceptor, "pre_list_users") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = user.ListUsersRequest.pb(user.ListUsersRequest()) + 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 = user.ListUsersResponse.to_json(user.ListUsersResponse()) + req.return_value.content = return_value + + request = user.ListUsersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user.ListUsersResponse() + post_with_metadata.return_value = user.ListUsersResponse(), metadata + + client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + +def test_initialize_client_w_rest(): + client = UserServiceClient( + 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_get_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_user), + '__call__') as call: + client.get_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.GetUserRequest() + + 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_create_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_user), + '__call__') as call: + client.create_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.CreateUserRequest() + + 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_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_user), + '__call__') as call: + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.DeleteUserRequest() + + 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_update_user_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_user), + '__call__') as call: + client.update_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gsma_user.UpdateUserRequest() + + 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_list_users_empty_call_rest(): + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_users), + '__call__') as call: + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = user.ListUsersRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserServiceGrpcTransport, + ) + +def test_user_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.shopping.merchant_accounts_v1beta.services.user_service.transports.UserServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_user', + 'create_user', + 'delete_user', + 'update_user', + 'list_users', + ) + 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_user_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_accounts_v1beta.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserServiceTransport( + 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_user_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_accounts_v1beta.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserServiceTransport() + adc.assert_called_once() + + +def test_user_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) + UserServiceClient() + 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.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + ], +) +def test_user_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.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + transports.UserServiceRestTransport, + ], +) +def test_user_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.UserServiceGrpcTransport, grpc_helpers), + (transports.UserServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) +def test_user_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_user_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.UserServiceRestTransport ( + 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_user_service_host_no_port(transport_name): + client = UserServiceClient( + 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_user_service_host_with_port(transport_name): + client = UserServiceClient( + 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_user_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = UserServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = UserServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_user._session + session2 = client2.transport.get_user._session + assert session1 != session2 + session1 = client1.transport.create_user._session + session2 = client2.transport.create_user._session + assert session1 != session2 + session1 = client1.transport.delete_user._session + session2 = client2.transport.delete_user._session + assert session1 != session2 + session1 = client1.transport.update_user._session + session2 = client2.transport.update_user._session + assert session1 != session2 + session1 = client1.transport.list_users._session + session2 = client2.transport.list_users._session + assert session1 != session2 +def test_user_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserServiceGrpcTransport( + 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_user_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserServiceGrpcAsyncIOTransport( + 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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) +def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) +def test_user_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = UserServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = UserServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_account_path(path) + assert expected == actual + +def test_user_path(): + account = "whelk" + email = "octopus" + expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) + actual = UserServiceClient.user_path(account, email) + assert expected == actual + + +def test_parse_user_path(): + expected = { + "account": "oyster", + "email": "nudibranch", + } + path = UserServiceClient.user_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_user_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = UserServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = UserServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = UserServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = UserServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = UserServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.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 = UserServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = UserServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserServiceClient.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.UserServiceTransport, '_prep_wrapped_messages') as prep: + client = UserServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserServiceClient.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 = UserServiceClient( + 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 = UserServiceAsyncClient( + 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 = UserServiceClient( + 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 = UserServiceClient( + 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", [ + (UserServiceClient, transports.UserServiceGrpcTransport), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport), +]) +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 fe7ad1b0426fd8a2601bffbf1dbf675153e4a7f5 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 6 Aug 2025 10:45:01 +0000 Subject: [PATCH 2/3] fix docs --- .../client-post-processing/doc-formatting.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/scripts/client-post-processing/doc-formatting.yaml b/scripts/client-post-processing/doc-formatting.yaml index b7fde0c0775d..73ab22a37423 100644 --- a/scripts/client-post-processing/doc-formatting.yaml +++ b/scripts/client-post-processing/doc-formatting.yaml @@ -361,24 +361,36 @@ replacements: packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py, ] before: name=accounts\/\*\/users\/me\/emailPreferences alias after: "`name=accounts/*/users/me/emailPreferences` alias" - count: 8 + count: 16 - paths: [ packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py, ] before: "This API defines the following resource model:\n --------------------------------------------------------\n\n `OnlineReturnPolicy" after: "This API defines the following resource model:\n\n - `OnlineReturnPolicy" - count: 4 + count: 8 - paths: [ packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py, packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py, + packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py, ] before: | This API defines the following resource model: @@ -387,7 +399,7 @@ replacements: after: | This API defines the following resource model: - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] - count: 4 + count: 8 - paths: [ packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py ] From ceba772a9849504dc3a3be9de1d0faca84e0c2bd Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 6 Aug 2025 10:55:38 +0000 Subject: [PATCH 3/3] =?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_accounts/__init__.py | 409 - .../shopping/merchant_accounts_v1/__init__.py | 410 - .../merchant_accounts_v1/gapic_version.py | 16 - .../shopping/merchant_accounts_v1/py.typed | 2 - .../services/accounts_service/__init__.py | 22 - .../accounts_service/transports/__init__.py | 38 - .../autofeed_settings_service/__init__.py | 22 - .../transports/__init__.py | 38 - .../business_info_service/__init__.py | 22 - .../transports/__init__.py | 38 - .../transports/__init__.py | 38 - .../transports/__init__.py | 38 - .../services/gbp_accounts_service/__init__.py | 22 - .../transports/__init__.py | 38 - .../transports/__init__.py | 38 - .../services/programs_service/__init__.py | 22 - .../programs_service/transports/__init__.py | 38 - .../regions_service/transports/__init__.py | 38 - .../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_accounts_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 - .../account_issue_service.rst | 10 - .../account_tax_service.rst | 10 - .../accounts_service.rst | 10 - .../autofeed_settings_service.rst | 6 - .../automatic_improvements_service.rst | 6 - .../business_identity_service.rst | 6 - .../business_info_service.rst | 6 - .../checkout_settings_service.rst | 6 - .../email_preferences_service.rst | 6 - .../gbp_accounts_service.rst | 10 - .../homepage_service.rst | 6 - .../lfp_providers_service.rst | 10 - .../omnichannel_settings_service.rst | 10 - .../online_return_policy_service.rst | 10 - .../programs_service.rst | 10 - .../regions_service.rst | 10 - .../merchant_accounts_v1beta/services_.rst | 25 - .../shipping_settings_service.rst | 6 - ...rms_of_service_agreement_state_service.rst | 6 - .../terms_of_service_service.rst | 6 - .../docs/merchant_accounts_v1beta/types_.rst | 6 - .../merchant_accounts_v1beta/user_service.rst | 10 - .../v1beta/docs/multiprocessing.rst | 7 - .../shopping/merchant_accounts/__init__.py | 371 - .../merchant_accounts/gapic_version.py | 16 - .../shopping/merchant_accounts/py.typed | 2 - .../merchant_accounts_v1beta/__init__.py | 372 - .../gapic_metadata.json | 1334 -- .../merchant_accounts_v1beta/gapic_version.py | 16 - .../merchant_accounts_v1beta/py.typed | 2 - .../account_issue_service/__init__.py | 22 - .../account_issue_service/async_client.py | 386 - .../services/account_issue_service/client.py | 755 -- .../services/account_issue_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../account_issue_service/transports/base.py | 159 - .../account_issue_service/transports/grpc.py | 347 - .../transports/grpc_asyncio.py | 368 - .../account_issue_service/transports/rest.py | 351 - .../transports/rest_base.py | 128 - .../services/account_tax_service/__init__.py | 22 - .../account_tax_service/async_client.py | 623 - .../services/account_tax_service/client.py | 981 -- .../services/account_tax_service/pagers.py | 166 - .../account_tax_service/transports/README.rst | 9 - .../transports/__init__.py | 38 - .../account_tax_service/transports/base.py | 188 - .../account_tax_service/transports/grpc.py | 407 - .../transports/grpc_asyncio.py | 438 - .../account_tax_service/transports/rest.py | 715 -- .../transports/rest_base.py | 213 - .../services/accounts_service/async_client.py | 894 -- .../services/accounts_service/client.py | 1269 -- .../services/accounts_service/pagers.py | 305 - .../accounts_service/transports/README.rst | 9 - .../accounts_service/transports/base.py | 230 - .../accounts_service/transports/grpc.py | 501 - .../transports/grpc_asyncio.py | 547 - .../accounts_service/transports/rest.py | 1149 -- .../accounts_service/transports/rest_base.py | 326 - .../autofeed_settings_service/async_client.py | 493 - .../autofeed_settings_service/client.py | 852 -- .../transports/README.rst | 9 - .../transports/base.py | 173 - .../transports/grpc.py | 374 - .../transports/grpc_asyncio.py | 400 - .../transports/rest.py | 534 - .../transports/rest_base.py | 175 - .../__init__.py | 22 - .../async_client.py | 499 - .../automatic_improvements_service/client.py | 858 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 173 - .../transports/grpc.py | 374 - .../transports/grpc_asyncio.py | 400 - .../transports/rest.py | 537 - .../transports/rest_base.py | 175 - .../business_identity_service/__init__.py | 22 - .../business_identity_service/async_client.py | 488 - .../business_identity_service/client.py | 847 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 173 - .../transports/grpc.py | 375 - .../transports/grpc_asyncio.py | 401 - .../transports/rest.py | 532 - .../transports/rest_base.py | 175 - .../business_info_service/async_client.py | 488 - .../services/business_info_service/client.py | 847 -- .../transports/README.rst | 9 - .../business_info_service/transports/base.py | 173 - .../business_info_service/transports/grpc.py | 373 - .../transports/grpc_asyncio.py | 399 - .../business_info_service/transports/rest.py | 529 - .../transports/rest_base.py | 175 - .../checkout_settings_service/__init__.py | 22 - .../checkout_settings_service/async_client.py | 706 -- .../checkout_settings_service/client.py | 1063 -- .../transports/README.rst | 9 - .../transports/base.py | 202 - .../transports/grpc.py | 429 - .../transports/grpc_asyncio.py | 465 - .../transports/rest.py | 815 -- .../transports/rest_base.py | 260 - .../email_preferences_service/__init__.py | 22 - .../email_preferences_service/async_client.py | 511 - .../email_preferences_service/client.py | 870 -- .../transports/README.rst | 9 - .../transports/base.py | 173 - .../transports/grpc.py | 390 - .../transports/grpc_asyncio.py | 416 - .../transports/rest.py | 540 - .../transports/rest_base.py | 175 - .../gbp_accounts_service/async_client.py | 502 - .../services/gbp_accounts_service/client.py | 870 -- .../services/gbp_accounts_service/pagers.py | 166 - .../transports/README.rst | 9 - .../gbp_accounts_service/transports/base.py | 173 - .../gbp_accounts_service/transports/grpc.py | 377 - .../transports/grpc_asyncio.py | 403 - .../gbp_accounts_service/transports/rest.py | 535 - .../transports/rest_base.py | 175 - .../services/homepage_service/__init__.py | 22 - .../services/homepage_service/async_client.py | 658 - .../services/homepage_service/client.py | 1017 -- .../homepage_service/transports/README.rst | 9 - .../homepage_service/transports/__init__.py | 38 - .../homepage_service/transports/base.py | 202 - .../homepage_service/transports/grpc.py | 439 - .../transports/grpc_asyncio.py | 475 - .../homepage_service/transports/rest.py | 874 -- .../homepage_service/transports/rest_base.py | 270 - .../lfp_providers_service/__init__.py | 22 - .../lfp_providers_service/async_client.py | 503 - .../services/lfp_providers_service/client.py | 871 -- .../services/lfp_providers_service/pagers.py | 166 - .../transports/README.rst | 9 - .../lfp_providers_service/transports/base.py | 173 - .../lfp_providers_service/transports/grpc.py | 376 - .../transports/grpc_asyncio.py | 402 - .../lfp_providers_service/transports/rest.py | 534 - .../transports/rest_base.py | 175 - .../omnichannel_settings_service/__init__.py | 22 - .../async_client.py | 866 -- .../omnichannel_settings_service/client.py | 1231 -- .../omnichannel_settings_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 215 - .../transports/grpc.py | 459 - .../transports/grpc_asyncio.py | 500 - .../transports/rest.py | 1068 -- .../transports/rest_base.py | 306 - .../online_return_policy_service/__init__.py | 22 - .../async_client.py | 860 -- .../online_return_policy_service/client.py | 1216 -- .../online_return_policy_service/pagers.py | 166 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 217 - .../transports/grpc.py | 461 - .../transports/grpc_asyncio.py | 502 - .../transports/rest.py | 1009 -- .../transports/rest_base.py | 298 - .../services/programs_service/async_client.py | 740 -- .../services/programs_service/client.py | 1097 -- .../services/programs_service/pagers.py | 166 - .../programs_service/transports/README.rst | 9 - .../programs_service/transports/base.py | 201 - .../programs_service/transports/grpc.py | 437 - .../transports/grpc_asyncio.py | 473 - .../programs_service/transports/rest.py | 913 -- .../programs_service/transports/rest_base.py | 259 - .../services/regions_service/__init__.py | 22 - .../services/regions_service/async_client.py | 847 -- .../services/regions_service/client.py | 1212 -- .../services/regions_service/pagers.py | 166 - .../regions_service/transports/README.rst | 9 - .../regions_service/transports/base.py | 216 - .../regions_service/transports/grpc.py | 459 - .../transports/grpc_asyncio.py | 500 - .../regions_service/transports/rest.py | 1004 -- .../regions_service/transports/rest_base.py | 297 - .../shipping_settings_service/__init__.py | 22 - .../shipping_settings_service/async_client.py | 461 - .../shipping_settings_service/client.py | 821 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 173 - .../transports/grpc.py | 375 - .../transports/grpc_asyncio.py | 401 - .../transports/rest.py | 531 - .../transports/rest_base.py | 175 - .../__init__.py | 22 - .../async_client.py | 536 - .../client.py | 913 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 173 - .../transports/grpc.py | 375 - .../transports/grpc_asyncio.py | 401 - .../transports/rest.py | 583 - .../transports/rest_base.py | 165 - .../terms_of_service_service/__init__.py | 22 - .../terms_of_service_service/async_client.py | 543 - .../terms_of_service_service/client.py | 911 -- .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../transports/base.py | 188 - .../transports/grpc.py | 403 - .../transports/grpc_asyncio.py | 434 - .../transports/rest.py | 630 - .../transports/rest_base.py | 203 - .../services/user_service/__init__.py | 22 - .../services/user_service/async_client.py | 827 -- .../services/user_service/client.py | 1192 -- .../services/user_service/pagers.py | 166 - .../user_service/transports/README.rst | 9 - .../user_service/transports/__init__.py | 38 - .../services/user_service/transports/base.py | 217 - .../services/user_service/transports/grpc.py | 455 - .../user_service/transports/grpc_asyncio.py | 496 - .../services/user_service/transports/rest.py | 983 -- .../user_service/transports/rest_base.py | 298 - .../types/__init__.py | 338 - .../types/accessright.py | 51 - .../types/account_tax.py | 167 - .../types/accountissue.py | 236 - .../types/accounts.py | 408 - .../types/accountservices.py | 36 - .../types/autofeedsettings.py | 111 - .../types/automaticimprovements.py | 386 - .../types/businessidentity.py | 204 - .../types/businessinfo.py | 148 - .../types/checkoutsettings.py | 316 - .../types/customerservice.py | 74 - .../types/emailpreferences.py | 121 - .../types/gbpaccounts.py | 198 - .../types/homepage.py | 139 - .../types/lfpproviders.py | 172 - .../types/omnichannelsettings.py | 548 - .../types/online_return_policy.py | 581 - .../types/phoneverificationstate.py | 47 - .../types/programs.py | 254 - .../merchant_accounts_v1beta/types/regions.py | 323 - .../types/shippingsettings.py | 1489 --- .../types/tax_rule.py | 149 - .../types/termsofservice.py | 164 - .../types/termsofserviceagreementstate.py | 217 - .../types/termsofservicekind.py | 44 - .../merchant_accounts_v1beta/types/user.py | 246 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 591 - ...issue_service_list_account_issues_async.py | 53 - ..._issue_service_list_account_issues_sync.py | 53 - ...count_tax_service_get_account_tax_async.py | 52 - ...ccount_tax_service_get_account_tax_sync.py | 52 - ...ount_tax_service_list_account_tax_async.py | 53 - ...count_tax_service_list_account_tax_sync.py | 53 - ...nt_tax_service_update_account_tax_async.py | 51 - ...unt_tax_service_update_account_tax_sync.py | 51 - ...vice_create_and_configure_account_async.py | 56 - ...rvice_create_and_configure_account_sync.py | 56 - ...d_accounts_service_delete_account_async.py | 50 - ...ed_accounts_service_delete_account_sync.py | 50 - ...ated_accounts_service_get_account_async.py | 52 - ...rated_accounts_service_get_account_sync.py | 52 - ...ed_accounts_service_list_accounts_async.py | 52 - ...ted_accounts_service_list_accounts_sync.py | 52 - ...ccounts_service_list_sub_accounts_async.py | 53 - ...accounts_service_list_sub_accounts_sync.py | 53 - ...d_accounts_service_update_account_async.py | 56 - ...ed_accounts_service_update_account_sync.py | 56 - ...ngs_service_get_autofeed_settings_async.py | 52 - ...ings_service_get_autofeed_settings_sync.py | 52 - ..._service_update_autofeed_settings_async.py | 55 - ...s_service_update_autofeed_settings_sync.py | 55 - ...ervice_get_automatic_improvements_async.py | 52 - ...service_get_automatic_improvements_sync.py | 52 - ...ice_update_automatic_improvements_async.py | 51 - ...vice_update_automatic_improvements_sync.py | 51 - ...ity_service_get_business_identity_async.py | 52 - ...tity_service_get_business_identity_sync.py | 52 - ..._service_update_business_identity_async.py | 51 - ...y_service_update_business_identity_sync.py | 51 - ...ss_info_service_get_business_info_async.py | 52 - ...ess_info_service_get_business_info_sync.py | 52 - ...info_service_update_business_info_async.py | 51 - ..._info_service_update_business_info_sync.py | 51 - ..._service_create_checkout_settings_async.py | 52 - ...s_service_create_checkout_settings_sync.py | 52 - ..._service_delete_checkout_settings_async.py | 50 - ...s_service_delete_checkout_settings_sync.py | 50 - ...ngs_service_get_checkout_settings_async.py | 52 - ...ings_service_get_checkout_settings_sync.py | 52 - ..._service_update_checkout_settings_async.py | 51 - ...s_service_update_checkout_settings_sync.py | 51 - ...ces_service_get_email_preferences_async.py | 52 - ...nces_service_get_email_preferences_sync.py | 52 - ..._service_update_email_preferences_async.py | 51 - ...s_service_update_email_preferences_sync.py | 51 - ...accounts_service_link_gbp_account_async.py | 53 - ..._accounts_service_link_gbp_account_sync.py | 53 - ...ccounts_service_list_gbp_accounts_async.py | 53 - ...accounts_service_list_gbp_accounts_sync.py | 53 - ...d_homepage_service_claim_homepage_async.py | 52 - ...ed_homepage_service_claim_homepage_sync.py | 52 - ...ted_homepage_service_get_homepage_async.py | 52 - ...ated_homepage_service_get_homepage_sync.py | 52 - ...homepage_service_unclaim_homepage_async.py | 52 - ..._homepage_service_unclaim_homepage_sync.py | 52 - ..._homepage_service_update_homepage_async.py | 51 - ...d_homepage_service_update_homepage_sync.py | 51 - ...viders_service_find_lfp_providers_async.py | 53 - ...oviders_service_find_lfp_providers_sync.py | 53 - ...oviders_service_link_lfp_provider_async.py | 53 - ...roviders_service_link_lfp_provider_sync.py | 53 - ...ervice_create_omnichannel_setting_async.py | 57 - ...service_create_omnichannel_setting_sync.py | 57 - ...s_service_get_omnichannel_setting_async.py | 52 - ...gs_service_get_omnichannel_setting_sync.py | 52 - ...service_list_omnichannel_settings_async.py | 53 - ..._service_list_omnichannel_settings_sync.py | 53 - ...ce_request_inventory_verification_async.py | 52 - ...ice_request_inventory_verification_sync.py | 52 - ...ervice_update_omnichannel_setting_async.py | 56 - ...service_update_omnichannel_setting_sync.py | 56 - ...rvice_create_online_return_policy_async.py | 58 - ...ervice_create_online_return_policy_sync.py | 58 - ...rvice_delete_online_return_policy_async.py | 50 - ...ervice_delete_online_return_policy_sync.py | 50 - ..._service_get_online_return_policy_async.py | 52 - ...y_service_get_online_return_policy_sync.py | 52 - ...rvice_list_online_return_policies_async.py | 53 - ...ervice_list_online_return_policies_sync.py | 53 - ...rvice_update_online_return_policy_async.py | 57 - ...ervice_update_online_return_policy_sync.py | 57 - ..._programs_service_disable_program_async.py | 52 - ...d_programs_service_disable_program_sync.py | 52 - ...d_programs_service_enable_program_async.py | 52 - ...ed_programs_service_enable_program_sync.py | 52 - ...ated_programs_service_get_program_async.py | 52 - ...rated_programs_service_get_program_sync.py | 52 - ...ed_programs_service_list_programs_async.py | 53 - ...ted_programs_service_list_programs_sync.py | 53 - ...ted_regions_service_create_region_async.py | 53 - ...ated_regions_service_create_region_sync.py | 53 - ...ted_regions_service_delete_region_async.py | 50 - ...ated_regions_service_delete_region_sync.py | 50 - ...erated_regions_service_get_region_async.py | 52 - ...nerated_regions_service_get_region_sync.py | 52 - ...ated_regions_service_list_regions_async.py | 53 - ...rated_regions_service_list_regions_sync.py | 53 - ...ted_regions_service_update_region_async.py | 51 - ...ated_regions_service_update_region_sync.py | 51 - ...ngs_service_get_shipping_settings_async.py | 52 - ...ings_service_get_shipping_settings_sync.py | 52 - ..._service_insert_shipping_settings_async.py | 56 - ...s_service_insert_shipping_settings_sync.py | 56 - ..._terms_of_service_agreement_state_async.py | 52 - ...t_terms_of_service_agreement_state_sync.py | 52 - ..._terms_of_service_agreement_state_async.py | 52 - ...n_terms_of_service_agreement_state_sync.py | 52 - ...e_service_accept_terms_of_service_async.py | 52 - ...ce_service_accept_terms_of_service_sync.py | 52 - ...vice_service_get_terms_of_service_async.py | 52 - ...rvice_service_get_terms_of_service_sync.py | 52 - ..._retrieve_latest_terms_of_service_async.py | 53 - ...e_retrieve_latest_terms_of_service_sync.py | 53 - ...enerated_user_service_create_user_async.py | 53 - ...generated_user_service_create_user_sync.py | 53 - ...enerated_user_service_delete_user_async.py | 50 - ...generated_user_service_delete_user_sync.py | 50 - ...a_generated_user_service_get_user_async.py | 52 - ...ta_generated_user_service_get_user_sync.py | 52 - ...generated_user_service_list_users_async.py | 53 - ..._generated_user_service_list_users_sync.py | 53 - ...enerated_user_service_update_user_async.py | 51 - ...generated_user_service_update_user_sync.py | 51 - ...gle.shopping.merchant.accounts.v1beta.json | 10226 ---------------- ...fixup_merchant_accounts_v1beta_keywords.py | 238 - .../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_accounts_v1beta/__init__.py | 16 - .../test_account_issue_service.py | 2418 ---- .../test_account_tax_service.py | 3803 ------ .../test_accounts_service.py | 5650 --------- .../test_autofeed_settings_service.py | 2890 ----- .../test_automatic_improvements_service.py | 2862 ----- .../test_business_identity_service.py | 2876 ----- .../test_business_info_service.py | 2894 ----- .../test_checkout_settings_service.py | 4334 ------- .../test_email_preferences_service.py | 2878 ----- .../test_gbp_accounts_service.py | 3072 ----- .../test_homepage_service.py | 3965 ------ .../test_lfp_providers_service.py | 3076 ----- .../test_omnichannel_settings_service.py | 5231 -------- .../test_online_return_policy_service.py | 5362 -------- .../test_programs_service.py | 4435 ------- .../test_regions_service.py | 5216 -------- .../test_shipping_settings_service.py | 2733 ----- ...erms_of_service_agreement_state_service.py | 2854 ----- .../test_terms_of_service_service.py | 3331 ----- .../test_user_service.py | 5226 -------- .../docs/index.rst | 11 + .../account_issue_service.rst | 0 .../account_relationships_service.rst | 0 .../account_services_service.rst | 0 .../merchant_accounts_v1/accounts_service.rst | 0 .../autofeed_settings_service.rst | 0 .../automatic_improvements_service.rst | 0 .../business_identity_service.rst | 0 .../business_info_service.rst | 0 .../checkout_settings_service.rst | 0 .../developer_registration_service.rst | 0 .../email_preferences_service.rst | 0 .../gbp_accounts_service.rst | 0 .../merchant_accounts_v1/homepage_service.rst | 0 .../lfp_providers_service.rst | 0 .../omnichannel_settings_service.rst | 0 .../online_return_policy_service.rst | 0 .../merchant_accounts_v1/programs_service.rst | 0 .../merchant_accounts_v1/regions_service.rst | 0 .../docs/merchant_accounts_v1/services_.rst | 0 .../shipping_settings_service.rst | 0 ...rms_of_service_agreement_state_service.rst | 0 .../terms_of_service_service.rst | 0 .../docs/merchant_accounts_v1/types_.rst | 0 .../merchant_accounts_v1/user_service.rst | 0 .../merchant_accounts/gapic_version.py | 2 +- .../shopping/merchant_accounts_v1/__init__.py | 482 + .../merchant_accounts_v1/gapic_metadata.json | 0 .../merchant_accounts_v1}/gapic_version.py | 0 .../shopping/merchant_accounts_v1}/py.typed | 0 .../merchant_accounts_v1/services/__init__.py | 0 .../account_issue_service/__init__.py | 6 +- .../account_issue_service/async_client.py | 154 +- .../services/account_issue_service/client.py | 322 +- .../services/account_issue_service/pagers.py | 75 +- .../transports/README.rst | 0 .../transports/__init__.py | 24 +- .../account_issue_service/transports/base.py | 95 +- .../account_issue_service/transports/grpc.py | 104 +- .../transports/grpc_asyncio.py | 113 +- .../account_issue_service/transports/rest.py | 192 +- .../transports/rest_base.py | 72 +- .../account_relationships_service/__init__.py | 6 +- .../async_client.py | 271 +- .../account_relationships_service/client.py | 435 +- .../account_relationships_service/pagers.py | 81 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 125 +- .../transports/grpc.py | 143 +- .../transports/grpc_asyncio.py | 155 +- .../transports/rest.py | 572 +- .../transports/rest_base.py | 158 +- .../account_services_service/__init__.py | 6 +- .../account_services_service/async_client.py | 318 +- .../account_services_service/client.py | 464 +- .../account_services_service/pagers.py | 75 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 151 +- .../transports/grpc.py | 169 +- .../transports/grpc_asyncio.py | 182 +- .../transports/rest.py | 680 +- .../transports/rest_base.py | 228 +- .../services/accounts_service/__init__.py | 6 +- .../services/accounts_service/async_client.py | 300 +- .../services/accounts_service/client.py | 455 +- .../services/accounts_service/pagers.py | 132 +- .../accounts_service/transports/README.rst | 0 .../accounts_service/transports/__init__.py | 20 +- .../accounts_service/transports/base.py | 157 +- .../accounts_service/transports/grpc.py | 174 +- .../transports/grpc_asyncio.py | 190 +- .../accounts_service/transports/rest.py | 802 +- .../accounts_service/transports/rest_base.py | 241 +- .../autofeed_settings_service/__init__.py | 6 +- .../autofeed_settings_service/async_client.py | 214 +- .../autofeed_settings_service/client.py | 354 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 110 +- .../transports/grpc.py | 121 +- .../transports/grpc_asyncio.py | 130 +- .../transports/rest.py | 328 +- .../transports/rest_base.py | 114 +- .../__init__.py | 6 +- .../async_client.py | 228 +- .../automatic_improvements_service/client.py | 388 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 110 +- .../transports/grpc.py | 126 +- .../transports/grpc_asyncio.py | 138 +- .../transports/rest.py | 420 +- .../transports/rest_base.py | 126 +- .../business_identity_service/__init__.py | 6 +- .../business_identity_service/async_client.py | 214 +- .../business_identity_service/client.py | 354 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 110 +- .../transports/grpc.py | 121 +- .../transports/grpc_asyncio.py | 130 +- .../transports/rest.py | 328 +- .../transports/rest_base.py | 112 +- .../business_info_service/__init__.py | 6 +- .../business_info_service/async_client.py | 202 +- .../services/business_info_service/client.py | 354 +- .../transports/README.rst | 0 .../transports/__init__.py | 24 +- .../business_info_service/transports/base.py | 104 +- .../business_info_service/transports/grpc.py | 116 +- .../transports/grpc_asyncio.py | 128 +- .../business_info_service/transports/rest.py | 309 +- .../transports/rest_base.py | 112 +- .../checkout_settings_service/__init__.py | 6 +- .../checkout_settings_service/async_client.py | 292 +- .../checkout_settings_service/client.py | 431 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 139 +- .../transports/grpc.py | 154 +- .../transports/grpc_asyncio.py | 165 +- .../transports/rest.py | 560 +- .../transports/rest_base.py | 190 +- .../__init__.py | 6 +- .../async_client.py | 228 +- .../developer_registration_service/client.py | 380 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 124 +- .../transports/grpc.py | 140 +- .../transports/grpc_asyncio.py | 154 +- .../transports/rest.py | 471 +- .../transports/rest_base.py | 162 +- .../email_preferences_service/__init__.py | 6 +- .../email_preferences_service/async_client.py | 218 +- .../email_preferences_service/client.py | 364 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 110 +- .../transports/grpc.py | 125 +- .../transports/grpc_asyncio.py | 134 +- .../transports/rest.py | 328 +- .../transports/rest_base.py | 114 +- .../services/gbp_accounts_service/__init__.py | 6 +- .../gbp_accounts_service/async_client.py | 190 +- .../services/gbp_accounts_service/client.py | 358 +- .../services/gbp_accounts_service/pagers.py | 75 +- .../transports/README.rst | 0 .../transports/__init__.py | 24 +- .../gbp_accounts_service/transports/base.py | 110 +- .../gbp_accounts_service/transports/grpc.py | 120 +- .../transports/grpc_asyncio.py | 130 +- .../gbp_accounts_service/transports/rest.py | 323 +- .../transports/rest_base.py | 112 +- .../services/homepage_service/__init__.py | 6 +- .../services/homepage_service/async_client.py | 236 +- .../services/homepage_service/client.py | 383 +- .../homepage_service/transports/README.rst | 0 .../homepage_service/transports/__init__.py | 20 +- .../homepage_service/transports/base.py | 130 +- .../homepage_service/transports/grpc.py | 146 +- .../transports/grpc_asyncio.py | 156 +- .../homepage_service/transports/rest.py | 527 +- .../homepage_service/transports/rest_base.py | 194 +- .../lfp_providers_service/__init__.py | 6 +- .../lfp_providers_service/async_client.py | 198 +- .../services/lfp_providers_service/client.py | 368 +- .../services/lfp_providers_service/pagers.py | 75 +- .../transports/README.rst | 0 .../transports/__init__.py | 24 +- .../lfp_providers_service/transports/base.py | 110 +- .../lfp_providers_service/transports/grpc.py | 120 +- .../transports/grpc_asyncio.py | 130 +- .../lfp_providers_service/transports/rest.py | 323 +- .../transports/rest_base.py | 112 +- .../omnichannel_settings_service/__init__.py | 6 +- .../async_client.py | 347 +- .../omnichannel_settings_service/client.py | 500 +- .../omnichannel_settings_service/pagers.py | 81 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 155 +- .../transports/grpc.py | 183 +- .../transports/grpc_asyncio.py | 195 +- .../transports/rest.py | 862 +- .../transports/rest_base.py | 232 +- .../online_return_policy_service/__init__.py | 6 +- .../async_client.py | 314 +- .../online_return_policy_service/client.py | 461 +- .../online_return_policy_service/pagers.py | 81 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 143 +- .../transports/grpc.py | 170 +- .../transports/grpc_asyncio.py | 179 +- .../transports/rest.py | 682 +- .../transports/rest_base.py | 198 +- .../services/programs_service/__init__.py | 6 +- .../services/programs_service/async_client.py | 253 +- .../services/programs_service/client.py | 402 +- .../services/programs_service/pagers.py | 75 +- .../programs_service/transports/README.rst | 0 .../programs_service/transports/__init__.py | 20 +- .../programs_service/transports/base.py | 128 +- .../programs_service/transports/grpc.py | 142 +- .../transports/grpc_asyncio.py | 154 +- .../programs_service/transports/rest.py | 510 +- .../programs_service/transports/rest_base.py | 186 +- .../services/regions_service/__init__.py | 6 +- .../services/regions_service/async_client.py | 295 +- .../services/regions_service/client.py | 450 +- .../services/regions_service/pagers.py | 75 +- .../regions_service/transports/README.rst | 0 .../regions_service/transports/__init__.py | 20 +- .../regions_service/transports/base.py | 139 +- .../regions_service/transports/grpc.py | 152 +- .../transports/grpc_asyncio.py | 168 +- .../regions_service/transports/rest.py | 595 +- .../regions_service/transports/rest_base.py | 224 +- .../shipping_settings_service/__init__.py | 6 +- .../shipping_settings_service/async_client.py | 197 +- .../shipping_settings_service/client.py | 347 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 110 +- .../transports/grpc.py | 121 +- .../transports/grpc_asyncio.py | 130 +- .../transports/rest.py | 328 +- .../transports/rest_base.py | 112 +- .../__init__.py | 6 +- .../async_client.py | 265 +- .../client.py | 451 +- .../transports/README.rst | 0 .../transports/__init__.py | 29 +- .../transports/base.py | 112 +- .../transports/grpc.py | 135 +- .../transports/grpc_asyncio.py | 143 +- .../transports/rest.py | 534 +- .../transports/rest_base.py | 120 +- .../terms_of_service_service/__init__.py | 6 +- .../terms_of_service_service/async_client.py | 236 +- .../terms_of_service_service/client.py | 401 +- .../transports/README.rst | 0 .../transports/__init__.py | 27 +- .../transports/base.py | 119 +- .../transports/grpc.py | 140 +- .../transports/grpc_asyncio.py | 149 +- .../transports/rest.py | 508 +- .../transports/rest_base.py | 146 +- .../services/user_service/__init__.py | 6 +- .../services/user_service/async_client.py | 283 +- .../services/user_service/client.py | 449 +- .../services/user_service/pagers.py | 75 +- .../user_service/transports/README.rst | 0 .../user_service/transports/__init__.py | 20 +- .../services/user_service/transports/base.py | 136 +- .../services/user_service/transports/grpc.py | 150 +- .../user_service/transports/grpc_asyncio.py | 166 +- .../services/user_service/transports/rest.py | 591 +- .../user_service/transports/rest_base.py | 224 +- .../merchant_accounts_v1/types/__init__.py | 314 +- .../merchant_accounts_v1/types/accessright.py | 5 +- .../types/accountissue.py | 27 +- .../types/accountrelationships.py | 24 +- .../merchant_accounts_v1/types/accounts.py | 43 +- .../types/accountservices.py | 88 +- .../types/autofeedsettings.py | 16 +- .../types/automaticimprovements.py | 46 +- .../types/businessidentity.py | 22 +- .../types/businessinfo.py | 33 +- .../types/checkoutsettings.py | 43 +- .../types/customerservice.py | 8 +- .../types/developerregistration.py | 11 +- .../types/emailpreferences.py | 17 +- .../merchant_accounts_v1/types/gbpaccounts.py | 21 +- .../merchant_accounts_v1/types/homepage.py | 20 +- .../types/lfpproviders.py | 20 +- .../types/omnichannelsettings.py | 106 +- .../types/online_return_policy.py | 45 +- .../types/phoneverificationstate.py | 5 +- .../merchant_accounts_v1/types/programs.py | 20 +- .../merchant_accounts_v1/types/regions.py | 38 +- .../types/shippingsettings.py | 186 +- .../types/termsofservice.py | 19 +- .../types/termsofserviceagreementstate.py | 23 +- .../types/termsofservicekind.py | 5 +- .../merchant_accounts_v1/types/user.py | 32 +- .../merchant_accounts_v1beta/gapic_version.py | 2 +- ...issue_service_list_account_issues_async.py | 0 ..._issue_service_list_account_issues_sync.py | 0 ..._service_get_account_relationship_async.py | 0 ...s_service_get_account_relationship_sync.py | 0 ...ervice_list_account_relationships_async.py | 0 ...service_list_account_relationships_sync.py | 0 ...rvice_update_account_relationship_async.py | 0 ...ervice_update_account_relationship_sync.py | 0 ...s_service_approve_account_service_async.py | 0 ...es_service_approve_account_service_sync.py | 0 ...vices_service_get_account_service_async.py | 0 ...rvices_service_get_account_service_sync.py | 0 ...ces_service_list_account_services_async.py | 0 ...ices_service_list_account_services_sync.py | 0 ...s_service_propose_account_service_async.py | 0 ...es_service_propose_account_service_sync.py | 0 ...es_service_reject_account_service_async.py | 0 ...ces_service_reject_account_service_sync.py | 0 ...vice_create_and_configure_account_async.py | 0 ...rvice_create_and_configure_account_sync.py | 0 ...d_accounts_service_delete_account_async.py | 0 ...ed_accounts_service_delete_account_sync.py | 0 ...ated_accounts_service_get_account_async.py | 0 ...rated_accounts_service_get_account_sync.py | 0 ...ed_accounts_service_list_accounts_async.py | 0 ...ted_accounts_service_list_accounts_sync.py | 0 ...ccounts_service_list_sub_accounts_async.py | 0 ...accounts_service_list_sub_accounts_sync.py | 0 ...d_accounts_service_update_account_async.py | 0 ...ed_accounts_service_update_account_sync.py | 0 ...ngs_service_get_autofeed_settings_async.py | 0 ...ings_service_get_autofeed_settings_sync.py | 0 ..._service_update_autofeed_settings_async.py | 0 ...s_service_update_autofeed_settings_sync.py | 0 ...ervice_get_automatic_improvements_async.py | 0 ...service_get_automatic_improvements_sync.py | 0 ...ice_update_automatic_improvements_async.py | 0 ...vice_update_automatic_improvements_sync.py | 0 ...ity_service_get_business_identity_async.py | 0 ...tity_service_get_business_identity_sync.py | 0 ..._service_update_business_identity_async.py | 0 ...y_service_update_business_identity_sync.py | 0 ...ss_info_service_get_business_info_async.py | 0 ...ess_info_service_get_business_info_sync.py | 0 ...info_service_update_business_info_async.py | 0 ..._info_service_update_business_info_sync.py | 0 ..._service_create_checkout_settings_async.py | 0 ...s_service_create_checkout_settings_sync.py | 0 ..._service_delete_checkout_settings_async.py | 0 ...s_service_delete_checkout_settings_sync.py | 0 ...ngs_service_get_checkout_settings_async.py | 0 ...ings_service_get_checkout_settings_sync.py | 0 ..._service_update_checkout_settings_async.py | 0 ...s_service_update_checkout_settings_sync.py | 0 ...ervice_get_developer_registration_async.py | 0 ...service_get_developer_registration_sync.py | 0 ...registration_service_register_gcp_async.py | 0 ..._registration_service_register_gcp_sync.py | 0 ...gistration_service_unregister_gcp_async.py | 0 ...egistration_service_unregister_gcp_sync.py | 0 ...ces_service_get_email_preferences_async.py | 0 ...nces_service_get_email_preferences_sync.py | 0 ..._service_update_email_preferences_async.py | 0 ...s_service_update_email_preferences_sync.py | 0 ...accounts_service_link_gbp_account_async.py | 0 ..._accounts_service_link_gbp_account_sync.py | 0 ...ccounts_service_list_gbp_accounts_async.py | 0 ...accounts_service_list_gbp_accounts_sync.py | 0 ...d_homepage_service_claim_homepage_async.py | 0 ...ed_homepage_service_claim_homepage_sync.py | 0 ...ted_homepage_service_get_homepage_async.py | 0 ...ated_homepage_service_get_homepage_sync.py | 0 ...homepage_service_unclaim_homepage_async.py | 0 ..._homepage_service_unclaim_homepage_sync.py | 0 ..._homepage_service_update_homepage_async.py | 0 ...d_homepage_service_update_homepage_sync.py | 0 ...viders_service_find_lfp_providers_async.py | 0 ...oviders_service_find_lfp_providers_sync.py | 0 ...oviders_service_link_lfp_provider_async.py | 0 ...roviders_service_link_lfp_provider_sync.py | 0 ...ervice_create_omnichannel_setting_async.py | 0 ...service_create_omnichannel_setting_sync.py | 0 ...s_service_get_omnichannel_setting_async.py | 0 ...gs_service_get_omnichannel_setting_sync.py | 0 ...service_list_omnichannel_settings_async.py | 0 ..._service_list_omnichannel_settings_sync.py | 0 ...ce_request_inventory_verification_async.py | 0 ...ice_request_inventory_verification_sync.py | 0 ...ervice_update_omnichannel_setting_async.py | 0 ...service_update_omnichannel_setting_sync.py | 0 ...rvice_create_online_return_policy_async.py | 0 ...ervice_create_online_return_policy_sync.py | 0 ...rvice_delete_online_return_policy_async.py | 0 ...ervice_delete_online_return_policy_sync.py | 0 ..._service_get_online_return_policy_async.py | 0 ...y_service_get_online_return_policy_sync.py | 0 ...rvice_list_online_return_policies_async.py | 0 ...ervice_list_online_return_policies_sync.py | 0 ..._programs_service_disable_program_async.py | 0 ...d_programs_service_disable_program_sync.py | 0 ...d_programs_service_enable_program_async.py | 0 ...ed_programs_service_enable_program_sync.py | 0 ...ated_programs_service_get_program_async.py | 0 ...rated_programs_service_get_program_sync.py | 0 ...ed_programs_service_list_programs_async.py | 0 ...ted_programs_service_list_programs_sync.py | 0 ...ted_regions_service_create_region_async.py | 0 ...ated_regions_service_create_region_sync.py | 0 ...ted_regions_service_delete_region_async.py | 0 ...ated_regions_service_delete_region_sync.py | 0 ...erated_regions_service_get_region_async.py | 0 ...nerated_regions_service_get_region_sync.py | 0 ...ated_regions_service_list_regions_async.py | 0 ...rated_regions_service_list_regions_sync.py | 0 ...ted_regions_service_update_region_async.py | 0 ...ated_regions_service_update_region_sync.py | 0 ...ngs_service_get_shipping_settings_async.py | 0 ...ings_service_get_shipping_settings_sync.py | 0 ..._service_insert_shipping_settings_async.py | 0 ...s_service_insert_shipping_settings_sync.py | 0 ..._terms_of_service_agreement_state_async.py | 0 ...t_terms_of_service_agreement_state_sync.py | 0 ..._terms_of_service_agreement_state_async.py | 0 ...n_terms_of_service_agreement_state_sync.py | 0 ...e_service_accept_terms_of_service_async.py | 0 ...ce_service_accept_terms_of_service_sync.py | 0 ...vice_service_get_terms_of_service_async.py | 0 ...rvice_service_get_terms_of_service_sync.py | 0 ..._retrieve_latest_terms_of_service_async.py | 0 ...e_retrieve_latest_terms_of_service_sync.py | 0 ...enerated_user_service_create_user_async.py | 0 ...generated_user_service_create_user_sync.py | 0 ...enerated_user_service_delete_user_async.py | 0 ...generated_user_service_delete_user_sync.py | 0 ...1_generated_user_service_get_user_async.py | 0 ...v1_generated_user_service_get_user_sync.py | 0 ...generated_user_service_list_users_async.py | 0 ..._generated_user_service_list_users_sync.py | 0 ...enerated_user_service_update_user_async.py | 0 ...generated_user_service_update_user_sync.py | 0 ..._google.shopping.merchant.accounts.v1.json | 0 ...gle.shopping.merchant.accounts.v1beta.json | 2 +- .../fixup_merchant_accounts_v1_keywords.py | 0 .../gapic/merchant_accounts_v1}/__init__.py | 0 .../test_account_issue_service.py | 1615 ++- .../test_account_relationships_service.py | 2479 ++-- .../test_account_services_service.py | 3036 +++-- .../test_accounts_service.py | 3038 +++-- .../test_autofeed_settings_service.py | 1886 ++- .../test_automatic_improvements_service.py | 1954 ++- .../test_business_identity_service.py | 1900 ++- .../test_business_info_service.py | 1926 ++- .../test_checkout_settings_service.py | 2847 +++-- .../test_developer_registration_service.py | 2058 ++-- .../test_email_preferences_service.py | 1904 ++- .../test_gbp_accounts_service.py | 1893 ++- .../test_homepage_service.py | 2307 ++-- .../test_lfp_providers_service.py | 1941 ++- .../test_omnichannel_settings_service.py | 3220 +++-- .../test_online_return_policy_service.py | 2993 +++-- .../test_programs_service.py | 2457 ++-- .../test_regions_service.py | 2722 ++-- .../test_shipping_settings_service.py | 1976 ++- ...erms_of_service_agreement_state_service.py | 2227 +++- .../test_terms_of_service_service.py | 2204 ++-- .../merchant_accounts_v1/test_user_service.py | 2636 ++-- 922 files changed, 59402 insertions(+), 213619 deletions(-) delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/LICENSE delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/LICENSE delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/setup.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py delete mode 100644 owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/account_issue_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/account_relationships_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/account_services_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/accounts_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/autofeed_settings_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/automatic_improvements_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/business_identity_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/business_info_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/checkout_settings_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/developer_registration_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/email_preferences_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/gbp_accounts_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/homepage_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/lfp_providers_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/omnichannel_settings_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/online_return_policy_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/programs_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/regions_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/services_.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/shipping_settings_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/terms_of_service_service.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/types_.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/docs/merchant_accounts_v1/user_service.rst (100%) create mode 100644 packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/__init__.py rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/gapic_metadata.json (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/gapic_version.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/py.typed (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/__init__.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py (69%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py (86%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py (85%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py (75%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py (70%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py (63%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/client.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py (70%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/accounts_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/client.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/accounts_service/transports/__init__.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py (68%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/autofeed_settings_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/autofeed_settings_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py (72%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py (64%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py (76%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py (76%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py (62%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py (62%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py (72%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py (64%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/business_info_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/business_info_service/transports/__init__.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py (68%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py (73%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/checkout_settings_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py (69%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/email_preferences_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py (72%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py (64%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/gbp_accounts_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/gbp_accounts_service/transports/__init__.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py (68%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py (73%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/client.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py (73%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/lfp_providers_service/transports/__init__.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py (72%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py (64%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py (63%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py (62%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py (57%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py (77%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py (64%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py (61%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/programs_service/__init__.py (91%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/client.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/programs_service/transports/__init__.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py (74%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py (92%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/client.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta => packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1}/services/regions_service/transports/__init__.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py (72%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py (84%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py (72%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py (87%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py (75%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py (74%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py (55%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py (81%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py (55%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py (60%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py (78%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py (59%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py (61%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/__init__.py (92%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/async_client.py (83%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/client.py (80%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/pagers.py (79%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py (68%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py (82%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py (71%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py (58%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/__init__.py (53%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/accessright.py (95%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/accountissue.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/accountrelationships.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/accounts.py (95%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/accountservices.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/autofeedsettings.py (92%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/automaticimprovements.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/businessidentity.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/businessinfo.py (90%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/checkoutsettings.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/customerservice.py (96%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/developerregistration.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/emailpreferences.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/gbpaccounts.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/homepage.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/lfpproviders.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py (89%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/online_return_policy.py (95%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/programs.py (96%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/regions.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/shippingsettings.py (92%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/termsofservice.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/termsofservicekind.py (93%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/google/shopping/merchant_accounts_v1/types/user.py (94%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/scripts/fixup_merchant_accounts_v1_keywords.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services => packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1}/__init__.py (100%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py (69%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py (70%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py (65%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py (68%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py (69%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py (69%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py (66%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py (70%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py (71%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py (63%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py (62%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py (67%) rename {owl-bot-staging/google-shopping-merchant-accounts/v1 => packages/google-shopping-merchant-accounts}/tests/unit/gapic/merchant_accounts_v1/test_user_service.py (72%) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc b/owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc deleted file mode 100644 index 8338bbe3403b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_accounts/__init__.py - google/shopping/merchant_accounts/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-accounts/v1/.flake8 b/owl-bot-staging/google-shopping-merchant-accounts/v1/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/LICENSE b/owl-bot-staging/google-shopping-merchant-accounts/v1/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-accounts/v1/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/README.rst deleted file mode 100644 index 419480c445c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Shopping Merchant Accounts 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 Accounts 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-accounts/v1/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/docs/conf.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/conf.py deleted file mode 100644 index 11bd96e58d11..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts 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-accounts" -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-accounts", - "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-accounts-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-accounts.tex", - u"google-shopping-merchant-accounts 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-accounts", - "google-shopping-merchant-accounts 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-accounts", - "google-shopping-merchant-accounts Documentation", - author, - "google-shopping-merchant-accounts", - "google-shopping-merchant-accounts 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-accounts/v1/docs/index.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/index.rst deleted file mode 100644 index 3155169d729f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_accounts_v1/services_ - merchant_accounts_v1/types_ diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/google/shopping/merchant_accounts/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/__init__.py deleted file mode 100644 index ba62edbc93f9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/__init__.py +++ /dev/null @@ -1,409 +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_accounts import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_accounts_v1.services.account_issue_service.client import AccountIssueServiceClient -from google.shopping.merchant_accounts_v1.services.account_issue_service.async_client import AccountIssueServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.account_relationships_service.client import AccountRelationshipsServiceClient -from google.shopping.merchant_accounts_v1.services.account_relationships_service.async_client import AccountRelationshipsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.account_services_service.client import AccountServicesServiceClient -from google.shopping.merchant_accounts_v1.services.account_services_service.async_client import AccountServicesServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.accounts_service.client import AccountsServiceClient -from google.shopping.merchant_accounts_v1.services.accounts_service.async_client import AccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.autofeed_settings_service.client import AutofeedSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.autofeed_settings_service.async_client import AutofeedSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.automatic_improvements_service.client import AutomaticImprovementsServiceClient -from google.shopping.merchant_accounts_v1.services.automatic_improvements_service.async_client import AutomaticImprovementsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.business_identity_service.client import BusinessIdentityServiceClient -from google.shopping.merchant_accounts_v1.services.business_identity_service.async_client import BusinessIdentityServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.business_info_service.client import BusinessInfoServiceClient -from google.shopping.merchant_accounts_v1.services.business_info_service.async_client import BusinessInfoServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.checkout_settings_service.client import CheckoutSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.checkout_settings_service.async_client import CheckoutSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.developer_registration_service.client import DeveloperRegistrationServiceClient -from google.shopping.merchant_accounts_v1.services.developer_registration_service.async_client import DeveloperRegistrationServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.email_preferences_service.client import EmailPreferencesServiceClient -from google.shopping.merchant_accounts_v1.services.email_preferences_service.async_client import EmailPreferencesServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.gbp_accounts_service.client import GbpAccountsServiceClient -from google.shopping.merchant_accounts_v1.services.gbp_accounts_service.async_client import GbpAccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.homepage_service.client import HomepageServiceClient -from google.shopping.merchant_accounts_v1.services.homepage_service.async_client import HomepageServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.lfp_providers_service.client import LfpProvidersServiceClient -from google.shopping.merchant_accounts_v1.services.lfp_providers_service.async_client import LfpProvidersServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.client import OmnichannelSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.async_client import OmnichannelSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.online_return_policy_service.client import OnlineReturnPolicyServiceClient -from google.shopping.merchant_accounts_v1.services.online_return_policy_service.async_client import OnlineReturnPolicyServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.programs_service.client import ProgramsServiceClient -from google.shopping.merchant_accounts_v1.services.programs_service.async_client import ProgramsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.regions_service.client import RegionsServiceClient -from google.shopping.merchant_accounts_v1.services.regions_service.async_client import RegionsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.shipping_settings_service.client import ShippingSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.shipping_settings_service.async_client import ShippingSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.client import TermsOfServiceAgreementStateServiceClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.async_client import TermsOfServiceAgreementStateServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_service.client import TermsOfServiceServiceClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_service.async_client import TermsOfServiceServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.user_service.client import UserServiceClient -from google.shopping.merchant_accounts_v1.services.user_service.async_client import UserServiceAsyncClient - -from google.shopping.merchant_accounts_v1.types.accessright import AccessRight -from google.shopping.merchant_accounts_v1.types.accountissue import AccountIssue -from google.shopping.merchant_accounts_v1.types.accountissue import ListAccountIssuesRequest -from google.shopping.merchant_accounts_v1.types.accountissue import ListAccountIssuesResponse -from google.shopping.merchant_accounts_v1.types.accountrelationships import AccountRelationship -from google.shopping.merchant_accounts_v1.types.accountrelationships import GetAccountRelationshipRequest -from google.shopping.merchant_accounts_v1.types.accountrelationships import ListAccountRelationshipsRequest -from google.shopping.merchant_accounts_v1.types.accountrelationships import ListAccountRelationshipsResponse -from google.shopping.merchant_accounts_v1.types.accountrelationships import UpdateAccountRelationshipRequest -from google.shopping.merchant_accounts_v1.types.accounts import Account -from google.shopping.merchant_accounts_v1.types.accounts import CreateAndConfigureAccountRequest -from google.shopping.merchant_accounts_v1.types.accounts import DeleteAccountRequest -from google.shopping.merchant_accounts_v1.types.accounts import GetAccountRequest -from google.shopping.merchant_accounts_v1.types.accounts import ListAccountsRequest -from google.shopping.merchant_accounts_v1.types.accounts import ListAccountsResponse -from google.shopping.merchant_accounts_v1.types.accounts import ListSubAccountsRequest -from google.shopping.merchant_accounts_v1.types.accounts import ListSubAccountsResponse -from google.shopping.merchant_accounts_v1.types.accounts import UpdateAccountRequest -from google.shopping.merchant_accounts_v1.types.accountservices import AccountAggregation -from google.shopping.merchant_accounts_v1.types.accountservices import AccountManagement -from google.shopping.merchant_accounts_v1.types.accountservices import AccountService -from google.shopping.merchant_accounts_v1.types.accountservices import ApproveAccountServiceRequest -from google.shopping.merchant_accounts_v1.types.accountservices import CampaignsManagement -from google.shopping.merchant_accounts_v1.types.accountservices import GetAccountServiceRequest -from google.shopping.merchant_accounts_v1.types.accountservices import Handshake -from google.shopping.merchant_accounts_v1.types.accountservices import ListAccountServicesRequest -from google.shopping.merchant_accounts_v1.types.accountservices import ListAccountServicesResponse -from google.shopping.merchant_accounts_v1.types.accountservices import LocalListingManagement -from google.shopping.merchant_accounts_v1.types.accountservices import ProductsManagement -from google.shopping.merchant_accounts_v1.types.accountservices import ProposeAccountServiceRequest -from google.shopping.merchant_accounts_v1.types.accountservices import RejectAccountServiceRequest -from google.shopping.merchant_accounts_v1.types.autofeedsettings import AutofeedSettings -from google.shopping.merchant_accounts_v1.types.autofeedsettings import GetAutofeedSettingsRequest -from google.shopping.merchant_accounts_v1.types.autofeedsettings import UpdateAutofeedSettingsRequest -from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticImageImprovements -from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticImprovements -from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticItemUpdates -from google.shopping.merchant_accounts_v1.types.automaticimprovements import AutomaticShippingImprovements -from google.shopping.merchant_accounts_v1.types.automaticimprovements import GetAutomaticImprovementsRequest -from google.shopping.merchant_accounts_v1.types.automaticimprovements import UpdateAutomaticImprovementsRequest -from google.shopping.merchant_accounts_v1.types.businessidentity import BusinessIdentity -from google.shopping.merchant_accounts_v1.types.businessidentity import GetBusinessIdentityRequest -from google.shopping.merchant_accounts_v1.types.businessidentity import UpdateBusinessIdentityRequest -from google.shopping.merchant_accounts_v1.types.businessinfo import BusinessInfo -from google.shopping.merchant_accounts_v1.types.businessinfo import GetBusinessInfoRequest -from google.shopping.merchant_accounts_v1.types.businessinfo import UpdateBusinessInfoRequest -from google.shopping.merchant_accounts_v1.types.checkoutsettings import CheckoutSettings -from google.shopping.merchant_accounts_v1.types.checkoutsettings import CreateCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1.types.checkoutsettings import DeleteCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1.types.checkoutsettings import GetCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1.types.checkoutsettings import UpdateCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1.types.checkoutsettings import UriSettings -from google.shopping.merchant_accounts_v1.types.customerservice import CustomerService -from google.shopping.merchant_accounts_v1.types.developerregistration import DeveloperRegistration -from google.shopping.merchant_accounts_v1.types.developerregistration import GetDeveloperRegistrationRequest -from google.shopping.merchant_accounts_v1.types.developerregistration import RegisterGcpRequest -from google.shopping.merchant_accounts_v1.types.developerregistration import UnregisterGcpRequest -from google.shopping.merchant_accounts_v1.types.emailpreferences import EmailPreferences -from google.shopping.merchant_accounts_v1.types.emailpreferences import GetEmailPreferencesRequest -from google.shopping.merchant_accounts_v1.types.emailpreferences import UpdateEmailPreferencesRequest -from google.shopping.merchant_accounts_v1.types.gbpaccounts import GbpAccount -from google.shopping.merchant_accounts_v1.types.gbpaccounts import LinkGbpAccountRequest -from google.shopping.merchant_accounts_v1.types.gbpaccounts import LinkGbpAccountResponse -from google.shopping.merchant_accounts_v1.types.gbpaccounts import ListGbpAccountsRequest -from google.shopping.merchant_accounts_v1.types.gbpaccounts import ListGbpAccountsResponse -from google.shopping.merchant_accounts_v1.types.homepage import ClaimHomepageRequest -from google.shopping.merchant_accounts_v1.types.homepage import GetHomepageRequest -from google.shopping.merchant_accounts_v1.types.homepage import Homepage -from google.shopping.merchant_accounts_v1.types.homepage import UnclaimHomepageRequest -from google.shopping.merchant_accounts_v1.types.homepage import UpdateHomepageRequest -from google.shopping.merchant_accounts_v1.types.lfpproviders import FindLfpProvidersRequest -from google.shopping.merchant_accounts_v1.types.lfpproviders import FindLfpProvidersResponse -from google.shopping.merchant_accounts_v1.types.lfpproviders import LfpProvider -from google.shopping.merchant_accounts_v1.types.lfpproviders import LinkLfpProviderRequest -from google.shopping.merchant_accounts_v1.types.lfpproviders import LinkLfpProviderResponse -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import About -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import CreateOmnichannelSettingRequest -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import GetOmnichannelSettingRequest -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import InStock -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import InventoryVerification -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import LfpLink -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import ListOmnichannelSettingsRequest -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import ListOmnichannelSettingsResponse -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import OmnichannelSetting -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import OnDisplayToOrder -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import Pickup -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import RequestInventoryVerificationRequest -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import RequestInventoryVerificationResponse -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import ReviewState -from google.shopping.merchant_accounts_v1.types.omnichannelsettings import UpdateOmnichannelSettingRequest -from google.shopping.merchant_accounts_v1.types.online_return_policy import CreateOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1.types.online_return_policy import DeleteOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1.types.online_return_policy import GetOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1.types.online_return_policy import ListOnlineReturnPoliciesRequest -from google.shopping.merchant_accounts_v1.types.online_return_policy import ListOnlineReturnPoliciesResponse -from google.shopping.merchant_accounts_v1.types.online_return_policy import OnlineReturnPolicy -from google.shopping.merchant_accounts_v1.types.phoneverificationstate import PhoneVerificationState -from google.shopping.merchant_accounts_v1.types.programs import DisableProgramRequest -from google.shopping.merchant_accounts_v1.types.programs import EnableProgramRequest -from google.shopping.merchant_accounts_v1.types.programs import GetProgramRequest -from google.shopping.merchant_accounts_v1.types.programs import ListProgramsRequest -from google.shopping.merchant_accounts_v1.types.programs import ListProgramsResponse -from google.shopping.merchant_accounts_v1.types.programs import Program -from google.shopping.merchant_accounts_v1.types.regions import CreateRegionRequest -from google.shopping.merchant_accounts_v1.types.regions import DeleteRegionRequest -from google.shopping.merchant_accounts_v1.types.regions import GetRegionRequest -from google.shopping.merchant_accounts_v1.types.regions import ListRegionsRequest -from google.shopping.merchant_accounts_v1.types.regions import ListRegionsResponse -from google.shopping.merchant_accounts_v1.types.regions import Region -from google.shopping.merchant_accounts_v1.types.regions import UpdateRegionRequest -from google.shopping.merchant_accounts_v1.types.shippingsettings import Address -from google.shopping.merchant_accounts_v1.types.shippingsettings import BusinessDayConfig -from google.shopping.merchant_accounts_v1.types.shippingsettings import CarrierRate -from google.shopping.merchant_accounts_v1.types.shippingsettings import CutoffTime -from google.shopping.merchant_accounts_v1.types.shippingsettings import DeliveryTime -from google.shopping.merchant_accounts_v1.types.shippingsettings import Distance -from google.shopping.merchant_accounts_v1.types.shippingsettings import GetShippingSettingsRequest -from google.shopping.merchant_accounts_v1.types.shippingsettings import Headers -from google.shopping.merchant_accounts_v1.types.shippingsettings import InsertShippingSettingsRequest -from google.shopping.merchant_accounts_v1.types.shippingsettings import LocationIdSet -from google.shopping.merchant_accounts_v1.types.shippingsettings import MinimumOrderValueTable -from google.shopping.merchant_accounts_v1.types.shippingsettings import RateGroup -from google.shopping.merchant_accounts_v1.types.shippingsettings import Row -from google.shopping.merchant_accounts_v1.types.shippingsettings import Service -from google.shopping.merchant_accounts_v1.types.shippingsettings import ShippingSettings -from google.shopping.merchant_accounts_v1.types.shippingsettings import Table -from google.shopping.merchant_accounts_v1.types.shippingsettings import TransitTable -from google.shopping.merchant_accounts_v1.types.shippingsettings import Value -from google.shopping.merchant_accounts_v1.types.shippingsettings import Warehouse -from google.shopping.merchant_accounts_v1.types.shippingsettings import WarehouseBasedDeliveryTime -from google.shopping.merchant_accounts_v1.types.shippingsettings import WarehouseCutoffTime -from google.shopping.merchant_accounts_v1.types.termsofservice import AcceptTermsOfServiceRequest -from google.shopping.merchant_accounts_v1.types.termsofservice import AcceptTermsOfServiceResponse -from google.shopping.merchant_accounts_v1.types.termsofservice import GetTermsOfServiceRequest -from google.shopping.merchant_accounts_v1.types.termsofservice import RetrieveLatestTermsOfServiceRequest -from google.shopping.merchant_accounts_v1.types.termsofservice import TermsOfService -from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import Accepted -from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest -from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import Required -from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest -from google.shopping.merchant_accounts_v1.types.termsofserviceagreementstate import TermsOfServiceAgreementState -from google.shopping.merchant_accounts_v1.types.termsofservicekind import TermsOfServiceKind -from google.shopping.merchant_accounts_v1.types.user import CreateUserRequest -from google.shopping.merchant_accounts_v1.types.user import DeleteUserRequest -from google.shopping.merchant_accounts_v1.types.user import GetUserRequest -from google.shopping.merchant_accounts_v1.types.user import ListUsersRequest -from google.shopping.merchant_accounts_v1.types.user import ListUsersResponse -from google.shopping.merchant_accounts_v1.types.user import UpdateUserRequest -from google.shopping.merchant_accounts_v1.types.user import User - -__all__ = ('AccountIssueServiceClient', - 'AccountIssueServiceAsyncClient', - 'AccountRelationshipsServiceClient', - 'AccountRelationshipsServiceAsyncClient', - 'AccountServicesServiceClient', - 'AccountServicesServiceAsyncClient', - 'AccountsServiceClient', - 'AccountsServiceAsyncClient', - 'AutofeedSettingsServiceClient', - 'AutofeedSettingsServiceAsyncClient', - 'AutomaticImprovementsServiceClient', - 'AutomaticImprovementsServiceAsyncClient', - 'BusinessIdentityServiceClient', - 'BusinessIdentityServiceAsyncClient', - 'BusinessInfoServiceClient', - 'BusinessInfoServiceAsyncClient', - 'CheckoutSettingsServiceClient', - 'CheckoutSettingsServiceAsyncClient', - 'DeveloperRegistrationServiceClient', - 'DeveloperRegistrationServiceAsyncClient', - 'EmailPreferencesServiceClient', - 'EmailPreferencesServiceAsyncClient', - 'GbpAccountsServiceClient', - 'GbpAccountsServiceAsyncClient', - 'HomepageServiceClient', - 'HomepageServiceAsyncClient', - 'LfpProvidersServiceClient', - 'LfpProvidersServiceAsyncClient', - 'OmnichannelSettingsServiceClient', - 'OmnichannelSettingsServiceAsyncClient', - 'OnlineReturnPolicyServiceClient', - 'OnlineReturnPolicyServiceAsyncClient', - 'ProgramsServiceClient', - 'ProgramsServiceAsyncClient', - 'RegionsServiceClient', - 'RegionsServiceAsyncClient', - 'ShippingSettingsServiceClient', - 'ShippingSettingsServiceAsyncClient', - 'TermsOfServiceAgreementStateServiceClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', - 'TermsOfServiceServiceClient', - 'TermsOfServiceServiceAsyncClient', - 'UserServiceClient', - 'UserServiceAsyncClient', - 'AccessRight', - 'AccountIssue', - 'ListAccountIssuesRequest', - 'ListAccountIssuesResponse', - 'AccountRelationship', - 'GetAccountRelationshipRequest', - 'ListAccountRelationshipsRequest', - 'ListAccountRelationshipsResponse', - 'UpdateAccountRelationshipRequest', - 'Account', - 'CreateAndConfigureAccountRequest', - 'DeleteAccountRequest', - 'GetAccountRequest', - 'ListAccountsRequest', - 'ListAccountsResponse', - 'ListSubAccountsRequest', - 'ListSubAccountsResponse', - 'UpdateAccountRequest', - 'AccountAggregation', - 'AccountManagement', - 'AccountService', - 'ApproveAccountServiceRequest', - 'CampaignsManagement', - 'GetAccountServiceRequest', - 'Handshake', - 'ListAccountServicesRequest', - 'ListAccountServicesResponse', - 'LocalListingManagement', - 'ProductsManagement', - 'ProposeAccountServiceRequest', - 'RejectAccountServiceRequest', - 'AutofeedSettings', - 'GetAutofeedSettingsRequest', - 'UpdateAutofeedSettingsRequest', - 'AutomaticImageImprovements', - 'AutomaticImprovements', - 'AutomaticItemUpdates', - 'AutomaticShippingImprovements', - 'GetAutomaticImprovementsRequest', - 'UpdateAutomaticImprovementsRequest', - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - 'CheckoutSettings', - 'CreateCheckoutSettingsRequest', - 'DeleteCheckoutSettingsRequest', - 'GetCheckoutSettingsRequest', - 'UpdateCheckoutSettingsRequest', - 'UriSettings', - 'CustomerService', - 'DeveloperRegistration', - 'GetDeveloperRegistrationRequest', - 'RegisterGcpRequest', - 'UnregisterGcpRequest', - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - 'GbpAccount', - 'LinkGbpAccountRequest', - 'LinkGbpAccountResponse', - 'ListGbpAccountsRequest', - 'ListGbpAccountsResponse', - 'ClaimHomepageRequest', - 'GetHomepageRequest', - 'Homepage', - 'UnclaimHomepageRequest', - 'UpdateHomepageRequest', - 'FindLfpProvidersRequest', - 'FindLfpProvidersResponse', - 'LfpProvider', - 'LinkLfpProviderRequest', - 'LinkLfpProviderResponse', - 'About', - 'CreateOmnichannelSettingRequest', - 'GetOmnichannelSettingRequest', - 'InStock', - 'InventoryVerification', - 'LfpLink', - 'ListOmnichannelSettingsRequest', - 'ListOmnichannelSettingsResponse', - 'OmnichannelSetting', - 'OnDisplayToOrder', - 'Pickup', - 'RequestInventoryVerificationRequest', - 'RequestInventoryVerificationResponse', - 'ReviewState', - 'UpdateOmnichannelSettingRequest', - 'CreateOnlineReturnPolicyRequest', - 'DeleteOnlineReturnPolicyRequest', - 'GetOnlineReturnPolicyRequest', - 'ListOnlineReturnPoliciesRequest', - 'ListOnlineReturnPoliciesResponse', - 'OnlineReturnPolicy', - 'PhoneVerificationState', - 'DisableProgramRequest', - 'EnableProgramRequest', - 'GetProgramRequest', - 'ListProgramsRequest', - 'ListProgramsResponse', - 'Program', - 'CreateRegionRequest', - 'DeleteRegionRequest', - 'GetRegionRequest', - 'ListRegionsRequest', - 'ListRegionsResponse', - 'Region', - 'UpdateRegionRequest', - 'Address', - 'BusinessDayConfig', - 'CarrierRate', - 'CutoffTime', - 'DeliveryTime', - 'Distance', - 'GetShippingSettingsRequest', - 'Headers', - 'InsertShippingSettingsRequest', - 'LocationIdSet', - 'MinimumOrderValueTable', - 'RateGroup', - 'Row', - 'Service', - 'ShippingSettings', - 'Table', - 'TransitTable', - 'Value', - 'Warehouse', - 'WarehouseBasedDeliveryTime', - 'WarehouseCutoffTime', - 'AcceptTermsOfServiceRequest', - 'AcceptTermsOfServiceResponse', - 'GetTermsOfServiceRequest', - 'RetrieveLatestTermsOfServiceRequest', - 'TermsOfService', - 'Accepted', - 'GetTermsOfServiceAgreementStateRequest', - 'Required', - 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', - 'TermsOfServiceAgreementState', - 'TermsOfServiceKind', - 'CreateUserRequest', - 'DeleteUserRequest', - 'GetUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - 'UpdateUserRequest', - 'User', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py deleted file mode 100644 index a20f2045d3f0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/__init__.py +++ /dev/null @@ -1,410 +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_accounts_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.account_issue_service import AccountIssueServiceClient -from .services.account_issue_service import AccountIssueServiceAsyncClient -from .services.account_relationships_service import AccountRelationshipsServiceClient -from .services.account_relationships_service import AccountRelationshipsServiceAsyncClient -from .services.account_services_service import AccountServicesServiceClient -from .services.account_services_service import AccountServicesServiceAsyncClient -from .services.accounts_service import AccountsServiceClient -from .services.accounts_service import AccountsServiceAsyncClient -from .services.autofeed_settings_service import AutofeedSettingsServiceClient -from .services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient -from .services.automatic_improvements_service import AutomaticImprovementsServiceClient -from .services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient -from .services.business_identity_service import BusinessIdentityServiceClient -from .services.business_identity_service import BusinessIdentityServiceAsyncClient -from .services.business_info_service import BusinessInfoServiceClient -from .services.business_info_service import BusinessInfoServiceAsyncClient -from .services.checkout_settings_service import CheckoutSettingsServiceClient -from .services.checkout_settings_service import CheckoutSettingsServiceAsyncClient -from .services.developer_registration_service import DeveloperRegistrationServiceClient -from .services.developer_registration_service import DeveloperRegistrationServiceAsyncClient -from .services.email_preferences_service import EmailPreferencesServiceClient -from .services.email_preferences_service import EmailPreferencesServiceAsyncClient -from .services.gbp_accounts_service import GbpAccountsServiceClient -from .services.gbp_accounts_service import GbpAccountsServiceAsyncClient -from .services.homepage_service import HomepageServiceClient -from .services.homepage_service import HomepageServiceAsyncClient -from .services.lfp_providers_service import LfpProvidersServiceClient -from .services.lfp_providers_service import LfpProvidersServiceAsyncClient -from .services.omnichannel_settings_service import OmnichannelSettingsServiceClient -from .services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient -from .services.online_return_policy_service import OnlineReturnPolicyServiceClient -from .services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient -from .services.programs_service import ProgramsServiceClient -from .services.programs_service import ProgramsServiceAsyncClient -from .services.regions_service import RegionsServiceClient -from .services.regions_service import RegionsServiceAsyncClient -from .services.shipping_settings_service import ShippingSettingsServiceClient -from .services.shipping_settings_service import ShippingSettingsServiceAsyncClient -from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient -from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient -from .services.terms_of_service_service import TermsOfServiceServiceClient -from .services.terms_of_service_service import TermsOfServiceServiceAsyncClient -from .services.user_service import UserServiceClient -from .services.user_service import UserServiceAsyncClient - -from .types.accessright import AccessRight -from .types.accountissue import AccountIssue -from .types.accountissue import ListAccountIssuesRequest -from .types.accountissue import ListAccountIssuesResponse -from .types.accountrelationships import AccountRelationship -from .types.accountrelationships import GetAccountRelationshipRequest -from .types.accountrelationships import ListAccountRelationshipsRequest -from .types.accountrelationships import ListAccountRelationshipsResponse -from .types.accountrelationships import UpdateAccountRelationshipRequest -from .types.accounts import Account -from .types.accounts import CreateAndConfigureAccountRequest -from .types.accounts import DeleteAccountRequest -from .types.accounts import GetAccountRequest -from .types.accounts import ListAccountsRequest -from .types.accounts import ListAccountsResponse -from .types.accounts import ListSubAccountsRequest -from .types.accounts import ListSubAccountsResponse -from .types.accounts import UpdateAccountRequest -from .types.accountservices import AccountAggregation -from .types.accountservices import AccountManagement -from .types.accountservices import AccountService -from .types.accountservices import ApproveAccountServiceRequest -from .types.accountservices import CampaignsManagement -from .types.accountservices import GetAccountServiceRequest -from .types.accountservices import Handshake -from .types.accountservices import ListAccountServicesRequest -from .types.accountservices import ListAccountServicesResponse -from .types.accountservices import LocalListingManagement -from .types.accountservices import ProductsManagement -from .types.accountservices import ProposeAccountServiceRequest -from .types.accountservices import RejectAccountServiceRequest -from .types.autofeedsettings import AutofeedSettings -from .types.autofeedsettings import GetAutofeedSettingsRequest -from .types.autofeedsettings import UpdateAutofeedSettingsRequest -from .types.automaticimprovements import AutomaticImageImprovements -from .types.automaticimprovements import AutomaticImprovements -from .types.automaticimprovements import AutomaticItemUpdates -from .types.automaticimprovements import AutomaticShippingImprovements -from .types.automaticimprovements import GetAutomaticImprovementsRequest -from .types.automaticimprovements import UpdateAutomaticImprovementsRequest -from .types.businessidentity import BusinessIdentity -from .types.businessidentity import GetBusinessIdentityRequest -from .types.businessidentity import UpdateBusinessIdentityRequest -from .types.businessinfo import BusinessInfo -from .types.businessinfo import GetBusinessInfoRequest -from .types.businessinfo import UpdateBusinessInfoRequest -from .types.checkoutsettings import CheckoutSettings -from .types.checkoutsettings import CreateCheckoutSettingsRequest -from .types.checkoutsettings import DeleteCheckoutSettingsRequest -from .types.checkoutsettings import GetCheckoutSettingsRequest -from .types.checkoutsettings import UpdateCheckoutSettingsRequest -from .types.checkoutsettings import UriSettings -from .types.customerservice import CustomerService -from .types.developerregistration import DeveloperRegistration -from .types.developerregistration import GetDeveloperRegistrationRequest -from .types.developerregistration import RegisterGcpRequest -from .types.developerregistration import UnregisterGcpRequest -from .types.emailpreferences import EmailPreferences -from .types.emailpreferences import GetEmailPreferencesRequest -from .types.emailpreferences import UpdateEmailPreferencesRequest -from .types.gbpaccounts import GbpAccount -from .types.gbpaccounts import LinkGbpAccountRequest -from .types.gbpaccounts import LinkGbpAccountResponse -from .types.gbpaccounts import ListGbpAccountsRequest -from .types.gbpaccounts import ListGbpAccountsResponse -from .types.homepage import ClaimHomepageRequest -from .types.homepage import GetHomepageRequest -from .types.homepage import Homepage -from .types.homepage import UnclaimHomepageRequest -from .types.homepage import UpdateHomepageRequest -from .types.lfpproviders import FindLfpProvidersRequest -from .types.lfpproviders import FindLfpProvidersResponse -from .types.lfpproviders import LfpProvider -from .types.lfpproviders import LinkLfpProviderRequest -from .types.lfpproviders import LinkLfpProviderResponse -from .types.omnichannelsettings import About -from .types.omnichannelsettings import CreateOmnichannelSettingRequest -from .types.omnichannelsettings import GetOmnichannelSettingRequest -from .types.omnichannelsettings import InStock -from .types.omnichannelsettings import InventoryVerification -from .types.omnichannelsettings import LfpLink -from .types.omnichannelsettings import ListOmnichannelSettingsRequest -from .types.omnichannelsettings import ListOmnichannelSettingsResponse -from .types.omnichannelsettings import OmnichannelSetting -from .types.omnichannelsettings import OnDisplayToOrder -from .types.omnichannelsettings import Pickup -from .types.omnichannelsettings import RequestInventoryVerificationRequest -from .types.omnichannelsettings import RequestInventoryVerificationResponse -from .types.omnichannelsettings import ReviewState -from .types.omnichannelsettings import UpdateOmnichannelSettingRequest -from .types.online_return_policy import CreateOnlineReturnPolicyRequest -from .types.online_return_policy import DeleteOnlineReturnPolicyRequest -from .types.online_return_policy import GetOnlineReturnPolicyRequest -from .types.online_return_policy import ListOnlineReturnPoliciesRequest -from .types.online_return_policy import ListOnlineReturnPoliciesResponse -from .types.online_return_policy import OnlineReturnPolicy -from .types.phoneverificationstate import PhoneVerificationState -from .types.programs import DisableProgramRequest -from .types.programs import EnableProgramRequest -from .types.programs import GetProgramRequest -from .types.programs import ListProgramsRequest -from .types.programs import ListProgramsResponse -from .types.programs import Program -from .types.regions import CreateRegionRequest -from .types.regions import DeleteRegionRequest -from .types.regions import GetRegionRequest -from .types.regions import ListRegionsRequest -from .types.regions import ListRegionsResponse -from .types.regions import Region -from .types.regions import UpdateRegionRequest -from .types.shippingsettings import Address -from .types.shippingsettings import BusinessDayConfig -from .types.shippingsettings import CarrierRate -from .types.shippingsettings import CutoffTime -from .types.shippingsettings import DeliveryTime -from .types.shippingsettings import Distance -from .types.shippingsettings import GetShippingSettingsRequest -from .types.shippingsettings import Headers -from .types.shippingsettings import InsertShippingSettingsRequest -from .types.shippingsettings import LocationIdSet -from .types.shippingsettings import MinimumOrderValueTable -from .types.shippingsettings import RateGroup -from .types.shippingsettings import Row -from .types.shippingsettings import Service -from .types.shippingsettings import ShippingSettings -from .types.shippingsettings import Table -from .types.shippingsettings import TransitTable -from .types.shippingsettings import Value -from .types.shippingsettings import Warehouse -from .types.shippingsettings import WarehouseBasedDeliveryTime -from .types.shippingsettings import WarehouseCutoffTime -from .types.termsofservice import AcceptTermsOfServiceRequest -from .types.termsofservice import AcceptTermsOfServiceResponse -from .types.termsofservice import GetTermsOfServiceRequest -from .types.termsofservice import RetrieveLatestTermsOfServiceRequest -from .types.termsofservice import TermsOfService -from .types.termsofserviceagreementstate import Accepted -from .types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest -from .types.termsofserviceagreementstate import Required -from .types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest -from .types.termsofserviceagreementstate import TermsOfServiceAgreementState -from .types.termsofservicekind import TermsOfServiceKind -from .types.user import CreateUserRequest -from .types.user import DeleteUserRequest -from .types.user import GetUserRequest -from .types.user import ListUsersRequest -from .types.user import ListUsersResponse -from .types.user import UpdateUserRequest -from .types.user import User - -__all__ = ( - 'AccountIssueServiceAsyncClient', - 'AccountRelationshipsServiceAsyncClient', - 'AccountServicesServiceAsyncClient', - 'AccountsServiceAsyncClient', - 'AutofeedSettingsServiceAsyncClient', - 'AutomaticImprovementsServiceAsyncClient', - 'BusinessIdentityServiceAsyncClient', - 'BusinessInfoServiceAsyncClient', - 'CheckoutSettingsServiceAsyncClient', - 'DeveloperRegistrationServiceAsyncClient', - 'EmailPreferencesServiceAsyncClient', - 'GbpAccountsServiceAsyncClient', - 'HomepageServiceAsyncClient', - 'LfpProvidersServiceAsyncClient', - 'OmnichannelSettingsServiceAsyncClient', - 'OnlineReturnPolicyServiceAsyncClient', - 'ProgramsServiceAsyncClient', - 'RegionsServiceAsyncClient', - 'ShippingSettingsServiceAsyncClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', - 'TermsOfServiceServiceAsyncClient', - 'UserServiceAsyncClient', -'About', -'AcceptTermsOfServiceRequest', -'AcceptTermsOfServiceResponse', -'Accepted', -'AccessRight', -'Account', -'AccountAggregation', -'AccountIssue', -'AccountIssueServiceClient', -'AccountManagement', -'AccountRelationship', -'AccountRelationshipsServiceClient', -'AccountService', -'AccountServicesServiceClient', -'AccountsServiceClient', -'Address', -'ApproveAccountServiceRequest', -'AutofeedSettings', -'AutofeedSettingsServiceClient', -'AutomaticImageImprovements', -'AutomaticImprovements', -'AutomaticImprovementsServiceClient', -'AutomaticItemUpdates', -'AutomaticShippingImprovements', -'BusinessDayConfig', -'BusinessIdentity', -'BusinessIdentityServiceClient', -'BusinessInfo', -'BusinessInfoServiceClient', -'CampaignsManagement', -'CarrierRate', -'CheckoutSettings', -'CheckoutSettingsServiceClient', -'ClaimHomepageRequest', -'CreateAndConfigureAccountRequest', -'CreateCheckoutSettingsRequest', -'CreateOmnichannelSettingRequest', -'CreateOnlineReturnPolicyRequest', -'CreateRegionRequest', -'CreateUserRequest', -'CustomerService', -'CutoffTime', -'DeleteAccountRequest', -'DeleteCheckoutSettingsRequest', -'DeleteOnlineReturnPolicyRequest', -'DeleteRegionRequest', -'DeleteUserRequest', -'DeliveryTime', -'DeveloperRegistration', -'DeveloperRegistrationServiceClient', -'DisableProgramRequest', -'Distance', -'EmailPreferences', -'EmailPreferencesServiceClient', -'EnableProgramRequest', -'FindLfpProvidersRequest', -'FindLfpProvidersResponse', -'GbpAccount', -'GbpAccountsServiceClient', -'GetAccountRelationshipRequest', -'GetAccountRequest', -'GetAccountServiceRequest', -'GetAutofeedSettingsRequest', -'GetAutomaticImprovementsRequest', -'GetBusinessIdentityRequest', -'GetBusinessInfoRequest', -'GetCheckoutSettingsRequest', -'GetDeveloperRegistrationRequest', -'GetEmailPreferencesRequest', -'GetHomepageRequest', -'GetOmnichannelSettingRequest', -'GetOnlineReturnPolicyRequest', -'GetProgramRequest', -'GetRegionRequest', -'GetShippingSettingsRequest', -'GetTermsOfServiceAgreementStateRequest', -'GetTermsOfServiceRequest', -'GetUserRequest', -'Handshake', -'Headers', -'Homepage', -'HomepageServiceClient', -'InStock', -'InsertShippingSettingsRequest', -'InventoryVerification', -'LfpLink', -'LfpProvider', -'LfpProvidersServiceClient', -'LinkGbpAccountRequest', -'LinkGbpAccountResponse', -'LinkLfpProviderRequest', -'LinkLfpProviderResponse', -'ListAccountIssuesRequest', -'ListAccountIssuesResponse', -'ListAccountRelationshipsRequest', -'ListAccountRelationshipsResponse', -'ListAccountServicesRequest', -'ListAccountServicesResponse', -'ListAccountsRequest', -'ListAccountsResponse', -'ListGbpAccountsRequest', -'ListGbpAccountsResponse', -'ListOmnichannelSettingsRequest', -'ListOmnichannelSettingsResponse', -'ListOnlineReturnPoliciesRequest', -'ListOnlineReturnPoliciesResponse', -'ListProgramsRequest', -'ListProgramsResponse', -'ListRegionsRequest', -'ListRegionsResponse', -'ListSubAccountsRequest', -'ListSubAccountsResponse', -'ListUsersRequest', -'ListUsersResponse', -'LocalListingManagement', -'LocationIdSet', -'MinimumOrderValueTable', -'OmnichannelSetting', -'OmnichannelSettingsServiceClient', -'OnDisplayToOrder', -'OnlineReturnPolicy', -'OnlineReturnPolicyServiceClient', -'PhoneVerificationState', -'Pickup', -'ProductsManagement', -'Program', -'ProgramsServiceClient', -'ProposeAccountServiceRequest', -'RateGroup', -'Region', -'RegionsServiceClient', -'RegisterGcpRequest', -'RejectAccountServiceRequest', -'RequestInventoryVerificationRequest', -'RequestInventoryVerificationResponse', -'Required', -'RetrieveForApplicationTermsOfServiceAgreementStateRequest', -'RetrieveLatestTermsOfServiceRequest', -'ReviewState', -'Row', -'Service', -'ShippingSettings', -'ShippingSettingsServiceClient', -'Table', -'TermsOfService', -'TermsOfServiceAgreementState', -'TermsOfServiceAgreementStateServiceClient', -'TermsOfServiceKind', -'TermsOfServiceServiceClient', -'TransitTable', -'UnclaimHomepageRequest', -'UnregisterGcpRequest', -'UpdateAccountRelationshipRequest', -'UpdateAccountRequest', -'UpdateAutofeedSettingsRequest', -'UpdateAutomaticImprovementsRequest', -'UpdateBusinessIdentityRequest', -'UpdateBusinessInfoRequest', -'UpdateCheckoutSettingsRequest', -'UpdateEmailPreferencesRequest', -'UpdateHomepageRequest', -'UpdateOmnichannelSettingRequest', -'UpdateRegionRequest', -'UpdateUserRequest', -'UriSettings', -'User', -'UserServiceClient', -'Value', -'Warehouse', -'WarehouseBasedDeliveryTime', -'WarehouseCutoffTime', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_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-accounts/v1/google/shopping/merchant_accounts_v1/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/py.typed deleted file mode 100644 index 19aa2588b0f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py deleted file mode 100644 index 5115ab24752a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_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 AccountsServiceClient -from .async_client import AccountsServiceAsyncClient - -__all__ = ( - 'AccountsServiceClient', - 'AccountsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py deleted file mode 100644 index 36cbcd559b5e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_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 AccountsServiceTransport -from .grpc import AccountsServiceGrpcTransport -from .grpc_asyncio import AccountsServiceGrpcAsyncIOTransport -from .rest import AccountsServiceRestTransport -from .rest import AccountsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AccountsServiceTransport]] -_transport_registry['grpc'] = AccountsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountsServiceRestTransport - -__all__ = ( - 'AccountsServiceTransport', - 'AccountsServiceGrpcTransport', - 'AccountsServiceGrpcAsyncIOTransport', - 'AccountsServiceRestTransport', - 'AccountsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py deleted file mode 100644 index 9d2f0554ddd6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_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 AutofeedSettingsServiceClient -from .async_client import AutofeedSettingsServiceAsyncClient - -__all__ = ( - 'AutofeedSettingsServiceClient', - 'AutofeedSettingsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py deleted file mode 100644 index c2ddd49ce02d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_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 AutofeedSettingsServiceTransport -from .grpc import AutofeedSettingsServiceGrpcTransport -from .grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport -from .rest import AutofeedSettingsServiceRestTransport -from .rest import AutofeedSettingsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AutofeedSettingsServiceTransport]] -_transport_registry['grpc'] = AutofeedSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AutofeedSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AutofeedSettingsServiceRestTransport - -__all__ = ( - 'AutofeedSettingsServiceTransport', - 'AutofeedSettingsServiceGrpcTransport', - 'AutofeedSettingsServiceGrpcAsyncIOTransport', - 'AutofeedSettingsServiceRestTransport', - 'AutofeedSettingsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py deleted file mode 100644 index df547a28f156..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_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 BusinessInfoServiceClient -from .async_client import BusinessInfoServiceAsyncClient - -__all__ = ( - 'BusinessInfoServiceClient', - 'BusinessInfoServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py deleted file mode 100644 index cd3235917a9f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_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 BusinessInfoServiceTransport -from .grpc import BusinessInfoServiceGrpcTransport -from .grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport -from .rest import BusinessInfoServiceRestTransport -from .rest import BusinessInfoServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessInfoServiceTransport]] -_transport_registry['grpc'] = BusinessInfoServiceGrpcTransport -_transport_registry['grpc_asyncio'] = BusinessInfoServiceGrpcAsyncIOTransport -_transport_registry['rest'] = BusinessInfoServiceRestTransport - -__all__ = ( - 'BusinessInfoServiceTransport', - 'BusinessInfoServiceGrpcTransport', - 'BusinessInfoServiceGrpcAsyncIOTransport', - 'BusinessInfoServiceRestTransport', - 'BusinessInfoServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py deleted file mode 100644 index e319afd3cf0a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_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 CheckoutSettingsServiceTransport -from .grpc import CheckoutSettingsServiceGrpcTransport -from .grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport -from .rest import CheckoutSettingsServiceRestTransport -from .rest import CheckoutSettingsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CheckoutSettingsServiceTransport]] -_transport_registry['grpc'] = CheckoutSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CheckoutSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = CheckoutSettingsServiceRestTransport - -__all__ = ( - 'CheckoutSettingsServiceTransport', - 'CheckoutSettingsServiceGrpcTransport', - 'CheckoutSettingsServiceGrpcAsyncIOTransport', - 'CheckoutSettingsServiceRestTransport', - 'CheckoutSettingsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py deleted file mode 100644 index 3bfd9590e738..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_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 EmailPreferencesServiceTransport -from .grpc import EmailPreferencesServiceGrpcTransport -from .grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport -from .rest import EmailPreferencesServiceRestTransport -from .rest import EmailPreferencesServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EmailPreferencesServiceTransport]] -_transport_registry['grpc'] = EmailPreferencesServiceGrpcTransport -_transport_registry['grpc_asyncio'] = EmailPreferencesServiceGrpcAsyncIOTransport -_transport_registry['rest'] = EmailPreferencesServiceRestTransport - -__all__ = ( - 'EmailPreferencesServiceTransport', - 'EmailPreferencesServiceGrpcTransport', - 'EmailPreferencesServiceGrpcAsyncIOTransport', - 'EmailPreferencesServiceRestTransport', - 'EmailPreferencesServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py deleted file mode 100644 index 38f66e5e7f00..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_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 GbpAccountsServiceClient -from .async_client import GbpAccountsServiceAsyncClient - -__all__ = ( - 'GbpAccountsServiceClient', - 'GbpAccountsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py deleted file mode 100644 index 6576bf17bbcf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_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 GbpAccountsServiceTransport -from .grpc import GbpAccountsServiceGrpcTransport -from .grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport -from .rest import GbpAccountsServiceRestTransport -from .rest import GbpAccountsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[GbpAccountsServiceTransport]] -_transport_registry['grpc'] = GbpAccountsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = GbpAccountsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = GbpAccountsServiceRestTransport - -__all__ = ( - 'GbpAccountsServiceTransport', - 'GbpAccountsServiceGrpcTransport', - 'GbpAccountsServiceGrpcAsyncIOTransport', - 'GbpAccountsServiceRestTransport', - 'GbpAccountsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py deleted file mode 100644 index f6510b1f8477..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_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 LfpProvidersServiceTransport -from .grpc import LfpProvidersServiceGrpcTransport -from .grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport -from .rest import LfpProvidersServiceRestTransport -from .rest import LfpProvidersServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LfpProvidersServiceTransport]] -_transport_registry['grpc'] = LfpProvidersServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LfpProvidersServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LfpProvidersServiceRestTransport - -__all__ = ( - 'LfpProvidersServiceTransport', - 'LfpProvidersServiceGrpcTransport', - 'LfpProvidersServiceGrpcAsyncIOTransport', - 'LfpProvidersServiceRestTransport', - 'LfpProvidersServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py deleted file mode 100644 index 400e3ec082c8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_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 ProgramsServiceClient -from .async_client import ProgramsServiceAsyncClient - -__all__ = ( - 'ProgramsServiceClient', - 'ProgramsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py deleted file mode 100644 index dc803437b5a1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_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 ProgramsServiceTransport -from .grpc import ProgramsServiceGrpcTransport -from .grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport -from .rest import ProgramsServiceRestTransport -from .rest import ProgramsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProgramsServiceTransport]] -_transport_registry['grpc'] = ProgramsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProgramsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ProgramsServiceRestTransport - -__all__ = ( - 'ProgramsServiceTransport', - 'ProgramsServiceGrpcTransport', - 'ProgramsServiceGrpcAsyncIOTransport', - 'ProgramsServiceRestTransport', - 'ProgramsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py deleted file mode 100644 index e958dfda0512..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_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 RegionsServiceTransport -from .grpc import RegionsServiceGrpcTransport -from .grpc_asyncio import RegionsServiceGrpcAsyncIOTransport -from .rest import RegionsServiceRestTransport -from .rest import RegionsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegionsServiceTransport]] -_transport_registry['grpc'] = RegionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegionsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RegionsServiceRestTransport - -__all__ = ( - 'RegionsServiceTransport', - 'RegionsServiceGrpcTransport', - 'RegionsServiceGrpcAsyncIOTransport', - 'RegionsServiceRestTransport', - 'RegionsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini b/owl-bot-staging/google-shopping-merchant-accounts/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/noxfile.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/noxfile.py deleted file mode 100644 index cc47a9500d4c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts" - -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-accounts/v1/setup.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/setup.py deleted file mode 100644 index 9c31c0f0922e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts' - - -description = "Google Shopping Merchant Accounts API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_accounts/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-accounts" - -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-accounts/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.13.txt deleted file mode 100644 index 0112695e5bbb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.7.txt deleted file mode 100644 index 2af887ec8ba0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_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-accounts/v1beta/.coveragerc b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.coveragerc deleted file mode 100644 index 8338bbe3403b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/shopping/merchant_accounts/__init__.py - google/shopping/merchant_accounts/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-accounts/v1beta/.flake8 b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/LICENSE b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/MANIFEST.in b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst deleted file mode 100644 index 419480c445c5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Shopping Merchant Accounts 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 Accounts 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-accounts/v1beta/docs/_static/custom.css b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/docs/_templates/layout.html b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/docs/conf.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/conf.py deleted file mode 100644 index 11bd96e58d11..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts 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-accounts" -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-accounts", - "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-accounts-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-accounts.tex", - u"google-shopping-merchant-accounts 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-accounts", - "google-shopping-merchant-accounts 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-accounts", - "google-shopping-merchant-accounts Documentation", - author, - "google-shopping-merchant-accounts", - "google-shopping-merchant-accounts 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-accounts/v1beta/docs/index.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst deleted file mode 100644 index eabb28aa260e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - merchant_accounts_v1beta/services_ - merchant_accounts_v1beta/types_ diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst deleted file mode 100644 index a5f41b61ad72..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_issue_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -AccountIssueService -------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_issue_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_issue_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst deleted file mode 100644 index 1693b3a3f8bd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/account_tax_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -AccountTaxService ------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_tax_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.account_tax_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst deleted file mode 100644 index 4b22494597e3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/accounts_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -AccountsService ---------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.accounts_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.accounts_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst deleted file mode 100644 index 7d16dfb96a4b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/autofeed_settings_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -AutofeedSettingsService ------------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst deleted file mode 100644 index b6303ccd115d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/automatic_improvements_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -AutomaticImprovementsService ----------------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst deleted file mode 100644 index a80c213d4edf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_identity_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -BusinessIdentityService ------------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.business_identity_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst deleted file mode 100644 index f5aa91c9d676..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/business_info_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -BusinessInfoService -------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.business_info_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst deleted file mode 100644 index fb09ef58f132..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/checkout_settings_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CheckoutSettingsService ------------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.checkout_settings_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst deleted file mode 100644 index 28be8558fb89..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/email_preferences_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -EmailPreferencesService ------------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.email_preferences_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst deleted file mode 100644 index 0e88935e0a26..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/gbp_accounts_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -GbpAccountsService ------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst deleted file mode 100644 index ce83ca532741..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/homepage_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -HomepageService ---------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.homepage_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst deleted file mode 100644 index 922ff6981cdc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/lfp_providers_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -LfpProvidersService -------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.lfp_providers_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst deleted file mode 100644 index a4bb28c60424..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/omnichannel_settings_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -OmnichannelSettingsService --------------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst deleted file mode 100644 index 4ebc9d8a8966..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/online_return_policy_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -OnlineReturnPolicyService -------------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.online_return_policy_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst deleted file mode 100644 index b69123082e7d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/programs_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ProgramsService ---------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.programs_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.programs_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst deleted file mode 100644 index 5516e7ccd805..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/regions_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -RegionsService --------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.regions_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.regions_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst deleted file mode 100644 index 7867c8a21080..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/services_.rst +++ /dev/null @@ -1,25 +0,0 @@ -Services for Google Shopping Merchant Accounts v1beta API -========================================================= -.. toctree:: - :maxdepth: 2 - - account_issue_service - accounts_service - account_tax_service - autofeed_settings_service - automatic_improvements_service - business_identity_service - business_info_service - checkout_settings_service - email_preferences_service - gbp_accounts_service - homepage_service - lfp_providers_service - omnichannel_settings_service - online_return_policy_service - programs_service - regions_service - shipping_settings_service - terms_of_service_agreement_state_service - terms_of_service_service - user_service diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst deleted file mode 100644 index 95f333afb030..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/shipping_settings_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -ShippingSettingsService ------------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.shipping_settings_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst deleted file mode 100644 index ea377121c221..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_agreement_state_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -TermsOfServiceAgreementStateService ------------------------------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst deleted file mode 100644 index 2aae813b00c9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/terms_of_service_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -TermsOfServiceService ---------------------------------------- - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.terms_of_service_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst deleted file mode 100644 index 3a0ebb568c5a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Shopping Merchant Accounts v1beta API -====================================================== - -.. automodule:: google.shopping.merchant_accounts_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst deleted file mode 100644 index 4179b3c56145..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/merchant_accounts_v1beta/user_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -UserService ------------------------------ - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.user_service - :members: - :inherited-members: - -.. automodule:: google.shopping.merchant_accounts_v1beta.services.user_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/multiprocessing.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/google/shopping/merchant_accounts/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py deleted file mode 100644 index 6c30f934f357..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/__init__.py +++ /dev/null @@ -1,371 +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_accounts import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.shopping.merchant_accounts_v1beta.services.account_issue_service.client import AccountIssueServiceClient -from google.shopping.merchant_accounts_v1beta.services.account_issue_service.async_client import AccountIssueServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.accounts_service.client import AccountsServiceClient -from google.shopping.merchant_accounts_v1beta.services.accounts_service.async_client import AccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.account_tax_service.client import AccountTaxServiceClient -from google.shopping.merchant_accounts_v1beta.services.account_tax_service.async_client import AccountTaxServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.client import AutofeedSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.async_client import AutofeedSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.client import AutomaticImprovementsServiceClient -from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.async_client import AutomaticImprovementsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.business_identity_service.client import BusinessIdentityServiceClient -from google.shopping.merchant_accounts_v1beta.services.business_identity_service.async_client import BusinessIdentityServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.business_info_service.client import BusinessInfoServiceClient -from google.shopping.merchant_accounts_v1beta.services.business_info_service.async_client import BusinessInfoServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.client import CheckoutSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.async_client import CheckoutSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.email_preferences_service.client import EmailPreferencesServiceClient -from google.shopping.merchant_accounts_v1beta.services.email_preferences_service.async_client import EmailPreferencesServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.client import GbpAccountsServiceClient -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.async_client import GbpAccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.homepage_service.client import HomepageServiceClient -from google.shopping.merchant_accounts_v1beta.services.homepage_service.async_client import HomepageServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.client import LfpProvidersServiceClient -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.async_client import LfpProvidersServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.client import OmnichannelSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.async_client import OmnichannelSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.client import OnlineReturnPolicyServiceClient -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.async_client import OnlineReturnPolicyServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.programs_service.client import ProgramsServiceClient -from google.shopping.merchant_accounts_v1beta.services.programs_service.async_client import ProgramsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.regions_service.client import RegionsServiceClient -from google.shopping.merchant_accounts_v1beta.services.regions_service.async_client import RegionsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.client import ShippingSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.async_client import ShippingSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.client import TermsOfServiceAgreementStateServiceClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.async_client import TermsOfServiceAgreementStateServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.client import TermsOfServiceServiceClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.async_client import TermsOfServiceServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.user_service.client import UserServiceClient -from google.shopping.merchant_accounts_v1beta.services.user_service.async_client import UserServiceAsyncClient - -from google.shopping.merchant_accounts_v1beta.types.accessright import AccessRight -from google.shopping.merchant_accounts_v1beta.types.account_tax import AccountTax -from google.shopping.merchant_accounts_v1beta.types.account_tax import GetAccountTaxRequest -from google.shopping.merchant_accounts_v1beta.types.account_tax import ListAccountTaxRequest -from google.shopping.merchant_accounts_v1beta.types.account_tax import ListAccountTaxResponse -from google.shopping.merchant_accounts_v1beta.types.account_tax import UpdateAccountTaxRequest -from google.shopping.merchant_accounts_v1beta.types.accountissue import AccountIssue -from google.shopping.merchant_accounts_v1beta.types.accountissue import ListAccountIssuesRequest -from google.shopping.merchant_accounts_v1beta.types.accountissue import ListAccountIssuesResponse -from google.shopping.merchant_accounts_v1beta.types.accounts import Account -from google.shopping.merchant_accounts_v1beta.types.accounts import CreateAndConfigureAccountRequest -from google.shopping.merchant_accounts_v1beta.types.accounts import DeleteAccountRequest -from google.shopping.merchant_accounts_v1beta.types.accounts import GetAccountRequest -from google.shopping.merchant_accounts_v1beta.types.accounts import ListAccountsRequest -from google.shopping.merchant_accounts_v1beta.types.accounts import ListAccountsResponse -from google.shopping.merchant_accounts_v1beta.types.accounts import ListSubAccountsRequest -from google.shopping.merchant_accounts_v1beta.types.accounts import ListSubAccountsResponse -from google.shopping.merchant_accounts_v1beta.types.accounts import UpdateAccountRequest -from google.shopping.merchant_accounts_v1beta.types.accountservices import AccountAggregation -from google.shopping.merchant_accounts_v1beta.types.autofeedsettings import AutofeedSettings -from google.shopping.merchant_accounts_v1beta.types.autofeedsettings import GetAutofeedSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.autofeedsettings import UpdateAutofeedSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticImageImprovements -from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticImprovements -from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticItemUpdates -from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import AutomaticShippingImprovements -from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import GetAutomaticImprovementsRequest -from google.shopping.merchant_accounts_v1beta.types.automaticimprovements import UpdateAutomaticImprovementsRequest -from google.shopping.merchant_accounts_v1beta.types.businessidentity import BusinessIdentity -from google.shopping.merchant_accounts_v1beta.types.businessidentity import GetBusinessIdentityRequest -from google.shopping.merchant_accounts_v1beta.types.businessidentity import UpdateBusinessIdentityRequest -from google.shopping.merchant_accounts_v1beta.types.businessinfo import BusinessInfo -from google.shopping.merchant_accounts_v1beta.types.businessinfo import GetBusinessInfoRequest -from google.shopping.merchant_accounts_v1beta.types.businessinfo import UpdateBusinessInfoRequest -from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import CheckoutSettings -from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import CreateCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import DeleteCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import GetCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import UpdateCheckoutSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.checkoutsettings import UriSettings -from google.shopping.merchant_accounts_v1beta.types.customerservice import CustomerService -from google.shopping.merchant_accounts_v1beta.types.emailpreferences import EmailPreferences -from google.shopping.merchant_accounts_v1beta.types.emailpreferences import GetEmailPreferencesRequest -from google.shopping.merchant_accounts_v1beta.types.emailpreferences import UpdateEmailPreferencesRequest -from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import GbpAccount -from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import LinkGbpAccountRequest -from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import LinkGbpAccountResponse -from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import ListGbpAccountsRequest -from google.shopping.merchant_accounts_v1beta.types.gbpaccounts import ListGbpAccountsResponse -from google.shopping.merchant_accounts_v1beta.types.homepage import ClaimHomepageRequest -from google.shopping.merchant_accounts_v1beta.types.homepage import GetHomepageRequest -from google.shopping.merchant_accounts_v1beta.types.homepage import Homepage -from google.shopping.merchant_accounts_v1beta.types.homepage import UnclaimHomepageRequest -from google.shopping.merchant_accounts_v1beta.types.homepage import UpdateHomepageRequest -from google.shopping.merchant_accounts_v1beta.types.lfpproviders import FindLfpProvidersRequest -from google.shopping.merchant_accounts_v1beta.types.lfpproviders import FindLfpProvidersResponse -from google.shopping.merchant_accounts_v1beta.types.lfpproviders import LfpProvider -from google.shopping.merchant_accounts_v1beta.types.lfpproviders import LinkLfpProviderRequest -from google.shopping.merchant_accounts_v1beta.types.lfpproviders import LinkLfpProviderResponse -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import About -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import CreateOmnichannelSettingRequest -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import GetOmnichannelSettingRequest -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import InStock -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import InventoryVerification -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import LfpLink -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import ListOmnichannelSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import ListOmnichannelSettingsResponse -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import OmnichannelSetting -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import OnDisplayToOrder -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import Pickup -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import RequestInventoryVerificationRequest -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import RequestInventoryVerificationResponse -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import ReviewState -from google.shopping.merchant_accounts_v1beta.types.omnichannelsettings import UpdateOmnichannelSettingRequest -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import CreateOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import DeleteOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import GetOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import ListOnlineReturnPoliciesRequest -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import ListOnlineReturnPoliciesResponse -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import OnlineReturnPolicy -from google.shopping.merchant_accounts_v1beta.types.online_return_policy import UpdateOnlineReturnPolicyRequest -from google.shopping.merchant_accounts_v1beta.types.phoneverificationstate import PhoneVerificationState -from google.shopping.merchant_accounts_v1beta.types.programs import DisableProgramRequest -from google.shopping.merchant_accounts_v1beta.types.programs import EnableProgramRequest -from google.shopping.merchant_accounts_v1beta.types.programs import GetProgramRequest -from google.shopping.merchant_accounts_v1beta.types.programs import ListProgramsRequest -from google.shopping.merchant_accounts_v1beta.types.programs import ListProgramsResponse -from google.shopping.merchant_accounts_v1beta.types.programs import Program -from google.shopping.merchant_accounts_v1beta.types.regions import CreateRegionRequest -from google.shopping.merchant_accounts_v1beta.types.regions import DeleteRegionRequest -from google.shopping.merchant_accounts_v1beta.types.regions import GetRegionRequest -from google.shopping.merchant_accounts_v1beta.types.regions import ListRegionsRequest -from google.shopping.merchant_accounts_v1beta.types.regions import ListRegionsResponse -from google.shopping.merchant_accounts_v1beta.types.regions import Region -from google.shopping.merchant_accounts_v1beta.types.regions import UpdateRegionRequest -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Address -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import BusinessDayConfig -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import CarrierRate -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import CutoffTime -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import DeliveryTime -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Distance -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import GetShippingSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Headers -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import InsertShippingSettingsRequest -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import LocationIdSet -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import MinimumOrderValueTable -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import RateGroup -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Row -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Service -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import ShippingSettings -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Table -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import TransitTable -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Value -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import Warehouse -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import WarehouseBasedDeliveryTime -from google.shopping.merchant_accounts_v1beta.types.shippingsettings import WarehouseCutoffTime -from google.shopping.merchant_accounts_v1beta.types.tax_rule import TaxRule -from google.shopping.merchant_accounts_v1beta.types.termsofservice import AcceptTermsOfServiceRequest -from google.shopping.merchant_accounts_v1beta.types.termsofservice import GetTermsOfServiceRequest -from google.shopping.merchant_accounts_v1beta.types.termsofservice import RetrieveLatestTermsOfServiceRequest -from google.shopping.merchant_accounts_v1beta.types.termsofservice import TermsOfService -from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import Accepted -from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest -from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import Required -from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest -from google.shopping.merchant_accounts_v1beta.types.termsofserviceagreementstate import TermsOfServiceAgreementState -from google.shopping.merchant_accounts_v1beta.types.termsofservicekind import TermsOfServiceKind -from google.shopping.merchant_accounts_v1beta.types.user import CreateUserRequest -from google.shopping.merchant_accounts_v1beta.types.user import DeleteUserRequest -from google.shopping.merchant_accounts_v1beta.types.user import GetUserRequest -from google.shopping.merchant_accounts_v1beta.types.user import ListUsersRequest -from google.shopping.merchant_accounts_v1beta.types.user import ListUsersResponse -from google.shopping.merchant_accounts_v1beta.types.user import UpdateUserRequest -from google.shopping.merchant_accounts_v1beta.types.user import User - -__all__ = ('AccountIssueServiceClient', - 'AccountIssueServiceAsyncClient', - 'AccountsServiceClient', - 'AccountsServiceAsyncClient', - 'AccountTaxServiceClient', - 'AccountTaxServiceAsyncClient', - 'AutofeedSettingsServiceClient', - 'AutofeedSettingsServiceAsyncClient', - 'AutomaticImprovementsServiceClient', - 'AutomaticImprovementsServiceAsyncClient', - 'BusinessIdentityServiceClient', - 'BusinessIdentityServiceAsyncClient', - 'BusinessInfoServiceClient', - 'BusinessInfoServiceAsyncClient', - 'CheckoutSettingsServiceClient', - 'CheckoutSettingsServiceAsyncClient', - 'EmailPreferencesServiceClient', - 'EmailPreferencesServiceAsyncClient', - 'GbpAccountsServiceClient', - 'GbpAccountsServiceAsyncClient', - 'HomepageServiceClient', - 'HomepageServiceAsyncClient', - 'LfpProvidersServiceClient', - 'LfpProvidersServiceAsyncClient', - 'OmnichannelSettingsServiceClient', - 'OmnichannelSettingsServiceAsyncClient', - 'OnlineReturnPolicyServiceClient', - 'OnlineReturnPolicyServiceAsyncClient', - 'ProgramsServiceClient', - 'ProgramsServiceAsyncClient', - 'RegionsServiceClient', - 'RegionsServiceAsyncClient', - 'ShippingSettingsServiceClient', - 'ShippingSettingsServiceAsyncClient', - 'TermsOfServiceAgreementStateServiceClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', - 'TermsOfServiceServiceClient', - 'TermsOfServiceServiceAsyncClient', - 'UserServiceClient', - 'UserServiceAsyncClient', - 'AccessRight', - 'AccountTax', - 'GetAccountTaxRequest', - 'ListAccountTaxRequest', - 'ListAccountTaxResponse', - 'UpdateAccountTaxRequest', - 'AccountIssue', - 'ListAccountIssuesRequest', - 'ListAccountIssuesResponse', - 'Account', - 'CreateAndConfigureAccountRequest', - 'DeleteAccountRequest', - 'GetAccountRequest', - 'ListAccountsRequest', - 'ListAccountsResponse', - 'ListSubAccountsRequest', - 'ListSubAccountsResponse', - 'UpdateAccountRequest', - 'AccountAggregation', - 'AutofeedSettings', - 'GetAutofeedSettingsRequest', - 'UpdateAutofeedSettingsRequest', - 'AutomaticImageImprovements', - 'AutomaticImprovements', - 'AutomaticItemUpdates', - 'AutomaticShippingImprovements', - 'GetAutomaticImprovementsRequest', - 'UpdateAutomaticImprovementsRequest', - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - 'CheckoutSettings', - 'CreateCheckoutSettingsRequest', - 'DeleteCheckoutSettingsRequest', - 'GetCheckoutSettingsRequest', - 'UpdateCheckoutSettingsRequest', - 'UriSettings', - 'CustomerService', - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - 'GbpAccount', - 'LinkGbpAccountRequest', - 'LinkGbpAccountResponse', - 'ListGbpAccountsRequest', - 'ListGbpAccountsResponse', - 'ClaimHomepageRequest', - 'GetHomepageRequest', - 'Homepage', - 'UnclaimHomepageRequest', - 'UpdateHomepageRequest', - 'FindLfpProvidersRequest', - 'FindLfpProvidersResponse', - 'LfpProvider', - 'LinkLfpProviderRequest', - 'LinkLfpProviderResponse', - 'About', - 'CreateOmnichannelSettingRequest', - 'GetOmnichannelSettingRequest', - 'InStock', - 'InventoryVerification', - 'LfpLink', - 'ListOmnichannelSettingsRequest', - 'ListOmnichannelSettingsResponse', - 'OmnichannelSetting', - 'OnDisplayToOrder', - 'Pickup', - 'RequestInventoryVerificationRequest', - 'RequestInventoryVerificationResponse', - 'ReviewState', - 'UpdateOmnichannelSettingRequest', - 'CreateOnlineReturnPolicyRequest', - 'DeleteOnlineReturnPolicyRequest', - 'GetOnlineReturnPolicyRequest', - 'ListOnlineReturnPoliciesRequest', - 'ListOnlineReturnPoliciesResponse', - 'OnlineReturnPolicy', - 'UpdateOnlineReturnPolicyRequest', - 'PhoneVerificationState', - 'DisableProgramRequest', - 'EnableProgramRequest', - 'GetProgramRequest', - 'ListProgramsRequest', - 'ListProgramsResponse', - 'Program', - 'CreateRegionRequest', - 'DeleteRegionRequest', - 'GetRegionRequest', - 'ListRegionsRequest', - 'ListRegionsResponse', - 'Region', - 'UpdateRegionRequest', - 'Address', - 'BusinessDayConfig', - 'CarrierRate', - 'CutoffTime', - 'DeliveryTime', - 'Distance', - 'GetShippingSettingsRequest', - 'Headers', - 'InsertShippingSettingsRequest', - 'LocationIdSet', - 'MinimumOrderValueTable', - 'RateGroup', - 'Row', - 'Service', - 'ShippingSettings', - 'Table', - 'TransitTable', - 'Value', - 'Warehouse', - 'WarehouseBasedDeliveryTime', - 'WarehouseCutoffTime', - 'TaxRule', - 'AcceptTermsOfServiceRequest', - 'GetTermsOfServiceRequest', - 'RetrieveLatestTermsOfServiceRequest', - 'TermsOfService', - 'Accepted', - 'GetTermsOfServiceAgreementStateRequest', - 'Required', - 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', - 'TermsOfServiceAgreementState', - 'TermsOfServiceKind', - 'CreateUserRequest', - 'DeleteUserRequest', - 'GetUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - 'UpdateUserRequest', - 'User', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/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-accounts/v1beta/google/shopping/merchant_accounts/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/py.typed deleted file mode 100644 index 19aa2588b0f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py deleted file mode 100644 index 845ae3aa592c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/__init__.py +++ /dev/null @@ -1,372 +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_accounts_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.account_issue_service import AccountIssueServiceClient -from .services.account_issue_service import AccountIssueServiceAsyncClient -from .services.accounts_service import AccountsServiceClient -from .services.accounts_service import AccountsServiceAsyncClient -from .services.account_tax_service import AccountTaxServiceClient -from .services.account_tax_service import AccountTaxServiceAsyncClient -from .services.autofeed_settings_service import AutofeedSettingsServiceClient -from .services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient -from .services.automatic_improvements_service import AutomaticImprovementsServiceClient -from .services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient -from .services.business_identity_service import BusinessIdentityServiceClient -from .services.business_identity_service import BusinessIdentityServiceAsyncClient -from .services.business_info_service import BusinessInfoServiceClient -from .services.business_info_service import BusinessInfoServiceAsyncClient -from .services.checkout_settings_service import CheckoutSettingsServiceClient -from .services.checkout_settings_service import CheckoutSettingsServiceAsyncClient -from .services.email_preferences_service import EmailPreferencesServiceClient -from .services.email_preferences_service import EmailPreferencesServiceAsyncClient -from .services.gbp_accounts_service import GbpAccountsServiceClient -from .services.gbp_accounts_service import GbpAccountsServiceAsyncClient -from .services.homepage_service import HomepageServiceClient -from .services.homepage_service import HomepageServiceAsyncClient -from .services.lfp_providers_service import LfpProvidersServiceClient -from .services.lfp_providers_service import LfpProvidersServiceAsyncClient -from .services.omnichannel_settings_service import OmnichannelSettingsServiceClient -from .services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient -from .services.online_return_policy_service import OnlineReturnPolicyServiceClient -from .services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient -from .services.programs_service import ProgramsServiceClient -from .services.programs_service import ProgramsServiceAsyncClient -from .services.regions_service import RegionsServiceClient -from .services.regions_service import RegionsServiceAsyncClient -from .services.shipping_settings_service import ShippingSettingsServiceClient -from .services.shipping_settings_service import ShippingSettingsServiceAsyncClient -from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient -from .services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient -from .services.terms_of_service_service import TermsOfServiceServiceClient -from .services.terms_of_service_service import TermsOfServiceServiceAsyncClient -from .services.user_service import UserServiceClient -from .services.user_service import UserServiceAsyncClient - -from .types.accessright import AccessRight -from .types.account_tax import AccountTax -from .types.account_tax import GetAccountTaxRequest -from .types.account_tax import ListAccountTaxRequest -from .types.account_tax import ListAccountTaxResponse -from .types.account_tax import UpdateAccountTaxRequest -from .types.accountissue import AccountIssue -from .types.accountissue import ListAccountIssuesRequest -from .types.accountissue import ListAccountIssuesResponse -from .types.accounts import Account -from .types.accounts import CreateAndConfigureAccountRequest -from .types.accounts import DeleteAccountRequest -from .types.accounts import GetAccountRequest -from .types.accounts import ListAccountsRequest -from .types.accounts import ListAccountsResponse -from .types.accounts import ListSubAccountsRequest -from .types.accounts import ListSubAccountsResponse -from .types.accounts import UpdateAccountRequest -from .types.accountservices import AccountAggregation -from .types.autofeedsettings import AutofeedSettings -from .types.autofeedsettings import GetAutofeedSettingsRequest -from .types.autofeedsettings import UpdateAutofeedSettingsRequest -from .types.automaticimprovements import AutomaticImageImprovements -from .types.automaticimprovements import AutomaticImprovements -from .types.automaticimprovements import AutomaticItemUpdates -from .types.automaticimprovements import AutomaticShippingImprovements -from .types.automaticimprovements import GetAutomaticImprovementsRequest -from .types.automaticimprovements import UpdateAutomaticImprovementsRequest -from .types.businessidentity import BusinessIdentity -from .types.businessidentity import GetBusinessIdentityRequest -from .types.businessidentity import UpdateBusinessIdentityRequest -from .types.businessinfo import BusinessInfo -from .types.businessinfo import GetBusinessInfoRequest -from .types.businessinfo import UpdateBusinessInfoRequest -from .types.checkoutsettings import CheckoutSettings -from .types.checkoutsettings import CreateCheckoutSettingsRequest -from .types.checkoutsettings import DeleteCheckoutSettingsRequest -from .types.checkoutsettings import GetCheckoutSettingsRequest -from .types.checkoutsettings import UpdateCheckoutSettingsRequest -from .types.checkoutsettings import UriSettings -from .types.customerservice import CustomerService -from .types.emailpreferences import EmailPreferences -from .types.emailpreferences import GetEmailPreferencesRequest -from .types.emailpreferences import UpdateEmailPreferencesRequest -from .types.gbpaccounts import GbpAccount -from .types.gbpaccounts import LinkGbpAccountRequest -from .types.gbpaccounts import LinkGbpAccountResponse -from .types.gbpaccounts import ListGbpAccountsRequest -from .types.gbpaccounts import ListGbpAccountsResponse -from .types.homepage import ClaimHomepageRequest -from .types.homepage import GetHomepageRequest -from .types.homepage import Homepage -from .types.homepage import UnclaimHomepageRequest -from .types.homepage import UpdateHomepageRequest -from .types.lfpproviders import FindLfpProvidersRequest -from .types.lfpproviders import FindLfpProvidersResponse -from .types.lfpproviders import LfpProvider -from .types.lfpproviders import LinkLfpProviderRequest -from .types.lfpproviders import LinkLfpProviderResponse -from .types.omnichannelsettings import About -from .types.omnichannelsettings import CreateOmnichannelSettingRequest -from .types.omnichannelsettings import GetOmnichannelSettingRequest -from .types.omnichannelsettings import InStock -from .types.omnichannelsettings import InventoryVerification -from .types.omnichannelsettings import LfpLink -from .types.omnichannelsettings import ListOmnichannelSettingsRequest -from .types.omnichannelsettings import ListOmnichannelSettingsResponse -from .types.omnichannelsettings import OmnichannelSetting -from .types.omnichannelsettings import OnDisplayToOrder -from .types.omnichannelsettings import Pickup -from .types.omnichannelsettings import RequestInventoryVerificationRequest -from .types.omnichannelsettings import RequestInventoryVerificationResponse -from .types.omnichannelsettings import ReviewState -from .types.omnichannelsettings import UpdateOmnichannelSettingRequest -from .types.online_return_policy import CreateOnlineReturnPolicyRequest -from .types.online_return_policy import DeleteOnlineReturnPolicyRequest -from .types.online_return_policy import GetOnlineReturnPolicyRequest -from .types.online_return_policy import ListOnlineReturnPoliciesRequest -from .types.online_return_policy import ListOnlineReturnPoliciesResponse -from .types.online_return_policy import OnlineReturnPolicy -from .types.online_return_policy import UpdateOnlineReturnPolicyRequest -from .types.phoneverificationstate import PhoneVerificationState -from .types.programs import DisableProgramRequest -from .types.programs import EnableProgramRequest -from .types.programs import GetProgramRequest -from .types.programs import ListProgramsRequest -from .types.programs import ListProgramsResponse -from .types.programs import Program -from .types.regions import CreateRegionRequest -from .types.regions import DeleteRegionRequest -from .types.regions import GetRegionRequest -from .types.regions import ListRegionsRequest -from .types.regions import ListRegionsResponse -from .types.regions import Region -from .types.regions import UpdateRegionRequest -from .types.shippingsettings import Address -from .types.shippingsettings import BusinessDayConfig -from .types.shippingsettings import CarrierRate -from .types.shippingsettings import CutoffTime -from .types.shippingsettings import DeliveryTime -from .types.shippingsettings import Distance -from .types.shippingsettings import GetShippingSettingsRequest -from .types.shippingsettings import Headers -from .types.shippingsettings import InsertShippingSettingsRequest -from .types.shippingsettings import LocationIdSet -from .types.shippingsettings import MinimumOrderValueTable -from .types.shippingsettings import RateGroup -from .types.shippingsettings import Row -from .types.shippingsettings import Service -from .types.shippingsettings import ShippingSettings -from .types.shippingsettings import Table -from .types.shippingsettings import TransitTable -from .types.shippingsettings import Value -from .types.shippingsettings import Warehouse -from .types.shippingsettings import WarehouseBasedDeliveryTime -from .types.shippingsettings import WarehouseCutoffTime -from .types.tax_rule import TaxRule -from .types.termsofservice import AcceptTermsOfServiceRequest -from .types.termsofservice import GetTermsOfServiceRequest -from .types.termsofservice import RetrieveLatestTermsOfServiceRequest -from .types.termsofservice import TermsOfService -from .types.termsofserviceagreementstate import Accepted -from .types.termsofserviceagreementstate import GetTermsOfServiceAgreementStateRequest -from .types.termsofserviceagreementstate import Required -from .types.termsofserviceagreementstate import RetrieveForApplicationTermsOfServiceAgreementStateRequest -from .types.termsofserviceagreementstate import TermsOfServiceAgreementState -from .types.termsofservicekind import TermsOfServiceKind -from .types.user import CreateUserRequest -from .types.user import DeleteUserRequest -from .types.user import GetUserRequest -from .types.user import ListUsersRequest -from .types.user import ListUsersResponse -from .types.user import UpdateUserRequest -from .types.user import User - -__all__ = ( - 'AccountIssueServiceAsyncClient', - 'AccountTaxServiceAsyncClient', - 'AccountsServiceAsyncClient', - 'AutofeedSettingsServiceAsyncClient', - 'AutomaticImprovementsServiceAsyncClient', - 'BusinessIdentityServiceAsyncClient', - 'BusinessInfoServiceAsyncClient', - 'CheckoutSettingsServiceAsyncClient', - 'EmailPreferencesServiceAsyncClient', - 'GbpAccountsServiceAsyncClient', - 'HomepageServiceAsyncClient', - 'LfpProvidersServiceAsyncClient', - 'OmnichannelSettingsServiceAsyncClient', - 'OnlineReturnPolicyServiceAsyncClient', - 'ProgramsServiceAsyncClient', - 'RegionsServiceAsyncClient', - 'ShippingSettingsServiceAsyncClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', - 'TermsOfServiceServiceAsyncClient', - 'UserServiceAsyncClient', -'About', -'AcceptTermsOfServiceRequest', -'Accepted', -'AccessRight', -'Account', -'AccountAggregation', -'AccountIssue', -'AccountIssueServiceClient', -'AccountTax', -'AccountTaxServiceClient', -'AccountsServiceClient', -'Address', -'AutofeedSettings', -'AutofeedSettingsServiceClient', -'AutomaticImageImprovements', -'AutomaticImprovements', -'AutomaticImprovementsServiceClient', -'AutomaticItemUpdates', -'AutomaticShippingImprovements', -'BusinessDayConfig', -'BusinessIdentity', -'BusinessIdentityServiceClient', -'BusinessInfo', -'BusinessInfoServiceClient', -'CarrierRate', -'CheckoutSettings', -'CheckoutSettingsServiceClient', -'ClaimHomepageRequest', -'CreateAndConfigureAccountRequest', -'CreateCheckoutSettingsRequest', -'CreateOmnichannelSettingRequest', -'CreateOnlineReturnPolicyRequest', -'CreateRegionRequest', -'CreateUserRequest', -'CustomerService', -'CutoffTime', -'DeleteAccountRequest', -'DeleteCheckoutSettingsRequest', -'DeleteOnlineReturnPolicyRequest', -'DeleteRegionRequest', -'DeleteUserRequest', -'DeliveryTime', -'DisableProgramRequest', -'Distance', -'EmailPreferences', -'EmailPreferencesServiceClient', -'EnableProgramRequest', -'FindLfpProvidersRequest', -'FindLfpProvidersResponse', -'GbpAccount', -'GbpAccountsServiceClient', -'GetAccountRequest', -'GetAccountTaxRequest', -'GetAutofeedSettingsRequest', -'GetAutomaticImprovementsRequest', -'GetBusinessIdentityRequest', -'GetBusinessInfoRequest', -'GetCheckoutSettingsRequest', -'GetEmailPreferencesRequest', -'GetHomepageRequest', -'GetOmnichannelSettingRequest', -'GetOnlineReturnPolicyRequest', -'GetProgramRequest', -'GetRegionRequest', -'GetShippingSettingsRequest', -'GetTermsOfServiceAgreementStateRequest', -'GetTermsOfServiceRequest', -'GetUserRequest', -'Headers', -'Homepage', -'HomepageServiceClient', -'InStock', -'InsertShippingSettingsRequest', -'InventoryVerification', -'LfpLink', -'LfpProvider', -'LfpProvidersServiceClient', -'LinkGbpAccountRequest', -'LinkGbpAccountResponse', -'LinkLfpProviderRequest', -'LinkLfpProviderResponse', -'ListAccountIssuesRequest', -'ListAccountIssuesResponse', -'ListAccountTaxRequest', -'ListAccountTaxResponse', -'ListAccountsRequest', -'ListAccountsResponse', -'ListGbpAccountsRequest', -'ListGbpAccountsResponse', -'ListOmnichannelSettingsRequest', -'ListOmnichannelSettingsResponse', -'ListOnlineReturnPoliciesRequest', -'ListOnlineReturnPoliciesResponse', -'ListProgramsRequest', -'ListProgramsResponse', -'ListRegionsRequest', -'ListRegionsResponse', -'ListSubAccountsRequest', -'ListSubAccountsResponse', -'ListUsersRequest', -'ListUsersResponse', -'LocationIdSet', -'MinimumOrderValueTable', -'OmnichannelSetting', -'OmnichannelSettingsServiceClient', -'OnDisplayToOrder', -'OnlineReturnPolicy', -'OnlineReturnPolicyServiceClient', -'PhoneVerificationState', -'Pickup', -'Program', -'ProgramsServiceClient', -'RateGroup', -'Region', -'RegionsServiceClient', -'RequestInventoryVerificationRequest', -'RequestInventoryVerificationResponse', -'Required', -'RetrieveForApplicationTermsOfServiceAgreementStateRequest', -'RetrieveLatestTermsOfServiceRequest', -'ReviewState', -'Row', -'Service', -'ShippingSettings', -'ShippingSettingsServiceClient', -'Table', -'TaxRule', -'TermsOfService', -'TermsOfServiceAgreementState', -'TermsOfServiceAgreementStateServiceClient', -'TermsOfServiceKind', -'TermsOfServiceServiceClient', -'TransitTable', -'UnclaimHomepageRequest', -'UpdateAccountRequest', -'UpdateAccountTaxRequest', -'UpdateAutofeedSettingsRequest', -'UpdateAutomaticImprovementsRequest', -'UpdateBusinessIdentityRequest', -'UpdateBusinessInfoRequest', -'UpdateCheckoutSettingsRequest', -'UpdateEmailPreferencesRequest', -'UpdateHomepageRequest', -'UpdateOmnichannelSettingRequest', -'UpdateOnlineReturnPolicyRequest', -'UpdateRegionRequest', -'UpdateUserRequest', -'UriSettings', -'User', -'UserServiceClient', -'Value', -'Warehouse', -'WarehouseBasedDeliveryTime', -'WarehouseCutoffTime', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json deleted file mode 100644 index 306403adf83a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_metadata.json +++ /dev/null @@ -1,1334 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.shopping.merchant_accounts_v1beta", - "protoPackage": "google.shopping.merchant.accounts.v1beta", - "schema": "1.0", - "services": { - "AccountIssueService": { - "clients": { - "grpc": { - "libraryClient": "AccountIssueServiceClient", - "rpcs": { - "ListAccountIssues": { - "methods": [ - "list_account_issues" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AccountIssueServiceAsyncClient", - "rpcs": { - "ListAccountIssues": { - "methods": [ - "list_account_issues" - ] - } - } - }, - "rest": { - "libraryClient": "AccountIssueServiceClient", - "rpcs": { - "ListAccountIssues": { - "methods": [ - "list_account_issues" - ] - } - } - } - } - }, - "AccountTaxService": { - "clients": { - "grpc": { - "libraryClient": "AccountTaxServiceClient", - "rpcs": { - "GetAccountTax": { - "methods": [ - "get_account_tax" - ] - }, - "ListAccountTax": { - "methods": [ - "list_account_tax" - ] - }, - "UpdateAccountTax": { - "methods": [ - "update_account_tax" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AccountTaxServiceAsyncClient", - "rpcs": { - "GetAccountTax": { - "methods": [ - "get_account_tax" - ] - }, - "ListAccountTax": { - "methods": [ - "list_account_tax" - ] - }, - "UpdateAccountTax": { - "methods": [ - "update_account_tax" - ] - } - } - }, - "rest": { - "libraryClient": "AccountTaxServiceClient", - "rpcs": { - "GetAccountTax": { - "methods": [ - "get_account_tax" - ] - }, - "ListAccountTax": { - "methods": [ - "list_account_tax" - ] - }, - "UpdateAccountTax": { - "methods": [ - "update_account_tax" - ] - } - } - } - } - }, - "AccountsService": { - "clients": { - "grpc": { - "libraryClient": "AccountsServiceClient", - "rpcs": { - "CreateAndConfigureAccount": { - "methods": [ - "create_and_configure_account" - ] - }, - "DeleteAccount": { - "methods": [ - "delete_account" - ] - }, - "GetAccount": { - "methods": [ - "get_account" - ] - }, - "ListAccounts": { - "methods": [ - "list_accounts" - ] - }, - "ListSubAccounts": { - "methods": [ - "list_sub_accounts" - ] - }, - "UpdateAccount": { - "methods": [ - "update_account" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AccountsServiceAsyncClient", - "rpcs": { - "CreateAndConfigureAccount": { - "methods": [ - "create_and_configure_account" - ] - }, - "DeleteAccount": { - "methods": [ - "delete_account" - ] - }, - "GetAccount": { - "methods": [ - "get_account" - ] - }, - "ListAccounts": { - "methods": [ - "list_accounts" - ] - }, - "ListSubAccounts": { - "methods": [ - "list_sub_accounts" - ] - }, - "UpdateAccount": { - "methods": [ - "update_account" - ] - } - } - }, - "rest": { - "libraryClient": "AccountsServiceClient", - "rpcs": { - "CreateAndConfigureAccount": { - "methods": [ - "create_and_configure_account" - ] - }, - "DeleteAccount": { - "methods": [ - "delete_account" - ] - }, - "GetAccount": { - "methods": [ - "get_account" - ] - }, - "ListAccounts": { - "methods": [ - "list_accounts" - ] - }, - "ListSubAccounts": { - "methods": [ - "list_sub_accounts" - ] - }, - "UpdateAccount": { - "methods": [ - "update_account" - ] - } - } - } - } - }, - "AutofeedSettingsService": { - "clients": { - "grpc": { - "libraryClient": "AutofeedSettingsServiceClient", - "rpcs": { - "GetAutofeedSettings": { - "methods": [ - "get_autofeed_settings" - ] - }, - "UpdateAutofeedSettings": { - "methods": [ - "update_autofeed_settings" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AutofeedSettingsServiceAsyncClient", - "rpcs": { - "GetAutofeedSettings": { - "methods": [ - "get_autofeed_settings" - ] - }, - "UpdateAutofeedSettings": { - "methods": [ - "update_autofeed_settings" - ] - } - } - }, - "rest": { - "libraryClient": "AutofeedSettingsServiceClient", - "rpcs": { - "GetAutofeedSettings": { - "methods": [ - "get_autofeed_settings" - ] - }, - "UpdateAutofeedSettings": { - "methods": [ - "update_autofeed_settings" - ] - } - } - } - } - }, - "AutomaticImprovementsService": { - "clients": { - "grpc": { - "libraryClient": "AutomaticImprovementsServiceClient", - "rpcs": { - "GetAutomaticImprovements": { - "methods": [ - "get_automatic_improvements" - ] - }, - "UpdateAutomaticImprovements": { - "methods": [ - "update_automatic_improvements" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AutomaticImprovementsServiceAsyncClient", - "rpcs": { - "GetAutomaticImprovements": { - "methods": [ - "get_automatic_improvements" - ] - }, - "UpdateAutomaticImprovements": { - "methods": [ - "update_automatic_improvements" - ] - } - } - }, - "rest": { - "libraryClient": "AutomaticImprovementsServiceClient", - "rpcs": { - "GetAutomaticImprovements": { - "methods": [ - "get_automatic_improvements" - ] - }, - "UpdateAutomaticImprovements": { - "methods": [ - "update_automatic_improvements" - ] - } - } - } - } - }, - "BusinessIdentityService": { - "clients": { - "grpc": { - "libraryClient": "BusinessIdentityServiceClient", - "rpcs": { - "GetBusinessIdentity": { - "methods": [ - "get_business_identity" - ] - }, - "UpdateBusinessIdentity": { - "methods": [ - "update_business_identity" - ] - } - } - }, - "grpc-async": { - "libraryClient": "BusinessIdentityServiceAsyncClient", - "rpcs": { - "GetBusinessIdentity": { - "methods": [ - "get_business_identity" - ] - }, - "UpdateBusinessIdentity": { - "methods": [ - "update_business_identity" - ] - } - } - }, - "rest": { - "libraryClient": "BusinessIdentityServiceClient", - "rpcs": { - "GetBusinessIdentity": { - "methods": [ - "get_business_identity" - ] - }, - "UpdateBusinessIdentity": { - "methods": [ - "update_business_identity" - ] - } - } - } - } - }, - "BusinessInfoService": { - "clients": { - "grpc": { - "libraryClient": "BusinessInfoServiceClient", - "rpcs": { - "GetBusinessInfo": { - "methods": [ - "get_business_info" - ] - }, - "UpdateBusinessInfo": { - "methods": [ - "update_business_info" - ] - } - } - }, - "grpc-async": { - "libraryClient": "BusinessInfoServiceAsyncClient", - "rpcs": { - "GetBusinessInfo": { - "methods": [ - "get_business_info" - ] - }, - "UpdateBusinessInfo": { - "methods": [ - "update_business_info" - ] - } - } - }, - "rest": { - "libraryClient": "BusinessInfoServiceClient", - "rpcs": { - "GetBusinessInfo": { - "methods": [ - "get_business_info" - ] - }, - "UpdateBusinessInfo": { - "methods": [ - "update_business_info" - ] - } - } - } - } - }, - "CheckoutSettingsService": { - "clients": { - "grpc": { - "libraryClient": "CheckoutSettingsServiceClient", - "rpcs": { - "CreateCheckoutSettings": { - "methods": [ - "create_checkout_settings" - ] - }, - "DeleteCheckoutSettings": { - "methods": [ - "delete_checkout_settings" - ] - }, - "GetCheckoutSettings": { - "methods": [ - "get_checkout_settings" - ] - }, - "UpdateCheckoutSettings": { - "methods": [ - "update_checkout_settings" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CheckoutSettingsServiceAsyncClient", - "rpcs": { - "CreateCheckoutSettings": { - "methods": [ - "create_checkout_settings" - ] - }, - "DeleteCheckoutSettings": { - "methods": [ - "delete_checkout_settings" - ] - }, - "GetCheckoutSettings": { - "methods": [ - "get_checkout_settings" - ] - }, - "UpdateCheckoutSettings": { - "methods": [ - "update_checkout_settings" - ] - } - } - }, - "rest": { - "libraryClient": "CheckoutSettingsServiceClient", - "rpcs": { - "CreateCheckoutSettings": { - "methods": [ - "create_checkout_settings" - ] - }, - "DeleteCheckoutSettings": { - "methods": [ - "delete_checkout_settings" - ] - }, - "GetCheckoutSettings": { - "methods": [ - "get_checkout_settings" - ] - }, - "UpdateCheckoutSettings": { - "methods": [ - "update_checkout_settings" - ] - } - } - } - } - }, - "EmailPreferencesService": { - "clients": { - "grpc": { - "libraryClient": "EmailPreferencesServiceClient", - "rpcs": { - "GetEmailPreferences": { - "methods": [ - "get_email_preferences" - ] - }, - "UpdateEmailPreferences": { - "methods": [ - "update_email_preferences" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EmailPreferencesServiceAsyncClient", - "rpcs": { - "GetEmailPreferences": { - "methods": [ - "get_email_preferences" - ] - }, - "UpdateEmailPreferences": { - "methods": [ - "update_email_preferences" - ] - } - } - }, - "rest": { - "libraryClient": "EmailPreferencesServiceClient", - "rpcs": { - "GetEmailPreferences": { - "methods": [ - "get_email_preferences" - ] - }, - "UpdateEmailPreferences": { - "methods": [ - "update_email_preferences" - ] - } - } - } - } - }, - "GbpAccountsService": { - "clients": { - "grpc": { - "libraryClient": "GbpAccountsServiceClient", - "rpcs": { - "LinkGbpAccount": { - "methods": [ - "link_gbp_account" - ] - }, - "ListGbpAccounts": { - "methods": [ - "list_gbp_accounts" - ] - } - } - }, - "grpc-async": { - "libraryClient": "GbpAccountsServiceAsyncClient", - "rpcs": { - "LinkGbpAccount": { - "methods": [ - "link_gbp_account" - ] - }, - "ListGbpAccounts": { - "methods": [ - "list_gbp_accounts" - ] - } - } - }, - "rest": { - "libraryClient": "GbpAccountsServiceClient", - "rpcs": { - "LinkGbpAccount": { - "methods": [ - "link_gbp_account" - ] - }, - "ListGbpAccounts": { - "methods": [ - "list_gbp_accounts" - ] - } - } - } - } - }, - "HomepageService": { - "clients": { - "grpc": { - "libraryClient": "HomepageServiceClient", - "rpcs": { - "ClaimHomepage": { - "methods": [ - "claim_homepage" - ] - }, - "GetHomepage": { - "methods": [ - "get_homepage" - ] - }, - "UnclaimHomepage": { - "methods": [ - "unclaim_homepage" - ] - }, - "UpdateHomepage": { - "methods": [ - "update_homepage" - ] - } - } - }, - "grpc-async": { - "libraryClient": "HomepageServiceAsyncClient", - "rpcs": { - "ClaimHomepage": { - "methods": [ - "claim_homepage" - ] - }, - "GetHomepage": { - "methods": [ - "get_homepage" - ] - }, - "UnclaimHomepage": { - "methods": [ - "unclaim_homepage" - ] - }, - "UpdateHomepage": { - "methods": [ - "update_homepage" - ] - } - } - }, - "rest": { - "libraryClient": "HomepageServiceClient", - "rpcs": { - "ClaimHomepage": { - "methods": [ - "claim_homepage" - ] - }, - "GetHomepage": { - "methods": [ - "get_homepage" - ] - }, - "UnclaimHomepage": { - "methods": [ - "unclaim_homepage" - ] - }, - "UpdateHomepage": { - "methods": [ - "update_homepage" - ] - } - } - } - } - }, - "LfpProvidersService": { - "clients": { - "grpc": { - "libraryClient": "LfpProvidersServiceClient", - "rpcs": { - "FindLfpProviders": { - "methods": [ - "find_lfp_providers" - ] - }, - "LinkLfpProvider": { - "methods": [ - "link_lfp_provider" - ] - } - } - }, - "grpc-async": { - "libraryClient": "LfpProvidersServiceAsyncClient", - "rpcs": { - "FindLfpProviders": { - "methods": [ - "find_lfp_providers" - ] - }, - "LinkLfpProvider": { - "methods": [ - "link_lfp_provider" - ] - } - } - }, - "rest": { - "libraryClient": "LfpProvidersServiceClient", - "rpcs": { - "FindLfpProviders": { - "methods": [ - "find_lfp_providers" - ] - }, - "LinkLfpProvider": { - "methods": [ - "link_lfp_provider" - ] - } - } - } - } - }, - "OmnichannelSettingsService": { - "clients": { - "grpc": { - "libraryClient": "OmnichannelSettingsServiceClient", - "rpcs": { - "CreateOmnichannelSetting": { - "methods": [ - "create_omnichannel_setting" - ] - }, - "GetOmnichannelSetting": { - "methods": [ - "get_omnichannel_setting" - ] - }, - "ListOmnichannelSettings": { - "methods": [ - "list_omnichannel_settings" - ] - }, - "RequestInventoryVerification": { - "methods": [ - "request_inventory_verification" - ] - }, - "UpdateOmnichannelSetting": { - "methods": [ - "update_omnichannel_setting" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OmnichannelSettingsServiceAsyncClient", - "rpcs": { - "CreateOmnichannelSetting": { - "methods": [ - "create_omnichannel_setting" - ] - }, - "GetOmnichannelSetting": { - "methods": [ - "get_omnichannel_setting" - ] - }, - "ListOmnichannelSettings": { - "methods": [ - "list_omnichannel_settings" - ] - }, - "RequestInventoryVerification": { - "methods": [ - "request_inventory_verification" - ] - }, - "UpdateOmnichannelSetting": { - "methods": [ - "update_omnichannel_setting" - ] - } - } - }, - "rest": { - "libraryClient": "OmnichannelSettingsServiceClient", - "rpcs": { - "CreateOmnichannelSetting": { - "methods": [ - "create_omnichannel_setting" - ] - }, - "GetOmnichannelSetting": { - "methods": [ - "get_omnichannel_setting" - ] - }, - "ListOmnichannelSettings": { - "methods": [ - "list_omnichannel_settings" - ] - }, - "RequestInventoryVerification": { - "methods": [ - "request_inventory_verification" - ] - }, - "UpdateOmnichannelSetting": { - "methods": [ - "update_omnichannel_setting" - ] - } - } - } - } - }, - "OnlineReturnPolicyService": { - "clients": { - "grpc": { - "libraryClient": "OnlineReturnPolicyServiceClient", - "rpcs": { - "CreateOnlineReturnPolicy": { - "methods": [ - "create_online_return_policy" - ] - }, - "DeleteOnlineReturnPolicy": { - "methods": [ - "delete_online_return_policy" - ] - }, - "GetOnlineReturnPolicy": { - "methods": [ - "get_online_return_policy" - ] - }, - "ListOnlineReturnPolicies": { - "methods": [ - "list_online_return_policies" - ] - }, - "UpdateOnlineReturnPolicy": { - "methods": [ - "update_online_return_policy" - ] - } - } - }, - "grpc-async": { - "libraryClient": "OnlineReturnPolicyServiceAsyncClient", - "rpcs": { - "CreateOnlineReturnPolicy": { - "methods": [ - "create_online_return_policy" - ] - }, - "DeleteOnlineReturnPolicy": { - "methods": [ - "delete_online_return_policy" - ] - }, - "GetOnlineReturnPolicy": { - "methods": [ - "get_online_return_policy" - ] - }, - "ListOnlineReturnPolicies": { - "methods": [ - "list_online_return_policies" - ] - }, - "UpdateOnlineReturnPolicy": { - "methods": [ - "update_online_return_policy" - ] - } - } - }, - "rest": { - "libraryClient": "OnlineReturnPolicyServiceClient", - "rpcs": { - "CreateOnlineReturnPolicy": { - "methods": [ - "create_online_return_policy" - ] - }, - "DeleteOnlineReturnPolicy": { - "methods": [ - "delete_online_return_policy" - ] - }, - "GetOnlineReturnPolicy": { - "methods": [ - "get_online_return_policy" - ] - }, - "ListOnlineReturnPolicies": { - "methods": [ - "list_online_return_policies" - ] - }, - "UpdateOnlineReturnPolicy": { - "methods": [ - "update_online_return_policy" - ] - } - } - } - } - }, - "ProgramsService": { - "clients": { - "grpc": { - "libraryClient": "ProgramsServiceClient", - "rpcs": { - "DisableProgram": { - "methods": [ - "disable_program" - ] - }, - "EnableProgram": { - "methods": [ - "enable_program" - ] - }, - "GetProgram": { - "methods": [ - "get_program" - ] - }, - "ListPrograms": { - "methods": [ - "list_programs" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProgramsServiceAsyncClient", - "rpcs": { - "DisableProgram": { - "methods": [ - "disable_program" - ] - }, - "EnableProgram": { - "methods": [ - "enable_program" - ] - }, - "GetProgram": { - "methods": [ - "get_program" - ] - }, - "ListPrograms": { - "methods": [ - "list_programs" - ] - } - } - }, - "rest": { - "libraryClient": "ProgramsServiceClient", - "rpcs": { - "DisableProgram": { - "methods": [ - "disable_program" - ] - }, - "EnableProgram": { - "methods": [ - "enable_program" - ] - }, - "GetProgram": { - "methods": [ - "get_program" - ] - }, - "ListPrograms": { - "methods": [ - "list_programs" - ] - } - } - } - } - }, - "RegionsService": { - "clients": { - "grpc": { - "libraryClient": "RegionsServiceClient", - "rpcs": { - "CreateRegion": { - "methods": [ - "create_region" - ] - }, - "DeleteRegion": { - "methods": [ - "delete_region" - ] - }, - "GetRegion": { - "methods": [ - "get_region" - ] - }, - "ListRegions": { - "methods": [ - "list_regions" - ] - }, - "UpdateRegion": { - "methods": [ - "update_region" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RegionsServiceAsyncClient", - "rpcs": { - "CreateRegion": { - "methods": [ - "create_region" - ] - }, - "DeleteRegion": { - "methods": [ - "delete_region" - ] - }, - "GetRegion": { - "methods": [ - "get_region" - ] - }, - "ListRegions": { - "methods": [ - "list_regions" - ] - }, - "UpdateRegion": { - "methods": [ - "update_region" - ] - } - } - }, - "rest": { - "libraryClient": "RegionsServiceClient", - "rpcs": { - "CreateRegion": { - "methods": [ - "create_region" - ] - }, - "DeleteRegion": { - "methods": [ - "delete_region" - ] - }, - "GetRegion": { - "methods": [ - "get_region" - ] - }, - "ListRegions": { - "methods": [ - "list_regions" - ] - }, - "UpdateRegion": { - "methods": [ - "update_region" - ] - } - } - } - } - }, - "ShippingSettingsService": { - "clients": { - "grpc": { - "libraryClient": "ShippingSettingsServiceClient", - "rpcs": { - "GetShippingSettings": { - "methods": [ - "get_shipping_settings" - ] - }, - "InsertShippingSettings": { - "methods": [ - "insert_shipping_settings" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ShippingSettingsServiceAsyncClient", - "rpcs": { - "GetShippingSettings": { - "methods": [ - "get_shipping_settings" - ] - }, - "InsertShippingSettings": { - "methods": [ - "insert_shipping_settings" - ] - } - } - }, - "rest": { - "libraryClient": "ShippingSettingsServiceClient", - "rpcs": { - "GetShippingSettings": { - "methods": [ - "get_shipping_settings" - ] - }, - "InsertShippingSettings": { - "methods": [ - "insert_shipping_settings" - ] - } - } - } - } - }, - "TermsOfServiceAgreementStateService": { - "clients": { - "grpc": { - "libraryClient": "TermsOfServiceAgreementStateServiceClient", - "rpcs": { - "GetTermsOfServiceAgreementState": { - "methods": [ - "get_terms_of_service_agreement_state" - ] - }, - "RetrieveForApplicationTermsOfServiceAgreementState": { - "methods": [ - "retrieve_for_application_terms_of_service_agreement_state" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TermsOfServiceAgreementStateServiceAsyncClient", - "rpcs": { - "GetTermsOfServiceAgreementState": { - "methods": [ - "get_terms_of_service_agreement_state" - ] - }, - "RetrieveForApplicationTermsOfServiceAgreementState": { - "methods": [ - "retrieve_for_application_terms_of_service_agreement_state" - ] - } - } - }, - "rest": { - "libraryClient": "TermsOfServiceAgreementStateServiceClient", - "rpcs": { - "GetTermsOfServiceAgreementState": { - "methods": [ - "get_terms_of_service_agreement_state" - ] - }, - "RetrieveForApplicationTermsOfServiceAgreementState": { - "methods": [ - "retrieve_for_application_terms_of_service_agreement_state" - ] - } - } - } - } - }, - "TermsOfServiceService": { - "clients": { - "grpc": { - "libraryClient": "TermsOfServiceServiceClient", - "rpcs": { - "AcceptTermsOfService": { - "methods": [ - "accept_terms_of_service" - ] - }, - "GetTermsOfService": { - "methods": [ - "get_terms_of_service" - ] - }, - "RetrieveLatestTermsOfService": { - "methods": [ - "retrieve_latest_terms_of_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "TermsOfServiceServiceAsyncClient", - "rpcs": { - "AcceptTermsOfService": { - "methods": [ - "accept_terms_of_service" - ] - }, - "GetTermsOfService": { - "methods": [ - "get_terms_of_service" - ] - }, - "RetrieveLatestTermsOfService": { - "methods": [ - "retrieve_latest_terms_of_service" - ] - } - } - }, - "rest": { - "libraryClient": "TermsOfServiceServiceClient", - "rpcs": { - "AcceptTermsOfService": { - "methods": [ - "accept_terms_of_service" - ] - }, - "GetTermsOfService": { - "methods": [ - "get_terms_of_service" - ] - }, - "RetrieveLatestTermsOfService": { - "methods": [ - "retrieve_latest_terms_of_service" - ] - } - } - } - } - }, - "UserService": { - "clients": { - "grpc": { - "libraryClient": "UserServiceClient", - "rpcs": { - "CreateUser": { - "methods": [ - "create_user" - ] - }, - "DeleteUser": { - "methods": [ - "delete_user" - ] - }, - "GetUser": { - "methods": [ - "get_user" - ] - }, - "ListUsers": { - "methods": [ - "list_users" - ] - }, - "UpdateUser": { - "methods": [ - "update_user" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserServiceAsyncClient", - "rpcs": { - "CreateUser": { - "methods": [ - "create_user" - ] - }, - "DeleteUser": { - "methods": [ - "delete_user" - ] - }, - "GetUser": { - "methods": [ - "get_user" - ] - }, - "ListUsers": { - "methods": [ - "list_users" - ] - }, - "UpdateUser": { - "methods": [ - "update_user" - ] - } - } - }, - "rest": { - "libraryClient": "UserServiceClient", - "rpcs": { - "CreateUser": { - "methods": [ - "create_user" - ] - }, - "DeleteUser": { - "methods": [ - "delete_user" - ] - }, - "GetUser": { - "methods": [ - "get_user" - ] - }, - "ListUsers": { - "methods": [ - "list_users" - ] - }, - "UpdateUser": { - "methods": [ - "update_user" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_version.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed deleted file mode 100644 index 19aa2588b0f7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-shopping-merchant-accounts package uses inline types. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/__init__.py deleted file mode 100644 index 1c1c6dd19914..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_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 AccountIssueServiceClient -from .async_client import AccountIssueServiceAsyncClient - -__all__ = ( - 'AccountIssueServiceClient', - 'AccountIssueServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py deleted file mode 100644 index 9863fcd0a6c7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/async_client.py +++ /dev/null @@ -1,386 +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_accounts_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_accounts_v1beta.services.account_issue_service import pagers -from google.shopping.merchant_accounts_v1beta.types import accountissue -from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport -from .client import AccountIssueServiceClient - -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 AccountIssueServiceAsyncClient: - """Service to support ``AccountIssueService`` API.""" - - _client: AccountIssueServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AccountIssueServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AccountIssueServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(AccountIssueServiceClient.account_path) - parse_account_path = staticmethod(AccountIssueServiceClient.parse_account_path) - account_issue_path = staticmethod(AccountIssueServiceClient.account_issue_path) - parse_account_issue_path = staticmethod(AccountIssueServiceClient.parse_account_issue_path) - common_billing_account_path = staticmethod(AccountIssueServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountIssueServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AccountIssueServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountIssueServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountIssueServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountIssueServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AccountIssueServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountIssueServiceClient.parse_common_project_path) - common_location_path = staticmethod(AccountIssueServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountIssueServiceClient.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: - AccountIssueServiceAsyncClient: The constructed client. - """ - return AccountIssueServiceClient.from_service_account_info.__func__(AccountIssueServiceAsyncClient, 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: - AccountIssueServiceAsyncClient: The constructed client. - """ - return AccountIssueServiceClient.from_service_account_file.__func__(AccountIssueServiceAsyncClient, 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 AccountIssueServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AccountIssueServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AccountIssueServiceTransport: 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 = AccountIssueServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the account issue 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,AccountIssueServiceTransport,Callable[..., AccountIssueServiceTransport]]]): - 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 AccountIssueServiceTransport 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 = AccountIssueServiceClient( - 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.accounts_v1beta.AccountIssueServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", - "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.accounts.v1beta.AccountIssueService", - "credentialsType": None, - } - ) - - async def list_account_issues(self, - request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesAsyncPager: - r"""Lists all account issues of a Merchant Center - 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_accounts_v1beta - - async def sample_list_account_issues(): - # Create a client - client = merchant_accounts_v1beta.AccountIssueServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountIssuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_issues(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest, dict]]): - The request object. Request message for the ``ListAccountIssues`` method. - parent (:class:`str`): - Required. The parent, which owns this collection of - issues. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesAsyncPager: - Response message for the ListAccountIssues 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, accountissue.ListAccountIssuesRequest): - request = accountissue.ListAccountIssuesRequest(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_account_issues] - - # 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.ListAccountIssuesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "AccountIssueServiceAsyncClient": - 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__ = ( - "AccountIssueServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py deleted file mode 100644 index c5f0d50a63ef..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/client.py +++ /dev/null @@ -1,755 +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_accounts_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_accounts_v1beta.services.account_issue_service import pagers -from google.shopping.merchant_accounts_v1beta.types import accountissue -from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AccountIssueServiceGrpcTransport -from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport -from .transports.rest import AccountIssueServiceRestTransport - - -class AccountIssueServiceClientMeta(type): - """Metaclass for the AccountIssueService 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[AccountIssueServiceTransport]] - _transport_registry["grpc"] = AccountIssueServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AccountIssueServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AccountIssueServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountIssueServiceTransport]: - """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 AccountIssueServiceClient(metaclass=AccountIssueServiceClientMeta): - """Service to support ``AccountIssueService`` API.""" - - @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: - AccountIssueServiceClient: 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: - AccountIssueServiceClient: 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) -> AccountIssueServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AccountIssueServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def account_issue_path(account: str,issue: str,) -> str: - """Returns a fully-qualified account_issue string.""" - return "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) - - @staticmethod - def parse_account_issue_path(path: str) -> Dict[str,str]: - """Parses a account_issue path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/issues/(?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 = AccountIssueServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AccountIssueServiceClient._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 = AccountIssueServiceClient._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, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the account issue 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,AccountIssueServiceTransport,Callable[..., AccountIssueServiceTransport]]]): - 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 AccountIssueServiceTransport 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 = AccountIssueServiceClient._read_environment_variables() - self._client_cert_source = AccountIssueServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountIssueServiceClient._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, AccountIssueServiceTransport) - if transport_provided: - # transport is a AccountIssueServiceTransport 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(AccountIssueServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AccountIssueServiceClient._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[AccountIssueServiceTransport], Callable[..., AccountIssueServiceTransport]] = ( - AccountIssueServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AccountIssueServiceTransport], 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.accounts_v1beta.AccountIssueServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", - "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.accounts.v1beta.AccountIssueService", - "credentialsType": None, - } - ) - - def list_account_issues(self, - request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesPager: - r"""Lists all account issues of a Merchant Center - 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_accounts_v1beta - - def sample_list_account_issues(): - # Create a client - client = merchant_accounts_v1beta.AccountIssueServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountIssuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_issues(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest, dict]): - The request object. Request message for the ``ListAccountIssues`` method. - parent (str): - Required. The parent, which owns this collection of - issues. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesPager: - Response message for the ListAccountIssues 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, accountissue.ListAccountIssuesRequest): - request = accountissue.ListAccountIssuesRequest(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_account_issues] - - # 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.ListAccountIssuesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AccountIssueServiceClient": - 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__ = ( - "AccountIssueServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/pagers.py deleted file mode 100644 index 25d6740a69a2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_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_accounts_v1beta.types import accountissue - - -class ListAccountIssuesPager: - """A pager for iterating through ``list_account_issues`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``account_issues`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAccountIssues`` requests and continue to iterate - through the ``account_issues`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` - 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[..., accountissue.ListAccountIssuesResponse], - request: accountissue.ListAccountIssuesRequest, - response: accountissue.ListAccountIssuesResponse, - *, - 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_accounts_v1beta.types.ListAccountIssuesRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse): - 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 = accountissue.ListAccountIssuesRequest(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[accountissue.ListAccountIssuesResponse]: - 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[accountissue.AccountIssue]: - for page in self.pages: - yield from page.account_issues - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAccountIssuesAsyncPager: - """A pager for iterating through ``list_account_issues`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``account_issues`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAccountIssues`` requests and continue to iterate - through the ``account_issues`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse` - 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[accountissue.ListAccountIssuesResponse]], - request: accountissue.ListAccountIssuesRequest, - response: accountissue.ListAccountIssuesResponse, - *, - 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_accounts_v1beta.types.ListAccountIssuesRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesResponse): - 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 = accountissue.ListAccountIssuesRequest(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[accountissue.ListAccountIssuesResponse]: - 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[accountissue.AccountIssue]: - async def async_generator(): - async for page in self.pages: - for response in page.account_issues: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst deleted file mode 100644 index c03ba991127e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AccountIssueServiceTransport` is the ABC for all transports. -- public child `AccountIssueServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AccountIssueServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAccountIssueServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AccountIssueServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/__init__.py deleted file mode 100644 index 7a24cf1c8dd1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_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 AccountIssueServiceTransport -from .grpc import AccountIssueServiceGrpcTransport -from .grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport -from .rest import AccountIssueServiceRestTransport -from .rest import AccountIssueServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AccountIssueServiceTransport]] -_transport_registry['grpc'] = AccountIssueServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountIssueServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountIssueServiceRestTransport - -__all__ = ( - 'AccountIssueServiceTransport', - 'AccountIssueServiceGrpcTransport', - 'AccountIssueServiceGrpcAsyncIOTransport', - 'AccountIssueServiceRestTransport', - 'AccountIssueServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py deleted file mode 100644 index 8f5c255142fb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/base.py +++ /dev/null @@ -1,159 +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_accounts_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.shopping.merchant_accounts_v1beta.types import accountissue - -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 AccountIssueServiceTransport(abc.ABC): - """Abstract transport class for AccountIssueService.""" - - 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_account_issues: gapic_v1.method.wrap_method( - self.list_account_issues, - 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_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - Union[ - accountissue.ListAccountIssuesResponse, - Awaitable[accountissue.ListAccountIssuesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AccountIssueServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py deleted file mode 100644 index 99311a702952..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc.py +++ /dev/null @@ -1,347 +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.shopping.merchant_accounts_v1beta.types import accountissue -from .base import AccountIssueServiceTransport, 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.accounts.v1beta.AccountIssueService", - "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.accounts.v1beta.AccountIssueService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AccountIssueServiceGrpcTransport(AccountIssueServiceTransport): - """gRPC backend transport for AccountIssueService. - - Service to support ``AccountIssueService`` API. - - 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_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - accountissue.ListAccountIssuesResponse]: - r"""Return a callable for the list account issues method over gRPC. - - Lists all account issues of a Merchant Center - account. - - Returns: - Callable[[~.ListAccountIssuesRequest], - ~.ListAccountIssuesResponse]: - 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_account_issues' not in self._stubs: - self._stubs['list_account_issues'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountIssueService/ListAccountIssues', - request_serializer=accountissue.ListAccountIssuesRequest.serialize, - response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, - ) - return self._stubs['list_account_issues'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AccountIssueServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py deleted file mode 100644 index 04f578690beb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,368 +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.shopping.merchant_accounts_v1beta.types import accountissue -from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AccountIssueServiceGrpcTransport - -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.accounts.v1beta.AccountIssueService", - "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.accounts.v1beta.AccountIssueService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AccountIssueServiceGrpcAsyncIOTransport(AccountIssueServiceTransport): - """gRPC AsyncIO backend transport for AccountIssueService. - - Service to support ``AccountIssueService`` API. - - 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_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - Awaitable[accountissue.ListAccountIssuesResponse]]: - r"""Return a callable for the list account issues method over gRPC. - - Lists all account issues of a Merchant Center - account. - - Returns: - Callable[[~.ListAccountIssuesRequest], - Awaitable[~.ListAccountIssuesResponse]]: - 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_account_issues' not in self._stubs: - self._stubs['list_account_issues'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountIssueService/ListAccountIssues', - request_serializer=accountissue.ListAccountIssuesRequest.serialize, - response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, - ) - return self._stubs['list_account_issues'] - - 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_account_issues: self._wrap_method( - self.list_account_issues, - 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__ = ( - 'AccountIssueServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py deleted file mode 100644 index 1c0497024937..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest.py +++ /dev/null @@ -1,351 +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.shopping.merchant_accounts_v1beta.types import accountissue - - -from .rest_base import _BaseAccountIssueServiceRestTransport -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 AccountIssueServiceRestInterceptor: - """Interceptor for AccountIssueService. - - 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 AccountIssueServiceRestTransport. - - .. code-block:: python - class MyCustomAccountIssueServiceInterceptor(AccountIssueServiceRestInterceptor): - def pre_list_account_issues(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_account_issues(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AccountIssueServiceRestTransport(interceptor=MyCustomAccountIssueServiceInterceptor()) - client = AccountIssueServiceClient(transport=transport) - - - """ - def pre_list_account_issues(self, request: accountissue.ListAccountIssuesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_account_issues - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountIssueService server. - """ - return request, metadata - - def post_list_account_issues(self, response: accountissue.ListAccountIssuesResponse) -> accountissue.ListAccountIssuesResponse: - """Post-rpc interceptor for list_account_issues - - DEPRECATED. Please use the `post_list_account_issues_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountIssueService server but before - it is returned to user code. This `post_list_account_issues` interceptor runs - before the `post_list_account_issues_with_metadata` interceptor. - """ - return response - - def post_list_account_issues_with_metadata(self, response: accountissue.ListAccountIssuesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_account_issues - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountIssueService server but before it is returned to user code. - - We recommend only using this `post_list_account_issues_with_metadata` - interceptor in new development instead of the `post_list_account_issues` interceptor. - When both interceptors are used, this `post_list_account_issues_with_metadata` interceptor runs after the - `post_list_account_issues` interceptor. The (possibly modified) response returned by - `post_list_account_issues` will be passed to - `post_list_account_issues_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class AccountIssueServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AccountIssueServiceRestInterceptor - - -class AccountIssueServiceRestTransport(_BaseAccountIssueServiceRestTransport): - """REST backend synchronous transport for AccountIssueService. - - Service to support ``AccountIssueService`` API. - - 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[AccountIssueServiceRestInterceptor] = 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 AccountIssueServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ListAccountIssues(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues, AccountIssueServiceRestStub): - def __hash__(self): - return hash("AccountIssueServiceRestTransport.ListAccountIssues") - - @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: accountissue.ListAccountIssuesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountissue.ListAccountIssuesResponse: - r"""Call the list account issues method over HTTP. - - Args: - request (~.accountissue.ListAccountIssuesRequest): - The request object. Request message for the ``ListAccountIssues`` 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: - ~.accountissue.ListAccountIssuesResponse: - Response message for the ``ListAccountIssues`` method. - """ - - http_options = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_http_options() - - request, metadata = self._interceptor.pre_list_account_issues(request, metadata) - transcoded_request = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountIssueServiceClient.ListAccountIssues", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", - "rpcName": "ListAccountIssues", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountIssueServiceRestTransport._ListAccountIssues._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 = accountissue.ListAccountIssuesResponse() - pb_resp = accountissue.ListAccountIssuesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_account_issues(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_account_issues_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = accountissue.ListAccountIssuesResponse.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.accounts_v1beta.AccountIssueServiceClient.list_account_issues", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", - "rpcName": "ListAccountIssues", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def list_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - accountissue.ListAccountIssuesResponse]: - # 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._ListAccountIssues(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AccountIssueServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py deleted file mode 100644 index 495938966b5a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_issue_service/transports/rest_base.py +++ /dev/null @@ -1,128 +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 AccountIssueServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import accountissue - - -class _BaseAccountIssueServiceRestTransport(AccountIssueServiceTransport): - """Base REST backend transport for AccountIssueService. - - 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 _BaseListAccountIssues: - 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': '/accounts/v1beta/{parent=accounts/*}/issues', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accountissue.ListAccountIssuesRequest.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(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAccountIssueServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/__init__.py deleted file mode 100644 index 440c9e63750e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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 AccountTaxServiceClient -from .async_client import AccountTaxServiceAsyncClient - -__all__ = ( - 'AccountTaxServiceClient', - 'AccountTaxServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py deleted file mode 100644 index c339300cded2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/async_client.py +++ /dev/null @@ -1,623 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.account_tax_service import pagers -from google.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax -from google.shopping.merchant_accounts_v1beta.types import tax_rule -from .transports.base import AccountTaxServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport -from .client import AccountTaxServiceClient - -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 AccountTaxServiceAsyncClient: - """Manages account level tax setting data. - - This API defines the following resource model: - - - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] - """ - - _client: AccountTaxServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AccountTaxServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AccountTaxServiceClient._DEFAULT_UNIVERSE - - account_tax_path = staticmethod(AccountTaxServiceClient.account_tax_path) - parse_account_tax_path = staticmethod(AccountTaxServiceClient.parse_account_tax_path) - common_billing_account_path = staticmethod(AccountTaxServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountTaxServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AccountTaxServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountTaxServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountTaxServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountTaxServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AccountTaxServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountTaxServiceClient.parse_common_project_path) - common_location_path = staticmethod(AccountTaxServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountTaxServiceClient.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: - AccountTaxServiceAsyncClient: The constructed client. - """ - return AccountTaxServiceClient.from_service_account_info.__func__(AccountTaxServiceAsyncClient, 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: - AccountTaxServiceAsyncClient: The constructed client. - """ - return AccountTaxServiceClient.from_service_account_file.__func__(AccountTaxServiceAsyncClient, 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 AccountTaxServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AccountTaxServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AccountTaxServiceTransport: 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 = AccountTaxServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountTaxServiceTransport, Callable[..., AccountTaxServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the account tax 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,AccountTaxServiceTransport,Callable[..., AccountTaxServiceTransport]]]): - 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 AccountTaxServiceTransport 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 = AccountTaxServiceClient( - 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.accounts_v1beta.AccountTaxServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "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.accounts.v1beta.AccountTaxService", - "credentialsType": None, - } - ) - - async def get_account_tax(self, - request: Optional[Union[account_tax.GetAccountTaxRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> account_tax.AccountTax: - r"""Returns the tax rules that match the conditions of - GetAccountTaxRequest - - .. 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_accounts_v1beta - - async def sample_get_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountTaxRequest( - name="name_value", - ) - - # Make the request - response = await client.get_account_tax(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest, dict]]): - The request object. Request to get tax settings - name (:class:`str`): - Required. The name from which tax - settings will be retrieved - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.AccountTax: - The tax settings of a merchant - account. All methods require the admin - role. - - """ - # 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, account_tax.GetAccountTaxRequest): - request = account_tax.GetAccountTaxRequest(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.get_account_tax] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_account_tax(self, - request: Optional[Union[account_tax.ListAccountTaxRequest, 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.ListAccountTaxAsyncPager: - r"""Lists the tax settings of the sub-accounts only in - your Merchant Center account. - This method can only be called on a multi-client - account, otherwise it'll return an error. - - .. 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_accounts_v1beta - - async def sample_list_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountTaxRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_tax(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest, dict]]): - The request object. Request to list all sub-account tax - settings only for the requesting - merchant This method can only be called - on a multi-client account, otherwise - it'll return an error. - parent (:class:`str`): - Required. The parent, which owns this - collection of account tax. Format: - accounts/{account} - - 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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxAsyncPager: - Response to account tax list request - This method can only be called on a - multi-client account, otherwise it'll - return an error. - - 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, account_tax.ListAccountTaxRequest): - request = account_tax.ListAccountTaxRequest(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_account_tax] - - # 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.ListAccountTaxAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_account_tax(self, - request: Optional[Union[gsma_account_tax.UpdateAccountTaxRequest, dict]] = None, - *, - account_tax: Optional[gsma_account_tax.AccountTax] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_account_tax.AccountTax: - r"""Updates the tax settings of the 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_accounts_v1beta - - async def sample_update_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAccountTaxRequest( - ) - - # Make the request - response = await client.update_account_tax(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest, dict]]): - The request object. Request to update the tax settings - account_tax (:class:`google.shopping.merchant_accounts_v1beta.types.AccountTax`): - Required. The tax setting that will - be updated - - This corresponds to the ``account_tax`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The list of fields to be updated - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AccountTax: - The tax settings of a merchant - account. All methods require the admin - role. - - """ - # 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 = [account_tax, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_account_tax.UpdateAccountTaxRequest): - request = gsma_account_tax.UpdateAccountTaxRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if account_tax is not None: - request.account_tax = account_tax - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_account_tax] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account_tax.name", request.account_tax.name), - )), - ) - - # 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 __aenter__(self) -> "AccountTaxServiceAsyncClient": - 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__ = ( - "AccountTaxServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py deleted file mode 100644 index 0f3cd5d31304..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/client.py +++ /dev/null @@ -1,981 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.account_tax_service import pagers -from google.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax -from google.shopping.merchant_accounts_v1beta.types import tax_rule -from .transports.base import AccountTaxServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AccountTaxServiceGrpcTransport -from .transports.grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport -from .transports.rest import AccountTaxServiceRestTransport - - -class AccountTaxServiceClientMeta(type): - """Metaclass for the AccountTaxService 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[AccountTaxServiceTransport]] - _transport_registry["grpc"] = AccountTaxServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AccountTaxServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AccountTaxServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountTaxServiceTransport]: - """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 AccountTaxServiceClient(metaclass=AccountTaxServiceClientMeta): - """Manages account level tax setting data. - - This API defines the following resource model: - - - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] - """ - - @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: - AccountTaxServiceClient: 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: - AccountTaxServiceClient: 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) -> AccountTaxServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AccountTaxServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_tax_path(account: str,tax: str,) -> str: - """Returns a fully-qualified account_tax string.""" - return "accounts/{account}/accounttax/{tax}".format(account=account, tax=tax, ) - - @staticmethod - def parse_account_tax_path(path: str) -> Dict[str,str]: - """Parses a account_tax path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/accounttax/(?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 = AccountTaxServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AccountTaxServiceClient._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 = AccountTaxServiceClient._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, AccountTaxServiceTransport, Callable[..., AccountTaxServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the account tax 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,AccountTaxServiceTransport,Callable[..., AccountTaxServiceTransport]]]): - 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 AccountTaxServiceTransport 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 = AccountTaxServiceClient._read_environment_variables() - self._client_cert_source = AccountTaxServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountTaxServiceClient._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, AccountTaxServiceTransport) - if transport_provided: - # transport is a AccountTaxServiceTransport 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(AccountTaxServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AccountTaxServiceClient._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[AccountTaxServiceTransport], Callable[..., AccountTaxServiceTransport]] = ( - AccountTaxServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AccountTaxServiceTransport], 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.accounts_v1beta.AccountTaxServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "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.accounts.v1beta.AccountTaxService", - "credentialsType": None, - } - ) - - def get_account_tax(self, - request: Optional[Union[account_tax.GetAccountTaxRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> account_tax.AccountTax: - r"""Returns the tax rules that match the conditions of - GetAccountTaxRequest - - .. 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_accounts_v1beta - - def sample_get_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountTaxRequest( - name="name_value", - ) - - # Make the request - response = client.get_account_tax(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest, dict]): - The request object. Request to get tax settings - name (str): - Required. The name from which tax - settings will be retrieved - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.AccountTax: - The tax settings of a merchant - account. All methods require the admin - role. - - """ - # 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, account_tax.GetAccountTaxRequest): - request = account_tax.GetAccountTaxRequest(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.get_account_tax] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_account_tax(self, - request: Optional[Union[account_tax.ListAccountTaxRequest, 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.ListAccountTaxPager: - r"""Lists the tax settings of the sub-accounts only in - your Merchant Center account. - This method can only be called on a multi-client - account, otherwise it'll return an error. - - .. 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_accounts_v1beta - - def sample_list_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountTaxRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_tax(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest, dict]): - The request object. Request to list all sub-account tax - settings only for the requesting - merchant This method can only be called - on a multi-client account, otherwise - it'll return an error. - parent (str): - Required. The parent, which owns this - collection of account tax. Format: - accounts/{account} - - 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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxPager: - Response to account tax list request - This method can only be called on a - multi-client account, otherwise it'll - return an error. - - 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, account_tax.ListAccountTaxRequest): - request = account_tax.ListAccountTaxRequest(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_account_tax] - - # 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.ListAccountTaxPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_account_tax(self, - request: Optional[Union[gsma_account_tax.UpdateAccountTaxRequest, dict]] = None, - *, - account_tax: Optional[gsma_account_tax.AccountTax] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_account_tax.AccountTax: - r"""Updates the tax settings of the 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_accounts_v1beta - - def sample_update_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAccountTaxRequest( - ) - - # Make the request - response = client.update_account_tax(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest, dict]): - The request object. Request to update the tax settings - account_tax (google.shopping.merchant_accounts_v1beta.types.AccountTax): - Required. The tax setting that will - be updated - - This corresponds to the ``account_tax`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AccountTax: - The tax settings of a merchant - account. All methods require the admin - role. - - """ - # 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 = [account_tax, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_account_tax.UpdateAccountTaxRequest): - request = gsma_account_tax.UpdateAccountTaxRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if account_tax is not None: - request.account_tax = account_tax - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_account_tax] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account_tax.name", request.account_tax.name), - )), - ) - - # 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 __enter__(self) -> "AccountTaxServiceClient": - 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__ = ( - "AccountTaxServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/pagers.py deleted file mode 100644 index d0e42a3afa12..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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_accounts_v1beta.types import account_tax - - -class ListAccountTaxPager: - """A pager for iterating through ``list_account_tax`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` object, and - provides an ``__iter__`` method to iterate through its - ``account_taxes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAccountTax`` requests and continue to iterate - through the ``account_taxes`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` - 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[..., account_tax.ListAccountTaxResponse], - request: account_tax.ListAccountTaxRequest, - response: account_tax.ListAccountTaxResponse, - *, - 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_accounts_v1beta.types.ListAccountTaxRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse): - 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 = account_tax.ListAccountTaxRequest(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[account_tax.ListAccountTaxResponse]: - 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[account_tax.AccountTax]: - for page in self.pages: - yield from page.account_taxes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAccountTaxAsyncPager: - """A pager for iterating through ``list_account_tax`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``account_taxes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAccountTax`` requests and continue to iterate - through the ``account_taxes`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse` - 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[account_tax.ListAccountTaxResponse]], - request: account_tax.ListAccountTaxRequest, - response: account_tax.ListAccountTaxResponse, - *, - 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_accounts_v1beta.types.ListAccountTaxRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListAccountTaxResponse): - 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 = account_tax.ListAccountTaxRequest(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[account_tax.ListAccountTaxResponse]: - 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[account_tax.AccountTax]: - async def async_generator(): - async for page in self.pages: - for response in page.account_taxes: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst deleted file mode 100644 index 2af3997395a2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AccountTaxServiceTransport` is the ABC for all transports. -- public child `AccountTaxServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AccountTaxServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAccountTaxServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AccountTaxServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/__init__.py deleted file mode 100644 index 711e8a17de35..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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 AccountTaxServiceTransport -from .grpc import AccountTaxServiceGrpcTransport -from .grpc_asyncio import AccountTaxServiceGrpcAsyncIOTransport -from .rest import AccountTaxServiceRestTransport -from .rest import AccountTaxServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AccountTaxServiceTransport]] -_transport_registry['grpc'] = AccountTaxServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountTaxServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountTaxServiceRestTransport - -__all__ = ( - 'AccountTaxServiceTransport', - 'AccountTaxServiceGrpcTransport', - 'AccountTaxServiceGrpcAsyncIOTransport', - 'AccountTaxServiceRestTransport', - 'AccountTaxServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/base.py deleted file mode 100644 index 931f0d82550c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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_accounts_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.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax - -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 AccountTaxServiceTransport(abc.ABC): - """Abstract transport class for AccountTaxService.""" - - 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.get_account_tax: gapic_v1.method.wrap_method( - self.get_account_tax, - default_timeout=None, - client_info=client_info, - ), - self.list_account_tax: gapic_v1.method.wrap_method( - self.list_account_tax, - default_timeout=None, - client_info=client_info, - ), - self.update_account_tax: gapic_v1.method.wrap_method( - self.update_account_tax, - 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 get_account_tax(self) -> Callable[ - [account_tax.GetAccountTaxRequest], - Union[ - account_tax.AccountTax, - Awaitable[account_tax.AccountTax] - ]]: - raise NotImplementedError() - - @property - def list_account_tax(self) -> Callable[ - [account_tax.ListAccountTaxRequest], - Union[ - account_tax.ListAccountTaxResponse, - Awaitable[account_tax.ListAccountTaxResponse] - ]]: - raise NotImplementedError() - - @property - def update_account_tax(self) -> Callable[ - [gsma_account_tax.UpdateAccountTaxRequest], - Union[ - gsma_account_tax.AccountTax, - Awaitable[gsma_account_tax.AccountTax] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AccountTaxServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py deleted file mode 100644 index 376fe4e410da..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc.py +++ /dev/null @@ -1,407 +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.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax -from .base import AccountTaxServiceTransport, 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.accounts.v1beta.AccountTaxService", - "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.accounts.v1beta.AccountTaxService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AccountTaxServiceGrpcTransport(AccountTaxServiceTransport): - """gRPC backend transport for AccountTaxService. - - Manages account level tax setting data. - - This API defines the following resource model: - - - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] - - 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 get_account_tax(self) -> Callable[ - [account_tax.GetAccountTaxRequest], - account_tax.AccountTax]: - r"""Return a callable for the get account tax method over gRPC. - - Returns the tax rules that match the conditions of - GetAccountTaxRequest - - Returns: - Callable[[~.GetAccountTaxRequest], - ~.AccountTax]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_account_tax' not in self._stubs: - self._stubs['get_account_tax'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountTaxService/GetAccountTax', - request_serializer=account_tax.GetAccountTaxRequest.serialize, - response_deserializer=account_tax.AccountTax.deserialize, - ) - return self._stubs['get_account_tax'] - - @property - def list_account_tax(self) -> Callable[ - [account_tax.ListAccountTaxRequest], - account_tax.ListAccountTaxResponse]: - r"""Return a callable for the list account tax method over gRPC. - - Lists the tax settings of the sub-accounts only in - your Merchant Center account. - This method can only be called on a multi-client - account, otherwise it'll return an error. - - Returns: - Callable[[~.ListAccountTaxRequest], - ~.ListAccountTaxResponse]: - 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_account_tax' not in self._stubs: - self._stubs['list_account_tax'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountTaxService/ListAccountTax', - request_serializer=account_tax.ListAccountTaxRequest.serialize, - response_deserializer=account_tax.ListAccountTaxResponse.deserialize, - ) - return self._stubs['list_account_tax'] - - @property - def update_account_tax(self) -> Callable[ - [gsma_account_tax.UpdateAccountTaxRequest], - gsma_account_tax.AccountTax]: - r"""Return a callable for the update account tax method over gRPC. - - Updates the tax settings of the account. - - Returns: - Callable[[~.UpdateAccountTaxRequest], - ~.AccountTax]: - 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 'update_account_tax' not in self._stubs: - self._stubs['update_account_tax'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountTaxService/UpdateAccountTax', - request_serializer=gsma_account_tax.UpdateAccountTaxRequest.serialize, - response_deserializer=gsma_account_tax.AccountTax.deserialize, - ) - return self._stubs['update_account_tax'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AccountTaxServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py deleted file mode 100644 index c88371254b2e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,438 +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.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax -from .base import AccountTaxServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AccountTaxServiceGrpcTransport - -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.accounts.v1beta.AccountTaxService", - "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.accounts.v1beta.AccountTaxService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AccountTaxServiceGrpcAsyncIOTransport(AccountTaxServiceTransport): - """gRPC AsyncIO backend transport for AccountTaxService. - - Manages account level tax setting data. - - This API defines the following resource model: - - - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] - - 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 get_account_tax(self) -> Callable[ - [account_tax.GetAccountTaxRequest], - Awaitable[account_tax.AccountTax]]: - r"""Return a callable for the get account tax method over gRPC. - - Returns the tax rules that match the conditions of - GetAccountTaxRequest - - Returns: - Callable[[~.GetAccountTaxRequest], - Awaitable[~.AccountTax]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_account_tax' not in self._stubs: - self._stubs['get_account_tax'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountTaxService/GetAccountTax', - request_serializer=account_tax.GetAccountTaxRequest.serialize, - response_deserializer=account_tax.AccountTax.deserialize, - ) - return self._stubs['get_account_tax'] - - @property - def list_account_tax(self) -> Callable[ - [account_tax.ListAccountTaxRequest], - Awaitable[account_tax.ListAccountTaxResponse]]: - r"""Return a callable for the list account tax method over gRPC. - - Lists the tax settings of the sub-accounts only in - your Merchant Center account. - This method can only be called on a multi-client - account, otherwise it'll return an error. - - Returns: - Callable[[~.ListAccountTaxRequest], - Awaitable[~.ListAccountTaxResponse]]: - 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_account_tax' not in self._stubs: - self._stubs['list_account_tax'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountTaxService/ListAccountTax', - request_serializer=account_tax.ListAccountTaxRequest.serialize, - response_deserializer=account_tax.ListAccountTaxResponse.deserialize, - ) - return self._stubs['list_account_tax'] - - @property - def update_account_tax(self) -> Callable[ - [gsma_account_tax.UpdateAccountTaxRequest], - Awaitable[gsma_account_tax.AccountTax]]: - r"""Return a callable for the update account tax method over gRPC. - - Updates the tax settings of the account. - - Returns: - Callable[[~.UpdateAccountTaxRequest], - Awaitable[~.AccountTax]]: - 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 'update_account_tax' not in self._stubs: - self._stubs['update_account_tax'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountTaxService/UpdateAccountTax', - request_serializer=gsma_account_tax.UpdateAccountTaxRequest.serialize, - response_deserializer=gsma_account_tax.AccountTax.deserialize, - ) - return self._stubs['update_account_tax'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_account_tax: self._wrap_method( - self.get_account_tax, - default_timeout=None, - client_info=client_info, - ), - self.list_account_tax: self._wrap_method( - self.list_account_tax, - default_timeout=None, - client_info=client_info, - ), - self.update_account_tax: self._wrap_method( - self.update_account_tax, - 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__ = ( - 'AccountTaxServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py deleted file mode 100644 index 509d7cfbd17c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest.py +++ /dev/null @@ -1,715 +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.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax - - -from .rest_base import _BaseAccountTaxServiceRestTransport -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 AccountTaxServiceRestInterceptor: - """Interceptor for AccountTaxService. - - 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 AccountTaxServiceRestTransport. - - .. code-block:: python - class MyCustomAccountTaxServiceInterceptor(AccountTaxServiceRestInterceptor): - def pre_get_account_tax(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_account_tax(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_account_tax(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_account_tax(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_account_tax(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_account_tax(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AccountTaxServiceRestTransport(interceptor=MyCustomAccountTaxServiceInterceptor()) - client = AccountTaxServiceClient(transport=transport) - - - """ - def pre_get_account_tax(self, request: account_tax.GetAccountTaxRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.GetAccountTaxRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_account_tax - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountTaxService server. - """ - return request, metadata - - def post_get_account_tax(self, response: account_tax.AccountTax) -> account_tax.AccountTax: - """Post-rpc interceptor for get_account_tax - - DEPRECATED. Please use the `post_get_account_tax_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountTaxService server but before - it is returned to user code. This `post_get_account_tax` interceptor runs - before the `post_get_account_tax_with_metadata` interceptor. - """ - return response - - def post_get_account_tax_with_metadata(self, response: account_tax.AccountTax, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.AccountTax, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_account_tax - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountTaxService server but before it is returned to user code. - - We recommend only using this `post_get_account_tax_with_metadata` - interceptor in new development instead of the `post_get_account_tax` interceptor. - When both interceptors are used, this `post_get_account_tax_with_metadata` interceptor runs after the - `post_get_account_tax` interceptor. The (possibly modified) response returned by - `post_get_account_tax` will be passed to - `post_get_account_tax_with_metadata`. - """ - return response, metadata - - def pre_list_account_tax(self, request: account_tax.ListAccountTaxRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.ListAccountTaxRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_account_tax - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountTaxService server. - """ - return request, metadata - - def post_list_account_tax(self, response: account_tax.ListAccountTaxResponse) -> account_tax.ListAccountTaxResponse: - """Post-rpc interceptor for list_account_tax - - DEPRECATED. Please use the `post_list_account_tax_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountTaxService server but before - it is returned to user code. This `post_list_account_tax` interceptor runs - before the `post_list_account_tax_with_metadata` interceptor. - """ - return response - - def post_list_account_tax_with_metadata(self, response: account_tax.ListAccountTaxResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[account_tax.ListAccountTaxResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_account_tax - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountTaxService server but before it is returned to user code. - - We recommend only using this `post_list_account_tax_with_metadata` - interceptor in new development instead of the `post_list_account_tax` interceptor. - When both interceptors are used, this `post_list_account_tax_with_metadata` interceptor runs after the - `post_list_account_tax` interceptor. The (possibly modified) response returned by - `post_list_account_tax` will be passed to - `post_list_account_tax_with_metadata`. - """ - return response, metadata - - def pre_update_account_tax(self, request: gsma_account_tax.UpdateAccountTaxRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_account_tax.UpdateAccountTaxRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_account_tax - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountTaxService server. - """ - return request, metadata - - def post_update_account_tax(self, response: gsma_account_tax.AccountTax) -> gsma_account_tax.AccountTax: - """Post-rpc interceptor for update_account_tax - - DEPRECATED. Please use the `post_update_account_tax_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountTaxService server but before - it is returned to user code. This `post_update_account_tax` interceptor runs - before the `post_update_account_tax_with_metadata` interceptor. - """ - return response - - def post_update_account_tax_with_metadata(self, response: gsma_account_tax.AccountTax, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_account_tax.AccountTax, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_account_tax - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountTaxService server but before it is returned to user code. - - We recommend only using this `post_update_account_tax_with_metadata` - interceptor in new development instead of the `post_update_account_tax` interceptor. - When both interceptors are used, this `post_update_account_tax_with_metadata` interceptor runs after the - `post_update_account_tax` interceptor. The (possibly modified) response returned by - `post_update_account_tax` will be passed to - `post_update_account_tax_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class AccountTaxServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AccountTaxServiceRestInterceptor - - -class AccountTaxServiceRestTransport(_BaseAccountTaxServiceRestTransport): - """REST backend synchronous transport for AccountTaxService. - - Manages account level tax setting data. - - This API defines the following resource model: - - - [AccountTax][google.shopping.merchant.accounts.v1main.AccountTax] - - 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[AccountTaxServiceRestInterceptor] = 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 AccountTaxServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetAccountTax(_BaseAccountTaxServiceRestTransport._BaseGetAccountTax, AccountTaxServiceRestStub): - def __hash__(self): - return hash("AccountTaxServiceRestTransport.GetAccountTax") - - @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: account_tax.GetAccountTaxRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> account_tax.AccountTax: - r"""Call the get account tax method over HTTP. - - Args: - request (~.account_tax.GetAccountTaxRequest): - The request object. Request to get tax settings - 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: - ~.account_tax.AccountTax: - The tax settings of a merchant - account. All methods require the admin - role. - - """ - - http_options = _BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_http_options() - - request, metadata = self._interceptor.pre_get_account_tax(request, metadata) - transcoded_request = _BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountTaxServiceClient.GetAccountTax", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "rpcName": "GetAccountTax", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountTaxServiceRestTransport._GetAccountTax._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 = account_tax.AccountTax() - pb_resp = account_tax.AccountTax.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_account_tax(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_account_tax_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = account_tax.AccountTax.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.accounts_v1beta.AccountTaxServiceClient.get_account_tax", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "rpcName": "GetAccountTax", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAccountTax(_BaseAccountTaxServiceRestTransport._BaseListAccountTax, AccountTaxServiceRestStub): - def __hash__(self): - return hash("AccountTaxServiceRestTransport.ListAccountTax") - - @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: account_tax.ListAccountTaxRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> account_tax.ListAccountTaxResponse: - r"""Call the list account tax method over HTTP. - - Args: - request (~.account_tax.ListAccountTaxRequest): - The request object. Request to list all sub-account tax - settings only for the requesting - merchant This method can only be called - on a multi-client account, otherwise - it'll return an error. - 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: - ~.account_tax.ListAccountTaxResponse: - Response to account tax list request - This method can only be called on a - multi-client account, otherwise it'll - return an error. - - """ - - http_options = _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_http_options() - - request, metadata = self._interceptor.pre_list_account_tax(request, metadata) - transcoded_request = _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountTaxServiceClient.ListAccountTax", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "rpcName": "ListAccountTax", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountTaxServiceRestTransport._ListAccountTax._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 = account_tax.ListAccountTaxResponse() - pb_resp = account_tax.ListAccountTaxResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_account_tax(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_account_tax_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = account_tax.ListAccountTaxResponse.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.accounts_v1beta.AccountTaxServiceClient.list_account_tax", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "rpcName": "ListAccountTax", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAccountTax(_BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax, AccountTaxServiceRestStub): - def __hash__(self): - return hash("AccountTaxServiceRestTransport.UpdateAccountTax") - - @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: gsma_account_tax.UpdateAccountTaxRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_account_tax.AccountTax: - r"""Call the update account tax method over HTTP. - - Args: - request (~.gsma_account_tax.UpdateAccountTaxRequest): - The request object. Request to update the tax settings - 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: - ~.gsma_account_tax.AccountTax: - The tax settings of a merchant - account. All methods require the admin - role. - - """ - - http_options = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_http_options() - - request, metadata = self._interceptor.pre_update_account_tax(request, metadata) - transcoded_request = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_transcoded_request(http_options, request) - - body = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountTaxServiceClient.UpdateAccountTax", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "rpcName": "UpdateAccountTax", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountTaxServiceRestTransport._UpdateAccountTax._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 = gsma_account_tax.AccountTax() - pb_resp = gsma_account_tax.AccountTax.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_account_tax(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_account_tax_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gsma_account_tax.AccountTax.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.accounts_v1beta.AccountTaxServiceClient.update_account_tax", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "rpcName": "UpdateAccountTax", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_account_tax(self) -> Callable[ - [account_tax.GetAccountTaxRequest], - account_tax.AccountTax]: - # 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._GetAccountTax(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_account_tax(self) -> Callable[ - [account_tax.ListAccountTaxRequest], - account_tax.ListAccountTaxResponse]: - # 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._ListAccountTax(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_account_tax(self) -> Callable[ - [gsma_account_tax.UpdateAccountTaxRequest], - gsma_account_tax.AccountTax]: - # 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._UpdateAccountTax(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AccountTaxServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_service/transports/rest_base.py deleted file mode 100644 index a893ddd9af6c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/account_tax_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 AccountTaxServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax - - -class _BaseAccountTaxServiceRestTransport(AccountTaxServiceTransport): - """Base REST backend transport for AccountTaxService. - - 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 _BaseGetAccountTax: - 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': '/accounts/v1beta/{name=accounts/*/accounttax/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = account_tax.GetAccountTaxRequest.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(_BaseAccountTaxServiceRestTransport._BaseGetAccountTax._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListAccountTax: - 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': '/accounts/v1beta/{parent=accounts/*}/accounttax', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = account_tax.ListAccountTaxRequest.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(_BaseAccountTaxServiceRestTransport._BaseListAccountTax._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateAccountTax: - 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': 'patch', - 'uri': '/accounts/v1beta/{account_tax.name=accounts/*/accounttax/*}', - 'body': 'account_tax', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gsma_account_tax.UpdateAccountTaxRequest.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(_BaseAccountTaxServiceRestTransport._BaseUpdateAccountTax._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAccountTaxServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py deleted file mode 100644 index 1b0e8912aa4c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/async_client.py +++ /dev/null @@ -1,894 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.accounts_service import pagers -from google.shopping.merchant_accounts_v1beta.types import accounts -from google.type import datetime_pb2 # type: ignore -from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport -from .client import AccountsServiceClient - -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 AccountsServiceAsyncClient: - """Service to support Accounts API.""" - - _client: AccountsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AccountsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AccountsServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(AccountsServiceClient.account_path) - parse_account_path = staticmethod(AccountsServiceClient.parse_account_path) - terms_of_service_path = staticmethod(AccountsServiceClient.terms_of_service_path) - parse_terms_of_service_path = staticmethod(AccountsServiceClient.parse_terms_of_service_path) - user_path = staticmethod(AccountsServiceClient.user_path) - parse_user_path = staticmethod(AccountsServiceClient.parse_user_path) - common_billing_account_path = staticmethod(AccountsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AccountsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AccountsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountsServiceClient.parse_common_project_path) - common_location_path = staticmethod(AccountsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountsServiceClient.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: - AccountsServiceAsyncClient: The constructed client. - """ - return AccountsServiceClient.from_service_account_info.__func__(AccountsServiceAsyncClient, 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: - AccountsServiceAsyncClient: The constructed client. - """ - return AccountsServiceClient.from_service_account_file.__func__(AccountsServiceAsyncClient, 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 AccountsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AccountsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AccountsServiceTransport: 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 = AccountsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the accounts 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,AccountsServiceTransport,Callable[..., AccountsServiceTransport]]]): - 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 AccountsServiceTransport 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 = AccountsServiceClient( - 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.accounts_v1beta.AccountsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "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.accounts.v1beta.AccountsService", - "credentialsType": None, - } - ) - - async def get_account(self, - request: Optional[Union[accounts.GetAccountRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: - r"""Retrieves an account from your Merchant Center - account. After inserting, updating, or deleting an - account, it may take several minutes before changes take - effect. - - .. 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_accounts_v1beta - - async def sample_get_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountRequest( - name="name_value", - ) - - # Make the request - response = await client.get_account(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAccountRequest, dict]]): - The request object. Request message for the ``GetAccount`` method. - name (:class:`str`): - Required. The name of the account to retrieve. Format: - ``accounts/{account}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Account: - An account. - """ - # 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, accounts.GetAccountRequest): - request = accounts.GetAccountRequest(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.get_account] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_and_configure_account(self, - request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: - r"""Creates a standalone Merchant Center account with - additional configuration. Adds the user that makes the - request as an admin for the new 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_accounts_v1beta - - async def sample_create_and_configure_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( - account=account, - ) - - # Make the request - response = await client.create_and_configure_account(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest, dict]]): - The request object. Request message for the ``CreateAndConfigureAccount`` - 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_accounts_v1beta.types.Account: - An account. - """ - # 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, accounts.CreateAndConfigureAccountRequest): - request = accounts.CreateAndConfigureAccountRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_and_configure_account] - - # 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_account(self, - request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, - *, - name: 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 account regardless of its type: - standalone, MCA or sub-account. Deleting an MCA leads to the - deletion of all of its sub-accounts. Executing this method - requires admin access. The deletion succeeds only if the account - does not provide services to any other account and has no - processed offers. You can use the ``force`` parameter to - override this. - - .. 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_accounts_v1beta - - async def sample_delete_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteAccountRequest( - name="name_value", - ) - - # Make the request - await client.delete_account(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest, dict]]): - The request object. Request message for the ``DeleteAccount`` method. - name (:class:`str`): - Required. The name of the account to delete. Format: - ``accounts/{account}`` - - 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, accounts.DeleteAccountRequest): - request = accounts.DeleteAccountRequest(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_account] - - # 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 update_account(self, - request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, - *, - account: Optional[accounts.Account] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: - r"""Updates an account regardless of its type: - standalone, MCA or sub-account. Executing this method - requires admin access. - - .. 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_accounts_v1beta - - async def sample_update_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.UpdateAccountRequest( - account=account, - ) - - # Make the request - response = await client.update_account(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest, dict]]): - The request object. Request message for the ``UpdateAccount`` method. - account (:class:`google.shopping.merchant_accounts_v1beta.types.Account`): - Required. The new version of the - account. - - This corresponds to the ``account`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Account: - An account. - """ - # 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 = [account, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, accounts.UpdateAccountRequest): - request = accounts.UpdateAccountRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if account is not None: - request.account = account - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_account] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account.name", request.account.name), - )), - ) - - # 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 list_accounts(self, - request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAccountsAsyncPager: - r"""Lists accounts accessible to the calling user and - matching the constraints of the request such as page - size or filters. This is not just listing the - sub-accounts of an MCA, but all accounts the calling - user has access to including other MCAs, linked - accounts, standalone accounts and so on. If no filter is - provided, then it returns accounts the user is directly - added to. - - .. 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_accounts_v1beta - - async def sample_list_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountsRequest( - ) - - # Make the request - page_result = client.list_accounts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest, dict]]): - The request object. Request message for the ``ListAccounts`` 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_accounts_v1beta.services.accounts_service.pagers.ListAccountsAsyncPager: - Response message for the ListAccounts method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # 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, accounts.ListAccountsRequest): - request = accounts.ListAccountsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_accounts] - - # 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.ListAccountsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sub_accounts(self, - request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, - *, - provider: 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.ListSubAccountsAsyncPager: - r"""List all sub-accounts for a given multi client account. This is - a convenience wrapper for the more powerful ``ListAccounts`` - method. This method will produce the same results as calling - ``ListsAccounts`` with the following filter: - ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` - - .. 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_accounts_v1beta - - async def sample_list_sub_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListSubAccountsRequest( - provider="provider_value", - ) - - # Make the request - page_result = client.list_sub_accounts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest, dict]]): - The request object. Request message for the ``ListSubAccounts`` method. - provider (:class:`str`): - Required. The parent account. Format: - ``accounts/{account}`` - - This corresponds to the ``provider`` 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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsAsyncPager: - Response message for the ListSubAccounts 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 = [provider] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, accounts.ListSubAccountsRequest): - request = accounts.ListSubAccountsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if provider is not None: - request.provider = provider - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_sub_accounts] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("provider", request.provider), - )), - ) - - # 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.ListSubAccountsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "AccountsServiceAsyncClient": - 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__ = ( - "AccountsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py deleted file mode 100644 index a2c5064fc494..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/client.py +++ /dev/null @@ -1,1269 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.accounts_service import pagers -from google.shopping.merchant_accounts_v1beta.types import accounts -from google.type import datetime_pb2 # type: ignore -from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AccountsServiceGrpcTransport -from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport -from .transports.rest import AccountsServiceRestTransport - - -class AccountsServiceClientMeta(type): - """Metaclass for the AccountsService 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[AccountsServiceTransport]] - _transport_registry["grpc"] = AccountsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AccountsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AccountsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountsServiceTransport]: - """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 AccountsServiceClient(metaclass=AccountsServiceClientMeta): - """Service to support Accounts API.""" - - @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: - AccountsServiceClient: 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: - AccountsServiceClient: 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) -> AccountsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AccountsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def terms_of_service_path(version: str,) -> str: - """Returns a fully-qualified terms_of_service string.""" - return "termsOfService/{version}".format(version=version, ) - - @staticmethod - def parse_terms_of_service_path(path: str) -> Dict[str,str]: - """Parses a terms_of_service path into its component segments.""" - m = re.match(r"^termsOfService/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_path(account: str,email: str,) -> str: - """Returns a fully-qualified user string.""" - return "accounts/{account}/users/{email}".format(account=account, email=email, ) - - @staticmethod - def parse_user_path(path: str) -> Dict[str,str]: - """Parses a user path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/users/(?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 = AccountsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AccountsServiceClient._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 = AccountsServiceClient._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, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the accounts 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,AccountsServiceTransport,Callable[..., AccountsServiceTransport]]]): - 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 AccountsServiceTransport 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 = AccountsServiceClient._read_environment_variables() - self._client_cert_source = AccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountsServiceClient._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, AccountsServiceTransport) - if transport_provided: - # transport is a AccountsServiceTransport 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(AccountsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AccountsServiceClient._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[AccountsServiceTransport], Callable[..., AccountsServiceTransport]] = ( - AccountsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AccountsServiceTransport], 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.accounts_v1beta.AccountsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "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.accounts.v1beta.AccountsService", - "credentialsType": None, - } - ) - - def get_account(self, - request: Optional[Union[accounts.GetAccountRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: - r"""Retrieves an account from your Merchant Center - account. After inserting, updating, or deleting an - account, it may take several minutes before changes take - effect. - - .. 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_accounts_v1beta - - def sample_get_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountRequest( - name="name_value", - ) - - # Make the request - response = client.get_account(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetAccountRequest, dict]): - The request object. Request message for the ``GetAccount`` method. - name (str): - Required. The name of the account to retrieve. Format: - ``accounts/{account}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Account: - An account. - """ - # 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, accounts.GetAccountRequest): - request = accounts.GetAccountRequest(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.get_account] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_and_configure_account(self, - request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: - r"""Creates a standalone Merchant Center account with - additional configuration. Adds the user that makes the - request as an admin for the new 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_accounts_v1beta - - def sample_create_and_configure_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( - account=account, - ) - - # Make the request - response = client.create_and_configure_account(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest, dict]): - The request object. Request message for the ``CreateAndConfigureAccount`` - 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_accounts_v1beta.types.Account: - An account. - """ - # 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, accounts.CreateAndConfigureAccountRequest): - request = accounts.CreateAndConfigureAccountRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_and_configure_account] - - # 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_account(self, - request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, - *, - name: 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 account regardless of its type: - standalone, MCA or sub-account. Deleting an MCA leads to the - deletion of all of its sub-accounts. Executing this method - requires admin access. The deletion succeeds only if the account - does not provide services to any other account and has no - processed offers. You can use the ``force`` parameter to - override this. - - .. 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_accounts_v1beta - - def sample_delete_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteAccountRequest( - name="name_value", - ) - - # Make the request - client.delete_account(request=request) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest, dict]): - The request object. Request message for the ``DeleteAccount`` method. - name (str): - Required. The name of the account to delete. Format: - ``accounts/{account}`` - - 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, accounts.DeleteAccountRequest): - request = accounts.DeleteAccountRequest(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_account] - - # 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 update_account(self, - request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, - *, - account: Optional[accounts.Account] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: - r"""Updates an account regardless of its type: - standalone, MCA or sub-account. Executing this method - requires admin access. - - .. 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_accounts_v1beta - - def sample_update_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.UpdateAccountRequest( - account=account, - ) - - # Make the request - response = client.update_account(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest, dict]): - The request object. Request message for the ``UpdateAccount`` method. - account (google.shopping.merchant_accounts_v1beta.types.Account): - Required. The new version of the - account. - - This corresponds to the ``account`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Account: - An account. - """ - # 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 = [account, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, accounts.UpdateAccountRequest): - request = accounts.UpdateAccountRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if account is not None: - request.account = account - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_account] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account.name", request.account.name), - )), - ) - - # 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 list_accounts(self, - request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAccountsPager: - r"""Lists accounts accessible to the calling user and - matching the constraints of the request such as page - size or filters. This is not just listing the - sub-accounts of an MCA, but all accounts the calling - user has access to including other MCAs, linked - accounts, standalone accounts and so on. If no filter is - provided, then it returns accounts the user is directly - added to. - - .. 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_accounts_v1beta - - def sample_list_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountsRequest( - ) - - # Make the request - page_result = client.list_accounts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest, dict]): - The request object. Request message for the ``ListAccounts`` 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_accounts_v1beta.services.accounts_service.pagers.ListAccountsPager: - Response message for the ListAccounts method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # 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, accounts.ListAccountsRequest): - request = accounts.ListAccountsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_accounts] - - # 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.ListAccountsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sub_accounts(self, - request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, - *, - provider: 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.ListSubAccountsPager: - r"""List all sub-accounts for a given multi client account. This is - a convenience wrapper for the more powerful ``ListAccounts`` - method. This method will produce the same results as calling - ``ListsAccounts`` with the following filter: - ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` - - .. 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_accounts_v1beta - - def sample_list_sub_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListSubAccountsRequest( - provider="provider_value", - ) - - # Make the request - page_result = client.list_sub_accounts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest, dict]): - The request object. Request message for the ``ListSubAccounts`` method. - provider (str): - Required. The parent account. Format: - ``accounts/{account}`` - - This corresponds to the ``provider`` 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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsPager: - Response message for the ListSubAccounts 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 = [provider] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, accounts.ListSubAccountsRequest): - request = accounts.ListSubAccountsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if provider is not None: - request.provider = provider - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_sub_accounts] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("provider", request.provider), - )), - ) - - # 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.ListSubAccountsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AccountsServiceClient": - 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__ = ( - "AccountsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py deleted file mode 100644 index de54451b9ec5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/pagers.py +++ /dev/null @@ -1,305 +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_accounts_v1beta.types import accounts - - -class ListAccountsPager: - """A pager for iterating through ``list_accounts`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``accounts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAccounts`` requests and continue to iterate - through the ``accounts`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` - 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[..., accounts.ListAccountsResponse], - request: accounts.ListAccountsRequest, - response: accounts.ListAccountsResponse, - *, - 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_accounts_v1beta.types.ListAccountsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse): - 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 = accounts.ListAccountsRequest(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[accounts.ListAccountsResponse]: - 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[accounts.Account]: - for page in self.pages: - yield from page.accounts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAccountsAsyncPager: - """A pager for iterating through ``list_accounts`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``accounts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAccounts`` requests and continue to iterate - through the ``accounts`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse` - 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[accounts.ListAccountsResponse]], - request: accounts.ListAccountsRequest, - response: accounts.ListAccountsResponse, - *, - 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_accounts_v1beta.types.ListAccountsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListAccountsResponse): - 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 = accounts.ListAccountsRequest(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[accounts.ListAccountsResponse]: - 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[accounts.Account]: - async def async_generator(): - async for page in self.pages: - for response in page.accounts: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSubAccountsPager: - """A pager for iterating through ``list_sub_accounts`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``accounts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSubAccounts`` requests and continue to iterate - through the ``accounts`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` - 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[..., accounts.ListSubAccountsResponse], - request: accounts.ListSubAccountsRequest, - response: accounts.ListSubAccountsResponse, - *, - 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_accounts_v1beta.types.ListSubAccountsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse): - 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 = accounts.ListSubAccountsRequest(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[accounts.ListSubAccountsResponse]: - 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[accounts.Account]: - for page in self.pages: - yield from page.accounts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSubAccountsAsyncPager: - """A pager for iterating through ``list_sub_accounts`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``accounts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSubAccounts`` requests and continue to iterate - through the ``accounts`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse` - 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[accounts.ListSubAccountsResponse]], - request: accounts.ListSubAccountsRequest, - response: accounts.ListSubAccountsResponse, - *, - 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_accounts_v1beta.types.ListSubAccountsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListSubAccountsResponse): - 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 = accounts.ListSubAccountsRequest(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[accounts.ListSubAccountsResponse]: - 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[accounts.Account]: - async def async_generator(): - async for page in self.pages: - for response in page.accounts: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst deleted file mode 100644 index feb9cc900a04..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AccountsServiceTransport` is the ABC for all transports. -- public child `AccountsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AccountsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAccountsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AccountsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py deleted file mode 100644 index 7b7b63ee46fa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/base.py +++ /dev/null @@ -1,230 +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_accounts_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_accounts_v1beta.types import accounts - -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 AccountsServiceTransport(abc.ABC): - """Abstract transport class for AccountsService.""" - - 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.get_account: gapic_v1.method.wrap_method( - self.get_account, - default_timeout=None, - client_info=client_info, - ), - self.create_and_configure_account: gapic_v1.method.wrap_method( - self.create_and_configure_account, - default_timeout=None, - client_info=client_info, - ), - self.delete_account: gapic_v1.method.wrap_method( - self.delete_account, - default_timeout=None, - client_info=client_info, - ), - self.update_account: gapic_v1.method.wrap_method( - self.update_account, - default_timeout=None, - client_info=client_info, - ), - self.list_accounts: gapic_v1.method.wrap_method( - self.list_accounts, - default_timeout=None, - client_info=client_info, - ), - self.list_sub_accounts: gapic_v1.method.wrap_method( - self.list_sub_accounts, - 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 get_account(self) -> Callable[ - [accounts.GetAccountRequest], - Union[ - accounts.Account, - Awaitable[accounts.Account] - ]]: - raise NotImplementedError() - - @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - Union[ - accounts.Account, - Awaitable[accounts.Account] - ]]: - raise NotImplementedError() - - @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - Union[ - accounts.Account, - Awaitable[accounts.Account] - ]]: - raise NotImplementedError() - - @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - Union[ - accounts.ListAccountsResponse, - Awaitable[accounts.ListAccountsResponse] - ]]: - raise NotImplementedError() - - @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - Union[ - accounts.ListSubAccountsResponse, - Awaitable[accounts.ListSubAccountsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AccountsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py deleted file mode 100644 index de3e2f9ab401..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc.py +++ /dev/null @@ -1,501 +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_accounts_v1beta.types import accounts -from .base import AccountsServiceTransport, 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.accounts.v1beta.AccountsService", - "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.accounts.v1beta.AccountsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AccountsServiceGrpcTransport(AccountsServiceTransport): - """gRPC backend transport for AccountsService. - - Service to support Accounts API. - - 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 get_account(self) -> Callable[ - [accounts.GetAccountRequest], - accounts.Account]: - r"""Return a callable for the get account method over gRPC. - - Retrieves an account from your Merchant Center - account. After inserting, updating, or deleting an - account, it may take several minutes before changes take - effect. - - Returns: - Callable[[~.GetAccountRequest], - ~.Account]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_account' not in self._stubs: - self._stubs['get_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/GetAccount', - request_serializer=accounts.GetAccountRequest.serialize, - response_deserializer=accounts.Account.deserialize, - ) - return self._stubs['get_account'] - - @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - accounts.Account]: - r"""Return a callable for the create and configure account method over gRPC. - - Creates a standalone Merchant Center account with - additional configuration. Adds the user that makes the - request as an admin for the new account. - - Returns: - Callable[[~.CreateAndConfigureAccountRequest], - ~.Account]: - 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 'create_and_configure_account' not in self._stubs: - self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/CreateAndConfigureAccount', - request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, - response_deserializer=accounts.Account.deserialize, - ) - return self._stubs['create_and_configure_account'] - - @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete account method over gRPC. - - Deletes the specified account regardless of its type: - standalone, MCA or sub-account. Deleting an MCA leads to the - deletion of all of its sub-accounts. Executing this method - requires admin access. The deletion succeeds only if the account - does not provide services to any other account and has no - processed offers. You can use the ``force`` parameter to - override this. - - Returns: - Callable[[~.DeleteAccountRequest], - ~.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_account' not in self._stubs: - self._stubs['delete_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/DeleteAccount', - request_serializer=accounts.DeleteAccountRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_account'] - - @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - accounts.Account]: - r"""Return a callable for the update account method over gRPC. - - Updates an account regardless of its type: - standalone, MCA or sub-account. Executing this method - requires admin access. - - Returns: - Callable[[~.UpdateAccountRequest], - ~.Account]: - 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 'update_account' not in self._stubs: - self._stubs['update_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/UpdateAccount', - request_serializer=accounts.UpdateAccountRequest.serialize, - response_deserializer=accounts.Account.deserialize, - ) - return self._stubs['update_account'] - - @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - accounts.ListAccountsResponse]: - r"""Return a callable for the list accounts method over gRPC. - - Lists accounts accessible to the calling user and - matching the constraints of the request such as page - size or filters. This is not just listing the - sub-accounts of an MCA, but all accounts the calling - user has access to including other MCAs, linked - accounts, standalone accounts and so on. If no filter is - provided, then it returns accounts the user is directly - added to. - - Returns: - Callable[[~.ListAccountsRequest], - ~.ListAccountsResponse]: - 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_accounts' not in self._stubs: - self._stubs['list_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/ListAccounts', - request_serializer=accounts.ListAccountsRequest.serialize, - response_deserializer=accounts.ListAccountsResponse.deserialize, - ) - return self._stubs['list_accounts'] - - @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - accounts.ListSubAccountsResponse]: - r"""Return a callable for the list sub accounts method over gRPC. - - List all sub-accounts for a given multi client account. This is - a convenience wrapper for the more powerful ``ListAccounts`` - method. This method will produce the same results as calling - ``ListsAccounts`` with the following filter: - ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` - - Returns: - Callable[[~.ListSubAccountsRequest], - ~.ListSubAccountsResponse]: - 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_sub_accounts' not in self._stubs: - self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/ListSubAccounts', - request_serializer=accounts.ListSubAccountsRequest.serialize, - response_deserializer=accounts.ListSubAccountsResponse.deserialize, - ) - return self._stubs['list_sub_accounts'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AccountsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py deleted file mode 100644 index 6cf2cf6fff4d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,547 +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_accounts_v1beta.types import accounts -from .base import AccountsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AccountsServiceGrpcTransport - -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.accounts.v1beta.AccountsService", - "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.accounts.v1beta.AccountsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AccountsServiceGrpcAsyncIOTransport(AccountsServiceTransport): - """gRPC AsyncIO backend transport for AccountsService. - - Service to support Accounts API. - - 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 get_account(self) -> Callable[ - [accounts.GetAccountRequest], - Awaitable[accounts.Account]]: - r"""Return a callable for the get account method over gRPC. - - Retrieves an account from your Merchant Center - account. After inserting, updating, or deleting an - account, it may take several minutes before changes take - effect. - - Returns: - Callable[[~.GetAccountRequest], - Awaitable[~.Account]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_account' not in self._stubs: - self._stubs['get_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/GetAccount', - request_serializer=accounts.GetAccountRequest.serialize, - response_deserializer=accounts.Account.deserialize, - ) - return self._stubs['get_account'] - - @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - Awaitable[accounts.Account]]: - r"""Return a callable for the create and configure account method over gRPC. - - Creates a standalone Merchant Center account with - additional configuration. Adds the user that makes the - request as an admin for the new account. - - Returns: - Callable[[~.CreateAndConfigureAccountRequest], - Awaitable[~.Account]]: - 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 'create_and_configure_account' not in self._stubs: - self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/CreateAndConfigureAccount', - request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, - response_deserializer=accounts.Account.deserialize, - ) - return self._stubs['create_and_configure_account'] - - @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete account method over gRPC. - - Deletes the specified account regardless of its type: - standalone, MCA or sub-account. Deleting an MCA leads to the - deletion of all of its sub-accounts. Executing this method - requires admin access. The deletion succeeds only if the account - does not provide services to any other account and has no - processed offers. You can use the ``force`` parameter to - override this. - - Returns: - Callable[[~.DeleteAccountRequest], - 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_account' not in self._stubs: - self._stubs['delete_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/DeleteAccount', - request_serializer=accounts.DeleteAccountRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_account'] - - @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - Awaitable[accounts.Account]]: - r"""Return a callable for the update account method over gRPC. - - Updates an account regardless of its type: - standalone, MCA or sub-account. Executing this method - requires admin access. - - Returns: - Callable[[~.UpdateAccountRequest], - Awaitable[~.Account]]: - 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 'update_account' not in self._stubs: - self._stubs['update_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/UpdateAccount', - request_serializer=accounts.UpdateAccountRequest.serialize, - response_deserializer=accounts.Account.deserialize, - ) - return self._stubs['update_account'] - - @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - Awaitable[accounts.ListAccountsResponse]]: - r"""Return a callable for the list accounts method over gRPC. - - Lists accounts accessible to the calling user and - matching the constraints of the request such as page - size or filters. This is not just listing the - sub-accounts of an MCA, but all accounts the calling - user has access to including other MCAs, linked - accounts, standalone accounts and so on. If no filter is - provided, then it returns accounts the user is directly - added to. - - Returns: - Callable[[~.ListAccountsRequest], - Awaitable[~.ListAccountsResponse]]: - 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_accounts' not in self._stubs: - self._stubs['list_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/ListAccounts', - request_serializer=accounts.ListAccountsRequest.serialize, - response_deserializer=accounts.ListAccountsResponse.deserialize, - ) - return self._stubs['list_accounts'] - - @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - Awaitable[accounts.ListSubAccountsResponse]]: - r"""Return a callable for the list sub accounts method over gRPC. - - List all sub-accounts for a given multi client account. This is - a convenience wrapper for the more powerful ``ListAccounts`` - method. This method will produce the same results as calling - ``ListsAccounts`` with the following filter: - ``relationship(providerId={parent} AND service(type="ACCOUNT_AGGREGATION"))`` - - Returns: - Callable[[~.ListSubAccountsRequest], - Awaitable[~.ListSubAccountsResponse]]: - 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_sub_accounts' not in self._stubs: - self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AccountsService/ListSubAccounts', - request_serializer=accounts.ListSubAccountsRequest.serialize, - response_deserializer=accounts.ListSubAccountsResponse.deserialize, - ) - return self._stubs['list_sub_accounts'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_account: self._wrap_method( - self.get_account, - default_timeout=None, - client_info=client_info, - ), - self.create_and_configure_account: self._wrap_method( - self.create_and_configure_account, - default_timeout=None, - client_info=client_info, - ), - self.delete_account: self._wrap_method( - self.delete_account, - default_timeout=None, - client_info=client_info, - ), - self.update_account: self._wrap_method( - self.update_account, - default_timeout=None, - client_info=client_info, - ), - self.list_accounts: self._wrap_method( - self.list_accounts, - default_timeout=None, - client_info=client_info, - ), - self.list_sub_accounts: self._wrap_method( - self.list_sub_accounts, - 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__ = ( - 'AccountsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py deleted file mode 100644 index 6f0c86176ba0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest.py +++ /dev/null @@ -1,1149 +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_accounts_v1beta.types import accounts - - -from .rest_base import _BaseAccountsServiceRestTransport -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 AccountsServiceRestInterceptor: - """Interceptor for AccountsService. - - 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 AccountsServiceRestTransport. - - .. code-block:: python - class MyCustomAccountsServiceInterceptor(AccountsServiceRestInterceptor): - def pre_create_and_configure_account(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_and_configure_account(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_account(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_account(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_account(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_accounts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_accounts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_sub_accounts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_sub_accounts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_account(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_account(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AccountsServiceRestTransport(interceptor=MyCustomAccountsServiceInterceptor()) - client = AccountsServiceClient(transport=transport) - - - """ - def pre_create_and_configure_account(self, request: accounts.CreateAndConfigureAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_and_configure_account - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountsService server. - """ - return request, metadata - - def post_create_and_configure_account(self, response: accounts.Account) -> accounts.Account: - """Post-rpc interceptor for create_and_configure_account - - DEPRECATED. Please use the `post_create_and_configure_account_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. This `post_create_and_configure_account` interceptor runs - before the `post_create_and_configure_account_with_metadata` interceptor. - """ - return response - - def post_create_and_configure_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_and_configure_account - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountsService server but before it is returned to user code. - - We recommend only using this `post_create_and_configure_account_with_metadata` - interceptor in new development instead of the `post_create_and_configure_account` interceptor. - When both interceptors are used, this `post_create_and_configure_account_with_metadata` interceptor runs after the - `post_create_and_configure_account` interceptor. The (possibly modified) response returned by - `post_create_and_configure_account` will be passed to - `post_create_and_configure_account_with_metadata`. - """ - return response, metadata - - def pre_delete_account(self, request: accounts.DeleteAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_account - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountsService server. - """ - return request, metadata - - def pre_get_account(self, request: accounts.GetAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_account - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountsService server. - """ - return request, metadata - - def post_get_account(self, response: accounts.Account) -> accounts.Account: - """Post-rpc interceptor for get_account - - DEPRECATED. Please use the `post_get_account_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. This `post_get_account` interceptor runs - before the `post_get_account_with_metadata` interceptor. - """ - return response - - def post_get_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_account - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountsService server but before it is returned to user code. - - We recommend only using this `post_get_account_with_metadata` - interceptor in new development instead of the `post_get_account` interceptor. - When both interceptors are used, this `post_get_account_with_metadata` interceptor runs after the - `post_get_account` interceptor. The (possibly modified) response returned by - `post_get_account` will be passed to - `post_get_account_with_metadata`. - """ - return response, metadata - - def pre_list_accounts(self, request: accounts.ListAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_accounts - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountsService server. - """ - return request, metadata - - def post_list_accounts(self, response: accounts.ListAccountsResponse) -> accounts.ListAccountsResponse: - """Post-rpc interceptor for list_accounts - - DEPRECATED. Please use the `post_list_accounts_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. This `post_list_accounts` interceptor runs - before the `post_list_accounts_with_metadata` interceptor. - """ - return response - - def post_list_accounts_with_metadata(self, response: accounts.ListAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_accounts - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountsService server but before it is returned to user code. - - We recommend only using this `post_list_accounts_with_metadata` - interceptor in new development instead of the `post_list_accounts` interceptor. - When both interceptors are used, this `post_list_accounts_with_metadata` interceptor runs after the - `post_list_accounts` interceptor. The (possibly modified) response returned by - `post_list_accounts` will be passed to - `post_list_accounts_with_metadata`. - """ - return response, metadata - - def pre_list_sub_accounts(self, request: accounts.ListSubAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_sub_accounts - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountsService server. - """ - return request, metadata - - def post_list_sub_accounts(self, response: accounts.ListSubAccountsResponse) -> accounts.ListSubAccountsResponse: - """Post-rpc interceptor for list_sub_accounts - - DEPRECATED. Please use the `post_list_sub_accounts_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. This `post_list_sub_accounts` interceptor runs - before the `post_list_sub_accounts_with_metadata` interceptor. - """ - return response - - def post_list_sub_accounts_with_metadata(self, response: accounts.ListSubAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_sub_accounts - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountsService server but before it is returned to user code. - - We recommend only using this `post_list_sub_accounts_with_metadata` - interceptor in new development instead of the `post_list_sub_accounts` interceptor. - When both interceptors are used, this `post_list_sub_accounts_with_metadata` interceptor runs after the - `post_list_sub_accounts` interceptor. The (possibly modified) response returned by - `post_list_sub_accounts` will be passed to - `post_list_sub_accounts_with_metadata`. - """ - return response, metadata - - def pre_update_account(self, request: accounts.UpdateAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_account - - Override in a subclass to manipulate the request or metadata - before they are sent to the AccountsService server. - """ - return request, metadata - - def post_update_account(self, response: accounts.Account) -> accounts.Account: - """Post-rpc interceptor for update_account - - DEPRECATED. Please use the `post_update_account_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AccountsService server but before - it is returned to user code. This `post_update_account` interceptor runs - before the `post_update_account_with_metadata` interceptor. - """ - return response - - def post_update_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_account - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AccountsService server but before it is returned to user code. - - We recommend only using this `post_update_account_with_metadata` - interceptor in new development instead of the `post_update_account` interceptor. - When both interceptors are used, this `post_update_account_with_metadata` interceptor runs after the - `post_update_account` interceptor. The (possibly modified) response returned by - `post_update_account` will be passed to - `post_update_account_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class AccountsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AccountsServiceRestInterceptor - - -class AccountsServiceRestTransport(_BaseAccountsServiceRestTransport): - """REST backend synchronous transport for AccountsService. - - Service to support Accounts API. - - 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[AccountsServiceRestInterceptor] = 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 AccountsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateAndConfigureAccount(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount, AccountsServiceRestStub): - def __hash__(self): - return hash("AccountsServiceRestTransport.CreateAndConfigureAccount") - - @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: accounts.CreateAndConfigureAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.Account: - r"""Call the create and configure - account method over HTTP. - - Args: - request (~.accounts.CreateAndConfigureAccountRequest): - The request object. Request message for the ``CreateAndConfigureAccount`` - 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: - ~.accounts.Account: - An account. - """ - - http_options = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_http_options() - - request, metadata = self._interceptor.pre_create_and_configure_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_transcoded_request(http_options, request) - - body = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.CreateAndConfigureAccount", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "CreateAndConfigureAccount", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountsServiceRestTransport._CreateAndConfigureAccount._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 = accounts.Account() - pb_resp = accounts.Account.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_and_configure_account(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_and_configure_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = accounts.Account.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.accounts_v1beta.AccountsServiceClient.create_and_configure_account", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "CreateAndConfigureAccount", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteAccount(_BaseAccountsServiceRestTransport._BaseDeleteAccount, AccountsServiceRestStub): - def __hash__(self): - return hash("AccountsServiceRestTransport.DeleteAccount") - - @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: accounts.DeleteAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete account method over HTTP. - - Args: - request (~.accounts.DeleteAccountRequest): - The request object. Request message for the ``DeleteAccount`` 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 = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_http_options() - - request, metadata = self._interceptor.pre_delete_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.DeleteAccount", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "DeleteAccount", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountsServiceRestTransport._DeleteAccount._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 _GetAccount(_BaseAccountsServiceRestTransport._BaseGetAccount, AccountsServiceRestStub): - def __hash__(self): - return hash("AccountsServiceRestTransport.GetAccount") - - @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: accounts.GetAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.Account: - r"""Call the get account method over HTTP. - - Args: - request (~.accounts.GetAccountRequest): - The request object. Request message for the ``GetAccount`` 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: - ~.accounts.Account: - An account. - """ - - http_options = _BaseAccountsServiceRestTransport._BaseGetAccount._get_http_options() - - request, metadata = self._interceptor.pre_get_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseGetAccount._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseGetAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.GetAccount", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "GetAccount", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountsServiceRestTransport._GetAccount._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 = accounts.Account() - pb_resp = accounts.Account.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_account(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = accounts.Account.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.accounts_v1beta.AccountsServiceClient.get_account", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "GetAccount", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListAccounts(_BaseAccountsServiceRestTransport._BaseListAccounts, AccountsServiceRestStub): - def __hash__(self): - return hash("AccountsServiceRestTransport.ListAccounts") - - @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: accounts.ListAccountsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.ListAccountsResponse: - r"""Call the list accounts method over HTTP. - - Args: - request (~.accounts.ListAccountsRequest): - The request object. Request message for the ``ListAccounts`` 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: - ~.accounts.ListAccountsResponse: - Response message for the ``ListAccounts`` method. - """ - - http_options = _BaseAccountsServiceRestTransport._BaseListAccounts._get_http_options() - - request, metadata = self._interceptor.pre_list_accounts(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseListAccounts._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseListAccounts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.ListAccounts", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "ListAccounts", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountsServiceRestTransport._ListAccounts._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 = accounts.ListAccountsResponse() - pb_resp = accounts.ListAccountsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_accounts(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_accounts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = accounts.ListAccountsResponse.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.accounts_v1beta.AccountsServiceClient.list_accounts", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "ListAccounts", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListSubAccounts(_BaseAccountsServiceRestTransport._BaseListSubAccounts, AccountsServiceRestStub): - def __hash__(self): - return hash("AccountsServiceRestTransport.ListSubAccounts") - - @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: accounts.ListSubAccountsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.ListSubAccountsResponse: - r"""Call the list sub accounts method over HTTP. - - Args: - request (~.accounts.ListSubAccountsRequest): - The request object. Request message for the ``ListSubAccounts`` 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: - ~.accounts.ListSubAccountsResponse: - Response message for the ``ListSubAccounts`` method. - """ - - http_options = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_http_options() - - request, metadata = self._interceptor.pre_list_sub_accounts(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.ListSubAccounts", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "ListSubAccounts", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountsServiceRestTransport._ListSubAccounts._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 = accounts.ListSubAccountsResponse() - pb_resp = accounts.ListSubAccountsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_sub_accounts(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_sub_accounts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = accounts.ListSubAccountsResponse.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.accounts_v1beta.AccountsServiceClient.list_sub_accounts", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "ListSubAccounts", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAccount(_BaseAccountsServiceRestTransport._BaseUpdateAccount, AccountsServiceRestStub): - def __hash__(self): - return hash("AccountsServiceRestTransport.UpdateAccount") - - @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: accounts.UpdateAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.Account: - r"""Call the update account method over HTTP. - - Args: - request (~.accounts.UpdateAccountRequest): - The request object. Request message for the ``UpdateAccount`` 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: - ~.accounts.Account: - An account. - """ - - http_options = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_http_options() - - request, metadata = self._interceptor.pre_update_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_transcoded_request(http_options, request) - - body = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AccountsServiceClient.UpdateAccount", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "UpdateAccount", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AccountsServiceRestTransport._UpdateAccount._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 = accounts.Account() - pb_resp = accounts.Account.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_account(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = accounts.Account.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.accounts_v1beta.AccountsServiceClient.update_account", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "rpcName": "UpdateAccount", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - accounts.Account]: - # 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._CreateAndConfigureAccount(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - 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._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_account(self) -> Callable[ - [accounts.GetAccountRequest], - accounts.Account]: - # 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._GetAccount(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - accounts.ListAccountsResponse]: - # 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._ListAccounts(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - accounts.ListSubAccountsResponse]: - # 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._ListSubAccounts(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - accounts.Account]: - # 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._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AccountsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py deleted file mode 100644 index 2eb9ab5be202..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/rest_base.py +++ /dev/null @@ -1,326 +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 AccountsServiceTransport, 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_accounts_v1beta.types import accounts - - -class _BaseAccountsServiceRestTransport(AccountsServiceTransport): - """Base REST backend transport for AccountsService. - - 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 _BaseCreateAndConfigureAccount: - 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': '/accounts/v1beta/accounts:createAndConfigure', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accounts.CreateAndConfigureAccountRequest.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(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteAccount: - 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': '/accounts/v1beta/{name=accounts/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accounts.DeleteAccountRequest.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(_BaseAccountsServiceRestTransport._BaseDeleteAccount._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetAccount: - 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': '/accounts/v1beta/{name=accounts/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accounts.GetAccountRequest.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(_BaseAccountsServiceRestTransport._BaseGetAccount._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListAccounts: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/accounts/v1beta/accounts', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accounts.ListAccountsRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListSubAccounts: - 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': '/accounts/v1beta/{provider=accounts/*}:listSubaccounts', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accounts.ListSubAccountsRequest.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(_BaseAccountsServiceRestTransport._BaseListSubAccounts._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateAccount: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{account.name=accounts/*}', - 'body': 'account', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = accounts.UpdateAccountRequest.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(_BaseAccountsServiceRestTransport._BaseUpdateAccount._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAccountsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py deleted file mode 100644 index 538b6cfb295e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/async_client.py +++ /dev/null @@ -1,493 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import autofeedsettings -from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport -from .client import AutofeedSettingsServiceClient - -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 AutofeedSettingsServiceAsyncClient: - """Service to support - `autofeed `__ - setting. - """ - - _client: AutofeedSettingsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - - autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.autofeed_settings_path) - parse_autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.parse_autofeed_settings_path) - common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AutofeedSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AutofeedSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AutofeedSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AutofeedSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AutofeedSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AutofeedSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(AutofeedSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AutofeedSettingsServiceClient.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: - AutofeedSettingsServiceAsyncClient: The constructed client. - """ - return AutofeedSettingsServiceClient.from_service_account_info.__func__(AutofeedSettingsServiceAsyncClient, 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: - AutofeedSettingsServiceAsyncClient: The constructed client. - """ - return AutofeedSettingsServiceClient.from_service_account_file.__func__(AutofeedSettingsServiceAsyncClient, 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 AutofeedSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AutofeedSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AutofeedSettingsServiceTransport: 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 = AutofeedSettingsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the autofeed settings 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,AutofeedSettingsServiceTransport,Callable[..., AutofeedSettingsServiceTransport]]]): - 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 AutofeedSettingsServiceTransport 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 = AutofeedSettingsServiceClient( - 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.accounts_v1beta.AutofeedSettingsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "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.accounts.v1beta.AutofeedSettingsService", - "credentialsType": None, - } - ) - - async def get_autofeed_settings(self, - request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: - r"""Retrieves the autofeed settings of an 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_accounts_v1beta - - async def sample_get_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_autofeed_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest, dict]]): - The request object. Request message for the ``GetAutofeedSettings`` method. - name (:class:`str`): - Required. The resource name of the autofeed settings. - Format: ``accounts/{account}/autofeedSettings`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.AutofeedSettings: - Collection of information related to the - [autofeed](https://support.google.com/merchants/answer/7538732) - settings. - - """ - # 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, autofeedsettings.GetAutofeedSettingsRequest): - request = autofeedsettings.GetAutofeedSettingsRequest(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.get_autofeed_settings] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_autofeed_settings(self, - request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, - *, - autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: - r"""Updates the autofeed settings of an 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_accounts_v1beta - - async def sample_update_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() - - # Initialize request argument(s) - autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() - autofeed_settings.enable_products = True - - request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( - autofeed_settings=autofeed_settings, - ) - - # Make the request - response = await client.update_autofeed_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest, dict]]): - The request object. Request message for the ``UpdateAutofeedSettings`` - method. - autofeed_settings (:class:`google.shopping.merchant_accounts_v1beta.types.AutofeedSettings`): - Required. The new version of the - autofeed setting. - - This corresponds to the ``autofeed_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutofeedSettings: - Collection of information related to the - [autofeed](https://support.google.com/merchants/answer/7538732) - settings. - - """ - # 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 = [autofeed_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, autofeedsettings.UpdateAutofeedSettingsRequest): - request = autofeedsettings.UpdateAutofeedSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if autofeed_settings is not None: - request.autofeed_settings = autofeed_settings - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_autofeed_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("autofeed_settings.name", request.autofeed_settings.name), - )), - ) - - # 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 __aenter__(self) -> "AutofeedSettingsServiceAsyncClient": - 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__ = ( - "AutofeedSettingsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py deleted file mode 100644 index b2e0f8881c87..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/client.py +++ /dev/null @@ -1,852 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import autofeedsettings -from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AutofeedSettingsServiceGrpcTransport -from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport -from .transports.rest import AutofeedSettingsServiceRestTransport - - -class AutofeedSettingsServiceClientMeta(type): - """Metaclass for the AutofeedSettingsService 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[AutofeedSettingsServiceTransport]] - _transport_registry["grpc"] = AutofeedSettingsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AutofeedSettingsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AutofeedSettingsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AutofeedSettingsServiceTransport]: - """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 AutofeedSettingsServiceClient(metaclass=AutofeedSettingsServiceClientMeta): - """Service to support - `autofeed `__ - setting. - """ - - @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: - AutofeedSettingsServiceClient: 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: - AutofeedSettingsServiceClient: 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) -> AutofeedSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AutofeedSettingsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def autofeed_settings_path(account: str,) -> str: - """Returns a fully-qualified autofeed_settings string.""" - return "accounts/{account}/autofeedSettings".format(account=account, ) - - @staticmethod - def parse_autofeed_settings_path(path: str) -> Dict[str,str]: - """Parses a autofeed_settings path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/autofeedSettings$", 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 = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient._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, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the autofeed settings 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,AutofeedSettingsServiceTransport,Callable[..., AutofeedSettingsServiceTransport]]]): - 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 AutofeedSettingsServiceTransport 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 = AutofeedSettingsServiceClient._read_environment_variables() - self._client_cert_source = AutofeedSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AutofeedSettingsServiceClient._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, AutofeedSettingsServiceTransport) - if transport_provided: - # transport is a AutofeedSettingsServiceTransport 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(AutofeedSettingsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AutofeedSettingsServiceClient._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[AutofeedSettingsServiceTransport], Callable[..., AutofeedSettingsServiceTransport]] = ( - AutofeedSettingsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AutofeedSettingsServiceTransport], 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.accounts_v1beta.AutofeedSettingsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "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.accounts.v1beta.AutofeedSettingsService", - "credentialsType": None, - } - ) - - def get_autofeed_settings(self, - request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: - r"""Retrieves the autofeed settings of an 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_accounts_v1beta - - def sample_get_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_autofeed_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest, dict]): - The request object. Request message for the ``GetAutofeedSettings`` method. - name (str): - Required. The resource name of the autofeed settings. - Format: ``accounts/{account}/autofeedSettings`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.AutofeedSettings: - Collection of information related to the - [autofeed](https://support.google.com/merchants/answer/7538732) - settings. - - """ - # 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, autofeedsettings.GetAutofeedSettingsRequest): - request = autofeedsettings.GetAutofeedSettingsRequest(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.get_autofeed_settings] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_autofeed_settings(self, - request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, - *, - autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: - r"""Updates the autofeed settings of an 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_accounts_v1beta - - def sample_update_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() - - # Initialize request argument(s) - autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() - autofeed_settings.enable_products = True - - request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( - autofeed_settings=autofeed_settings, - ) - - # Make the request - response = client.update_autofeed_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest, dict]): - The request object. Request message for the ``UpdateAutofeedSettings`` - method. - autofeed_settings (google.shopping.merchant_accounts_v1beta.types.AutofeedSettings): - Required. The new version of the - autofeed setting. - - This corresponds to the ``autofeed_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutofeedSettings: - Collection of information related to the - [autofeed](https://support.google.com/merchants/answer/7538732) - settings. - - """ - # 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 = [autofeed_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, autofeedsettings.UpdateAutofeedSettingsRequest): - request = autofeedsettings.UpdateAutofeedSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if autofeed_settings is not None: - request.autofeed_settings = autofeed_settings - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_autofeed_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("autofeed_settings.name", request.autofeed_settings.name), - )), - ) - - # 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 __enter__(self) -> "AutofeedSettingsServiceClient": - 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__ = ( - "AutofeedSettingsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst deleted file mode 100644 index 54f64d66d215..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AutofeedSettingsServiceTransport` is the ABC for all transports. -- public child `AutofeedSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AutofeedSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAutofeedSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AutofeedSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py deleted file mode 100644 index 746744918723..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import autofeedsettings - -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 AutofeedSettingsServiceTransport(abc.ABC): - """Abstract transport class for AutofeedSettingsService.""" - - 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.get_autofeed_settings: gapic_v1.method.wrap_method( - self.get_autofeed_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_autofeed_settings: gapic_v1.method.wrap_method( - self.update_autofeed_settings, - 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 get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - Union[ - autofeedsettings.AutofeedSettings, - Awaitable[autofeedsettings.AutofeedSettings] - ]]: - raise NotImplementedError() - - @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - Union[ - autofeedsettings.AutofeedSettings, - Awaitable[autofeedsettings.AutofeedSettings] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AutofeedSettingsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py deleted file mode 100644 index 85dd101af839..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc.py +++ /dev/null @@ -1,374 +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.shopping.merchant_accounts_v1beta.types import autofeedsettings -from .base import AutofeedSettingsServiceTransport, 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.accounts.v1beta.AutofeedSettingsService", - "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.accounts.v1beta.AutofeedSettingsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AutofeedSettingsServiceGrpcTransport(AutofeedSettingsServiceTransport): - """gRPC backend transport for AutofeedSettingsService. - - Service to support - `autofeed `__ - setting. - - 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 get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: - r"""Return a callable for the get autofeed settings method over gRPC. - - Retrieves the autofeed settings of an account. - - Returns: - Callable[[~.GetAutofeedSettingsRequest], - ~.AutofeedSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_autofeed_settings' not in self._stubs: - self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/GetAutofeedSettings', - request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, - response_deserializer=autofeedsettings.AutofeedSettings.deserialize, - ) - return self._stubs['get_autofeed_settings'] - - @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: - r"""Return a callable for the update autofeed settings method over gRPC. - - Updates the autofeed settings of an account. - - Returns: - Callable[[~.UpdateAutofeedSettingsRequest], - ~.AutofeedSettings]: - 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 'update_autofeed_settings' not in self._stubs: - self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/UpdateAutofeedSettings', - request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, - response_deserializer=autofeedsettings.AutofeedSettings.deserialize, - ) - return self._stubs['update_autofeed_settings'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AutofeedSettingsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py deleted file mode 100644 index c02a74167f25..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,400 +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.shopping.merchant_accounts_v1beta.types import autofeedsettings -from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AutofeedSettingsServiceGrpcTransport - -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.accounts.v1beta.AutofeedSettingsService", - "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.accounts.v1beta.AutofeedSettingsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AutofeedSettingsServiceGrpcAsyncIOTransport(AutofeedSettingsServiceTransport): - """gRPC AsyncIO backend transport for AutofeedSettingsService. - - Service to support - `autofeed `__ - setting. - - 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 get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - Awaitable[autofeedsettings.AutofeedSettings]]: - r"""Return a callable for the get autofeed settings method over gRPC. - - Retrieves the autofeed settings of an account. - - Returns: - Callable[[~.GetAutofeedSettingsRequest], - Awaitable[~.AutofeedSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_autofeed_settings' not in self._stubs: - self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/GetAutofeedSettings', - request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, - response_deserializer=autofeedsettings.AutofeedSettings.deserialize, - ) - return self._stubs['get_autofeed_settings'] - - @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - Awaitable[autofeedsettings.AutofeedSettings]]: - r"""Return a callable for the update autofeed settings method over gRPC. - - Updates the autofeed settings of an account. - - Returns: - Callable[[~.UpdateAutofeedSettingsRequest], - Awaitable[~.AutofeedSettings]]: - 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 'update_autofeed_settings' not in self._stubs: - self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutofeedSettingsService/UpdateAutofeedSettings', - request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, - response_deserializer=autofeedsettings.AutofeedSettings.deserialize, - ) - return self._stubs['update_autofeed_settings'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_autofeed_settings: self._wrap_method( - self.get_autofeed_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_autofeed_settings: self._wrap_method( - self.update_autofeed_settings, - 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__ = ( - 'AutofeedSettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py deleted file mode 100644 index bc908e354b7e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest.py +++ /dev/null @@ -1,534 +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.shopping.merchant_accounts_v1beta.types import autofeedsettings - - -from .rest_base import _BaseAutofeedSettingsServiceRestTransport -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 AutofeedSettingsServiceRestInterceptor: - """Interceptor for AutofeedSettingsService. - - 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 AutofeedSettingsServiceRestTransport. - - .. code-block:: python - class MyCustomAutofeedSettingsServiceInterceptor(AutofeedSettingsServiceRestInterceptor): - def pre_get_autofeed_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_autofeed_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_autofeed_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_autofeed_settings(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AutofeedSettingsServiceRestTransport(interceptor=MyCustomAutofeedSettingsServiceInterceptor()) - client = AutofeedSettingsServiceClient(transport=transport) - - - """ - def pre_get_autofeed_settings(self, request: autofeedsettings.GetAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_autofeed_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutofeedSettingsService server. - """ - return request, metadata - - def post_get_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: - """Post-rpc interceptor for get_autofeed_settings - - DEPRECATED. Please use the `post_get_autofeed_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AutofeedSettingsService server but before - it is returned to user code. This `post_get_autofeed_settings` interceptor runs - before the `post_get_autofeed_settings_with_metadata` interceptor. - """ - return response - - def post_get_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_autofeed_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AutofeedSettingsService server but before it is returned to user code. - - We recommend only using this `post_get_autofeed_settings_with_metadata` - interceptor in new development instead of the `post_get_autofeed_settings` interceptor. - When both interceptors are used, this `post_get_autofeed_settings_with_metadata` interceptor runs after the - `post_get_autofeed_settings` interceptor. The (possibly modified) response returned by - `post_get_autofeed_settings` will be passed to - `post_get_autofeed_settings_with_metadata`. - """ - return response, metadata - - def pre_update_autofeed_settings(self, request: autofeedsettings.UpdateAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_autofeed_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutofeedSettingsService server. - """ - return request, metadata - - def post_update_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: - """Post-rpc interceptor for update_autofeed_settings - - DEPRECATED. Please use the `post_update_autofeed_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AutofeedSettingsService server but before - it is returned to user code. This `post_update_autofeed_settings` interceptor runs - before the `post_update_autofeed_settings_with_metadata` interceptor. - """ - return response - - def post_update_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_autofeed_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AutofeedSettingsService server but before it is returned to user code. - - We recommend only using this `post_update_autofeed_settings_with_metadata` - interceptor in new development instead of the `post_update_autofeed_settings` interceptor. - When both interceptors are used, this `post_update_autofeed_settings_with_metadata` interceptor runs after the - `post_update_autofeed_settings` interceptor. The (possibly modified) response returned by - `post_update_autofeed_settings` will be passed to - `post_update_autofeed_settings_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class AutofeedSettingsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AutofeedSettingsServiceRestInterceptor - - -class AutofeedSettingsServiceRestTransport(_BaseAutofeedSettingsServiceRestTransport): - """REST backend synchronous transport for AutofeedSettingsService. - - Service to support - `autofeed `__ - setting. - - 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[AutofeedSettingsServiceRestInterceptor] = 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 AutofeedSettingsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings, AutofeedSettingsServiceRestStub): - def __hash__(self): - return hash("AutofeedSettingsServiceRestTransport.GetAutofeedSettings") - - @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: autofeedsettings.GetAutofeedSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> autofeedsettings.AutofeedSettings: - r"""Call the get autofeed settings method over HTTP. - - Args: - request (~.autofeedsettings.GetAutofeedSettingsRequest): - The request object. Request message for the ``GetAutofeedSettings`` 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: - ~.autofeedsettings.AutofeedSettings: - Collection of information related to the - `autofeed `__ - settings. - - """ - - http_options = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_http_options() - - request, metadata = self._interceptor.pre_get_autofeed_settings(request, metadata) - transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutofeedSettingsServiceClient.GetAutofeedSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "rpcName": "GetAutofeedSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AutofeedSettingsServiceRestTransport._GetAutofeedSettings._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 = autofeedsettings.AutofeedSettings() - pb_resp = autofeedsettings.AutofeedSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_autofeed_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_autofeed_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1beta.AutofeedSettingsServiceClient.get_autofeed_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "rpcName": "GetAutofeedSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings, AutofeedSettingsServiceRestStub): - def __hash__(self): - return hash("AutofeedSettingsServiceRestTransport.UpdateAutofeedSettings") - - @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: autofeedsettings.UpdateAutofeedSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> autofeedsettings.AutofeedSettings: - r"""Call the update autofeed settings method over HTTP. - - Args: - request (~.autofeedsettings.UpdateAutofeedSettingsRequest): - The request object. Request message for the ``UpdateAutofeedSettings`` - 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: - ~.autofeedsettings.AutofeedSettings: - Collection of information related to the - `autofeed `__ - settings. - - """ - - http_options = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_http_options() - - request, metadata = self._interceptor.pre_update_autofeed_settings(request, metadata) - transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_transcoded_request(http_options, request) - - body = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutofeedSettingsServiceClient.UpdateAutofeedSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "rpcName": "UpdateAutofeedSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AutofeedSettingsServiceRestTransport._UpdateAutofeedSettings._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 = autofeedsettings.AutofeedSettings() - pb_resp = autofeedsettings.AutofeedSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_autofeed_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_autofeed_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1beta.AutofeedSettingsServiceClient.update_autofeed_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "rpcName": "UpdateAutofeedSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: - # 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._GetAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: - # 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._UpdateAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AutofeedSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py deleted file mode 100644 index c5c58aca9244..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import autofeedsettings - - -class _BaseAutofeedSettingsServiceRestTransport(AutofeedSettingsServiceTransport): - """Base REST backend transport for AutofeedSettingsService. - - 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 _BaseGetAutofeedSettings: - 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': '/accounts/v1beta/{name=accounts/*/autofeedSettings}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autofeedsettings.GetAutofeedSettingsRequest.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(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateAutofeedSettings: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{autofeed_settings.name=accounts/*/autofeedSettings}', - 'body': 'autofeed_settings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autofeedsettings.UpdateAutofeedSettingsRequest.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(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAutofeedSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/__init__.py deleted file mode 100644 index 7df59eeedb79..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_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 AutomaticImprovementsServiceClient -from .async_client import AutomaticImprovementsServiceAsyncClient - -__all__ = ( - 'AutomaticImprovementsServiceClient', - 'AutomaticImprovementsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py deleted file mode 100644 index 60e41a5290e6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/async_client.py +++ /dev/null @@ -1,499 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import automaticimprovements -from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport -from .client import AutomaticImprovementsServiceClient - -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 AutomaticImprovementsServiceAsyncClient: - """Service to manage the automatic improvements of an account. - The automatic improvements of the account can be used to - automatically update products, improve images and shipping. - """ - - _client: AutomaticImprovementsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - - automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.automatic_improvements_path) - parse_automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.parse_automatic_improvements_path) - common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AutomaticImprovementsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AutomaticImprovementsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AutomaticImprovementsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_project_path) - common_location_path = staticmethod(AutomaticImprovementsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AutomaticImprovementsServiceClient.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: - AutomaticImprovementsServiceAsyncClient: The constructed client. - """ - return AutomaticImprovementsServiceClient.from_service_account_info.__func__(AutomaticImprovementsServiceAsyncClient, 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: - AutomaticImprovementsServiceAsyncClient: The constructed client. - """ - return AutomaticImprovementsServiceClient.from_service_account_file.__func__(AutomaticImprovementsServiceAsyncClient, 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 AutomaticImprovementsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AutomaticImprovementsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AutomaticImprovementsServiceTransport: 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 = AutomaticImprovementsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the automatic improvements 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,AutomaticImprovementsServiceTransport,Callable[..., AutomaticImprovementsServiceTransport]]]): - 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 AutomaticImprovementsServiceTransport 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 = AutomaticImprovementsServiceClient( - 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.accounts_v1beta.AutomaticImprovementsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "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.accounts.v1beta.AutomaticImprovementsService", - "credentialsType": None, - } - ) - - async def get_automatic_improvements(self, - request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: - r"""Retrieves the automatic improvements of an 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_accounts_v1beta - - async def sample_get_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_automatic_improvements(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest, dict]]): - The request object. Request message for the ``GetAutomaticImprovements`` - method. - name (:class:`str`): - Required. The resource name of the automatic - improvements. Format: - ``accounts/{account}/automaticImprovements`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements: - Collection of information related to the [automatic - improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) - of an account. - - """ - # 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, automaticimprovements.GetAutomaticImprovementsRequest): - request = automaticimprovements.GetAutomaticImprovementsRequest(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.get_automatic_improvements] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_automatic_improvements(self, - request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, - *, - automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: - r"""Updates the automatic improvements of an 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_accounts_v1beta - - async def sample_update_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( - ) - - # Make the request - response = await client.update_automatic_improvements(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest, dict]]): - The request object. Request message for the ``UpdateAutomaticImprovements`` - method. - automatic_improvements (:class:`google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements`): - Required. The new version of the - automatic imrovements. - - This corresponds to the ``automatic_improvements`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being updated. The following - fields are supported (in both ``snake_case`` and - ``lowerCamelCase``): - - - ``item_updates`` - - ``item_updates.account_level_settings`` - - ``image_improvements`` - - ``image_improvements.account_level_settings`` - - ``shipping_improvements`` - - ``shipping_improvements.allow_shipping_improvements`` - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutomaticImprovements: - Collection of information related to the [automatic - improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) - of an account. - - """ - # 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 = [automatic_improvements, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, automaticimprovements.UpdateAutomaticImprovementsRequest): - request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if automatic_improvements is not None: - request.automatic_improvements = automatic_improvements - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_automatic_improvements] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("automatic_improvements.name", request.automatic_improvements.name), - )), - ) - - # 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 __aenter__(self) -> "AutomaticImprovementsServiceAsyncClient": - 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__ = ( - "AutomaticImprovementsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py deleted file mode 100644 index ceb3df3a74cc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/client.py +++ /dev/null @@ -1,858 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import automaticimprovements -from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AutomaticImprovementsServiceGrpcTransport -from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport -from .transports.rest import AutomaticImprovementsServiceRestTransport - - -class AutomaticImprovementsServiceClientMeta(type): - """Metaclass for the AutomaticImprovementsService 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[AutomaticImprovementsServiceTransport]] - _transport_registry["grpc"] = AutomaticImprovementsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AutomaticImprovementsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AutomaticImprovementsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AutomaticImprovementsServiceTransport]: - """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 AutomaticImprovementsServiceClient(metaclass=AutomaticImprovementsServiceClientMeta): - """Service to manage the automatic improvements of an account. - The automatic improvements of the account can be used to - automatically update products, improve images and shipping. - """ - - @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: - AutomaticImprovementsServiceClient: 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: - AutomaticImprovementsServiceClient: 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) -> AutomaticImprovementsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AutomaticImprovementsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def automatic_improvements_path(account: str,) -> str: - """Returns a fully-qualified automatic_improvements string.""" - return "accounts/{account}/automaticImprovements".format(account=account, ) - - @staticmethod - def parse_automatic_improvements_path(path: str) -> Dict[str,str]: - """Parses a automatic_improvements path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/automaticImprovements$", 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 = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient._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, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the automatic improvements 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,AutomaticImprovementsServiceTransport,Callable[..., AutomaticImprovementsServiceTransport]]]): - 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 AutomaticImprovementsServiceTransport 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 = AutomaticImprovementsServiceClient._read_environment_variables() - self._client_cert_source = AutomaticImprovementsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AutomaticImprovementsServiceClient._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, AutomaticImprovementsServiceTransport) - if transport_provided: - # transport is a AutomaticImprovementsServiceTransport 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(AutomaticImprovementsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AutomaticImprovementsServiceClient._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[AutomaticImprovementsServiceTransport], Callable[..., AutomaticImprovementsServiceTransport]] = ( - AutomaticImprovementsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AutomaticImprovementsServiceTransport], 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.accounts_v1beta.AutomaticImprovementsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "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.accounts.v1beta.AutomaticImprovementsService", - "credentialsType": None, - } - ) - - def get_automatic_improvements(self, - request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: - r"""Retrieves the automatic improvements of an 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_accounts_v1beta - - def sample_get_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( - name="name_value", - ) - - # Make the request - response = client.get_automatic_improvements(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest, dict]): - The request object. Request message for the ``GetAutomaticImprovements`` - method. - name (str): - Required. The resource name of the automatic - improvements. Format: - ``accounts/{account}/automaticImprovements`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements: - Collection of information related to the [automatic - improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) - of an account. - - """ - # 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, automaticimprovements.GetAutomaticImprovementsRequest): - request = automaticimprovements.GetAutomaticImprovementsRequest(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.get_automatic_improvements] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_automatic_improvements(self, - request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, - *, - automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: - r"""Updates the automatic improvements of an 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_accounts_v1beta - - def sample_update_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( - ) - - # Make the request - response = client.update_automatic_improvements(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest, dict]): - The request object. Request message for the ``UpdateAutomaticImprovements`` - method. - automatic_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements): - Required. The new version of the - automatic imrovements. - - This corresponds to the ``automatic_improvements`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. The following - fields are supported (in both ``snake_case`` and - ``lowerCamelCase``): - - - ``item_updates`` - - ``item_updates.account_level_settings`` - - ``image_improvements`` - - ``image_improvements.account_level_settings`` - - ``shipping_improvements`` - - ``shipping_improvements.allow_shipping_improvements`` - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.AutomaticImprovements: - Collection of information related to the [automatic - improvements](\ https://developers.google.com/shopping-content/guides/automatic-improvements) - of an account. - - """ - # 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 = [automatic_improvements, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, automaticimprovements.UpdateAutomaticImprovementsRequest): - request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if automatic_improvements is not None: - request.automatic_improvements = automatic_improvements - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_automatic_improvements] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("automatic_improvements.name", request.automatic_improvements.name), - )), - ) - - # 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 __enter__(self) -> "AutomaticImprovementsServiceClient": - 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__ = ( - "AutomaticImprovementsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst deleted file mode 100644 index 87e807806d8b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AutomaticImprovementsServiceTransport` is the ABC for all transports. -- public child `AutomaticImprovementsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AutomaticImprovementsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAutomaticImprovementsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AutomaticImprovementsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/__init__.py deleted file mode 100644 index 815443dffafc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_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 AutomaticImprovementsServiceTransport -from .grpc import AutomaticImprovementsServiceGrpcTransport -from .grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport -from .rest import AutomaticImprovementsServiceRestTransport -from .rest import AutomaticImprovementsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] -_transport_registry['grpc'] = AutomaticImprovementsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AutomaticImprovementsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AutomaticImprovementsServiceRestTransport - -__all__ = ( - 'AutomaticImprovementsServiceTransport', - 'AutomaticImprovementsServiceGrpcTransport', - 'AutomaticImprovementsServiceGrpcAsyncIOTransport', - 'AutomaticImprovementsServiceRestTransport', - 'AutomaticImprovementsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py deleted file mode 100644 index 2d15663db10e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import automaticimprovements - -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 AutomaticImprovementsServiceTransport(abc.ABC): - """Abstract transport class for AutomaticImprovementsService.""" - - 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.get_automatic_improvements: gapic_v1.method.wrap_method( - self.get_automatic_improvements, - default_timeout=None, - client_info=client_info, - ), - self.update_automatic_improvements: gapic_v1.method.wrap_method( - self.update_automatic_improvements, - 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 get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - Union[ - automaticimprovements.AutomaticImprovements, - Awaitable[automaticimprovements.AutomaticImprovements] - ]]: - raise NotImplementedError() - - @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - Union[ - automaticimprovements.AutomaticImprovements, - Awaitable[automaticimprovements.AutomaticImprovements] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AutomaticImprovementsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py deleted file mode 100644 index 7b84dd140ddc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc.py +++ /dev/null @@ -1,374 +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.shopping.merchant_accounts_v1beta.types import automaticimprovements -from .base import AutomaticImprovementsServiceTransport, 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.accounts.v1beta.AutomaticImprovementsService", - "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.accounts.v1beta.AutomaticImprovementsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AutomaticImprovementsServiceGrpcTransport(AutomaticImprovementsServiceTransport): - """gRPC backend transport for AutomaticImprovementsService. - - Service to manage the automatic improvements of an account. - The automatic improvements of the account can be used to - automatically update products, improve images and shipping. - - 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 get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: - r"""Return a callable for the get automatic improvements method over gRPC. - - Retrieves the automatic improvements of an account. - - Returns: - Callable[[~.GetAutomaticImprovementsRequest], - ~.AutomaticImprovements]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_automatic_improvements' not in self._stubs: - self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/GetAutomaticImprovements', - request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, - response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, - ) - return self._stubs['get_automatic_improvements'] - - @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: - r"""Return a callable for the update automatic improvements method over gRPC. - - Updates the automatic improvements of an account. - - Returns: - Callable[[~.UpdateAutomaticImprovementsRequest], - ~.AutomaticImprovements]: - 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 'update_automatic_improvements' not in self._stubs: - self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/UpdateAutomaticImprovements', - request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, - response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, - ) - return self._stubs['update_automatic_improvements'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AutomaticImprovementsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py deleted file mode 100644 index 73e3540640d7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,400 +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.shopping.merchant_accounts_v1beta.types import automaticimprovements -from .base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AutomaticImprovementsServiceGrpcTransport - -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.accounts.v1beta.AutomaticImprovementsService", - "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.accounts.v1beta.AutomaticImprovementsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class AutomaticImprovementsServiceGrpcAsyncIOTransport(AutomaticImprovementsServiceTransport): - """gRPC AsyncIO backend transport for AutomaticImprovementsService. - - Service to manage the automatic improvements of an account. - The automatic improvements of the account can be used to - automatically update products, improve images and shipping. - - 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 get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - Awaitable[automaticimprovements.AutomaticImprovements]]: - r"""Return a callable for the get automatic improvements method over gRPC. - - Retrieves the automatic improvements of an account. - - Returns: - Callable[[~.GetAutomaticImprovementsRequest], - Awaitable[~.AutomaticImprovements]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_automatic_improvements' not in self._stubs: - self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/GetAutomaticImprovements', - request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, - response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, - ) - return self._stubs['get_automatic_improvements'] - - @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - Awaitable[automaticimprovements.AutomaticImprovements]]: - r"""Return a callable for the update automatic improvements method over gRPC. - - Updates the automatic improvements of an account. - - Returns: - Callable[[~.UpdateAutomaticImprovementsRequest], - Awaitable[~.AutomaticImprovements]]: - 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 'update_automatic_improvements' not in self._stubs: - self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService/UpdateAutomaticImprovements', - request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, - response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, - ) - return self._stubs['update_automatic_improvements'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_automatic_improvements: self._wrap_method( - self.get_automatic_improvements, - default_timeout=None, - client_info=client_info, - ), - self.update_automatic_improvements: self._wrap_method( - self.update_automatic_improvements, - 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__ = ( - 'AutomaticImprovementsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py deleted file mode 100644 index bb8df4b21ee0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest.py +++ /dev/null @@ -1,537 +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.shopping.merchant_accounts_v1beta.types import automaticimprovements - - -from .rest_base import _BaseAutomaticImprovementsServiceRestTransport -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 AutomaticImprovementsServiceRestInterceptor: - """Interceptor for AutomaticImprovementsService. - - 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 AutomaticImprovementsServiceRestTransport. - - .. code-block:: python - class MyCustomAutomaticImprovementsServiceInterceptor(AutomaticImprovementsServiceRestInterceptor): - def pre_get_automatic_improvements(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_automatic_improvements(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_automatic_improvements(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_automatic_improvements(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AutomaticImprovementsServiceRestTransport(interceptor=MyCustomAutomaticImprovementsServiceInterceptor()) - client = AutomaticImprovementsServiceClient(transport=transport) - - - """ - def pre_get_automatic_improvements(self, request: automaticimprovements.GetAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.GetAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_automatic_improvements - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutomaticImprovementsService server. - """ - return request, metadata - - def post_get_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: - """Post-rpc interceptor for get_automatic_improvements - - DEPRECATED. Please use the `post_get_automatic_improvements_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AutomaticImprovementsService server but before - it is returned to user code. This `post_get_automatic_improvements` interceptor runs - before the `post_get_automatic_improvements_with_metadata` interceptor. - """ - return response - - def post_get_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_automatic_improvements - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AutomaticImprovementsService server but before it is returned to user code. - - We recommend only using this `post_get_automatic_improvements_with_metadata` - interceptor in new development instead of the `post_get_automatic_improvements` interceptor. - When both interceptors are used, this `post_get_automatic_improvements_with_metadata` interceptor runs after the - `post_get_automatic_improvements` interceptor. The (possibly modified) response returned by - `post_get_automatic_improvements` will be passed to - `post_get_automatic_improvements_with_metadata`. - """ - return response, metadata - - def pre_update_automatic_improvements(self, request: automaticimprovements.UpdateAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.UpdateAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_automatic_improvements - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutomaticImprovementsService server. - """ - return request, metadata - - def post_update_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: - """Post-rpc interceptor for update_automatic_improvements - - DEPRECATED. Please use the `post_update_automatic_improvements_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the AutomaticImprovementsService server but before - it is returned to user code. This `post_update_automatic_improvements` interceptor runs - before the `post_update_automatic_improvements_with_metadata` interceptor. - """ - return response - - def post_update_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_automatic_improvements - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the AutomaticImprovementsService server but before it is returned to user code. - - We recommend only using this `post_update_automatic_improvements_with_metadata` - interceptor in new development instead of the `post_update_automatic_improvements` interceptor. - When both interceptors are used, this `post_update_automatic_improvements_with_metadata` interceptor runs after the - `post_update_automatic_improvements` interceptor. The (possibly modified) response returned by - `post_update_automatic_improvements` will be passed to - `post_update_automatic_improvements_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class AutomaticImprovementsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AutomaticImprovementsServiceRestInterceptor - - -class AutomaticImprovementsServiceRestTransport(_BaseAutomaticImprovementsServiceRestTransport): - """REST backend synchronous transport for AutomaticImprovementsService. - - Service to manage the automatic improvements of an account. - The automatic improvements of the account can be used to - automatically update products, improve images and shipping. - - 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[AutomaticImprovementsServiceRestInterceptor] = 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 AutomaticImprovementsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements, AutomaticImprovementsServiceRestStub): - def __hash__(self): - return hash("AutomaticImprovementsServiceRestTransport.GetAutomaticImprovements") - - @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: automaticimprovements.GetAutomaticImprovementsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> automaticimprovements.AutomaticImprovements: - r"""Call the get automatic - improvements method over HTTP. - - Args: - request (~.automaticimprovements.GetAutomaticImprovementsRequest): - The request object. Request message for the ``GetAutomaticImprovements`` - 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: - ~.automaticimprovements.AutomaticImprovements: - Collection of information related to the `automatic - improvements `__ - of an account. - - """ - - http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_http_options() - - request, metadata = self._interceptor.pre_get_automatic_improvements(request, metadata) - transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutomaticImprovementsServiceClient.GetAutomaticImprovements", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "rpcName": "GetAutomaticImprovements", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AutomaticImprovementsServiceRestTransport._GetAutomaticImprovements._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 = automaticimprovements.AutomaticImprovements() - pb_resp = automaticimprovements.AutomaticImprovements.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_automatic_improvements(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_automatic_improvements_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = automaticimprovements.AutomaticImprovements.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.accounts_v1beta.AutomaticImprovementsServiceClient.get_automatic_improvements", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "rpcName": "GetAutomaticImprovements", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements, AutomaticImprovementsServiceRestStub): - def __hash__(self): - return hash("AutomaticImprovementsServiceRestTransport.UpdateAutomaticImprovements") - - @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: automaticimprovements.UpdateAutomaticImprovementsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> automaticimprovements.AutomaticImprovements: - r"""Call the update automatic - improvements method over HTTP. - - Args: - request (~.automaticimprovements.UpdateAutomaticImprovementsRequest): - The request object. Request message for the ``UpdateAutomaticImprovements`` - 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: - ~.automaticimprovements.AutomaticImprovements: - Collection of information related to the `automatic - improvements `__ - of an account. - - """ - - http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_http_options() - - request, metadata = self._interceptor.pre_update_automatic_improvements(request, metadata) - transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_transcoded_request(http_options, request) - - body = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.AutomaticImprovementsServiceClient.UpdateAutomaticImprovements", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "rpcName": "UpdateAutomaticImprovements", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = AutomaticImprovementsServiceRestTransport._UpdateAutomaticImprovements._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 = automaticimprovements.AutomaticImprovements() - pb_resp = automaticimprovements.AutomaticImprovements.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_automatic_improvements(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_automatic_improvements_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = automaticimprovements.AutomaticImprovements.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.accounts_v1beta.AutomaticImprovementsServiceClient.update_automatic_improvements", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "rpcName": "UpdateAutomaticImprovements", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: - # 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._GetAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: - # 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._UpdateAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AutomaticImprovementsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py deleted file mode 100644 index f2a1be12bb5c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/automatic_improvements_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import automaticimprovements - - -class _BaseAutomaticImprovementsServiceRestTransport(AutomaticImprovementsServiceTransport): - """Base REST backend transport for AutomaticImprovementsService. - - 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 _BaseGetAutomaticImprovements: - 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': '/accounts/v1beta/{name=accounts/*/automaticImprovements}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = automaticimprovements.GetAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateAutomaticImprovements: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{automatic_improvements.name=accounts/*/automaticImprovements}', - 'body': 'automatic_improvements', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = automaticimprovements.UpdateAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseAutomaticImprovementsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/__init__.py deleted file mode 100644 index f97b26e0a25c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_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 BusinessIdentityServiceClient -from .async_client import BusinessIdentityServiceAsyncClient - -__all__ = ( - 'BusinessIdentityServiceClient', - 'BusinessIdentityServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py deleted file mode 100644 index a46b3103fdfc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/async_client.py +++ /dev/null @@ -1,488 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import businessidentity -from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport -from .client import BusinessIdentityServiceClient - -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 BusinessIdentityServiceAsyncClient: - """Service to support `business - identity `__ - API. - """ - - _client: BusinessIdentityServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - - business_identity_path = staticmethod(BusinessIdentityServiceClient.business_identity_path) - parse_business_identity_path = staticmethod(BusinessIdentityServiceClient.parse_business_identity_path) - common_billing_account_path = staticmethod(BusinessIdentityServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BusinessIdentityServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(BusinessIdentityServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(BusinessIdentityServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(BusinessIdentityServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(BusinessIdentityServiceClient.parse_common_organization_path) - common_project_path = staticmethod(BusinessIdentityServiceClient.common_project_path) - parse_common_project_path = staticmethod(BusinessIdentityServiceClient.parse_common_project_path) - common_location_path = staticmethod(BusinessIdentityServiceClient.common_location_path) - parse_common_location_path = staticmethod(BusinessIdentityServiceClient.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: - BusinessIdentityServiceAsyncClient: The constructed client. - """ - return BusinessIdentityServiceClient.from_service_account_info.__func__(BusinessIdentityServiceAsyncClient, 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: - BusinessIdentityServiceAsyncClient: The constructed client. - """ - return BusinessIdentityServiceClient.from_service_account_file.__func__(BusinessIdentityServiceAsyncClient, 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 BusinessIdentityServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> BusinessIdentityServiceTransport: - """Returns the transport used by the client instance. - - Returns: - BusinessIdentityServiceTransport: 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 = BusinessIdentityServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the business identity 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,BusinessIdentityServiceTransport,Callable[..., BusinessIdentityServiceTransport]]]): - 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 BusinessIdentityServiceTransport 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 = BusinessIdentityServiceClient( - 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.accounts_v1beta.BusinessIdentityServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "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.accounts.v1beta.BusinessIdentityService", - "credentialsType": None, - } - ) - - async def get_business_identity(self, - request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: - r"""Retrieves the business identity of an 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_accounts_v1beta - - async def sample_get_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessIdentityRequest( - name="name_value", - ) - - # Make the request - response = await client.get_business_identity(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest, dict]]): - The request object. Request message for the ``GetBusinessIdentity`` method. - name (:class:`str`): - Required. The resource name of the business identity. - Format: ``accounts/{account}/businessIdentity`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.BusinessIdentity: - Collection of information related to the [identity of a - business](\ https://support.google.com/merchants/answer/12564247). - - """ - # 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, businessidentity.GetBusinessIdentityRequest): - request = businessidentity.GetBusinessIdentityRequest(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.get_business_identity] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_business_identity(self, - request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, - *, - business_identity: Optional[businessidentity.BusinessIdentity] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: - r"""Updates the business identity of an account. - Executing this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_update_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( - ) - - # Make the request - response = await client.update_business_identity(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest, dict]]): - The request object. Request message for the ``UpdateBusinessIdentity`` - method. - business_identity (:class:`google.shopping.merchant_accounts_v1beta.types.BusinessIdentity`): - Required. The new version of the - business identity. - - This corresponds to the ``business_identity`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessIdentity: - Collection of information related to the [identity of a - business](\ https://support.google.com/merchants/answer/12564247). - - """ - # 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 = [business_identity, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, businessidentity.UpdateBusinessIdentityRequest): - request = businessidentity.UpdateBusinessIdentityRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if business_identity is not None: - request.business_identity = business_identity - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_identity] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_identity.name", request.business_identity.name), - )), - ) - - # 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 __aenter__(self) -> "BusinessIdentityServiceAsyncClient": - 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__ = ( - "BusinessIdentityServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py deleted file mode 100644 index 6b84a83a61a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/client.py +++ /dev/null @@ -1,847 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import businessidentity -from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import BusinessIdentityServiceGrpcTransport -from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport -from .transports.rest import BusinessIdentityServiceRestTransport - - -class BusinessIdentityServiceClientMeta(type): - """Metaclass for the BusinessIdentityService 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[BusinessIdentityServiceTransport]] - _transport_registry["grpc"] = BusinessIdentityServiceGrpcTransport - _transport_registry["grpc_asyncio"] = BusinessIdentityServiceGrpcAsyncIOTransport - _transport_registry["rest"] = BusinessIdentityServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[BusinessIdentityServiceTransport]: - """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 BusinessIdentityServiceClient(metaclass=BusinessIdentityServiceClientMeta): - """Service to support `business - identity `__ - API. - """ - - @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: - BusinessIdentityServiceClient: 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: - BusinessIdentityServiceClient: 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) -> BusinessIdentityServiceTransport: - """Returns the transport used by the client instance. - - Returns: - BusinessIdentityServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def business_identity_path(account: str,) -> str: - """Returns a fully-qualified business_identity string.""" - return "accounts/{account}/businessIdentity".format(account=account, ) - - @staticmethod - def parse_business_identity_path(path: str) -> Dict[str,str]: - """Parses a business_identity path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/businessIdentity$", 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 = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient._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, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the business identity 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,BusinessIdentityServiceTransport,Callable[..., BusinessIdentityServiceTransport]]]): - 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 BusinessIdentityServiceTransport 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 = BusinessIdentityServiceClient._read_environment_variables() - self._client_cert_source = BusinessIdentityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = BusinessIdentityServiceClient._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, BusinessIdentityServiceTransport) - if transport_provided: - # transport is a BusinessIdentityServiceTransport 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(BusinessIdentityServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - BusinessIdentityServiceClient._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[BusinessIdentityServiceTransport], Callable[..., BusinessIdentityServiceTransport]] = ( - BusinessIdentityServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., BusinessIdentityServiceTransport], 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.accounts_v1beta.BusinessIdentityServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "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.accounts.v1beta.BusinessIdentityService", - "credentialsType": None, - } - ) - - def get_business_identity(self, - request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: - r"""Retrieves the business identity of an 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_accounts_v1beta - - def sample_get_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessIdentityRequest( - name="name_value", - ) - - # Make the request - response = client.get_business_identity(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest, dict]): - The request object. Request message for the ``GetBusinessIdentity`` method. - name (str): - Required. The resource name of the business identity. - Format: ``accounts/{account}/businessIdentity`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.BusinessIdentity: - Collection of information related to the [identity of a - business](\ https://support.google.com/merchants/answer/12564247). - - """ - # 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, businessidentity.GetBusinessIdentityRequest): - request = businessidentity.GetBusinessIdentityRequest(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.get_business_identity] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_business_identity(self, - request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, - *, - business_identity: Optional[businessidentity.BusinessIdentity] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: - r"""Updates the business identity of an account. - Executing this method requires admin access. - - .. 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_accounts_v1beta - - def sample_update_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( - ) - - # Make the request - response = client.update_business_identity(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest, dict]): - The request object. Request message for the ``UpdateBusinessIdentity`` - method. - business_identity (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity): - Required. The new version of the - business identity. - - This corresponds to the ``business_identity`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessIdentity: - Collection of information related to the [identity of a - business](\ https://support.google.com/merchants/answer/12564247). - - """ - # 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 = [business_identity, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, businessidentity.UpdateBusinessIdentityRequest): - request = businessidentity.UpdateBusinessIdentityRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if business_identity is not None: - request.business_identity = business_identity - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_business_identity] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_identity.name", request.business_identity.name), - )), - ) - - # 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 __enter__(self) -> "BusinessIdentityServiceClient": - 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__ = ( - "BusinessIdentityServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst deleted file mode 100644 index 55db4f093f62..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`BusinessIdentityServiceTransport` is the ABC for all transports. -- public child `BusinessIdentityServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `BusinessIdentityServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseBusinessIdentityServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `BusinessIdentityServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/__init__.py deleted file mode 100644 index 0f211578bee2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_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 BusinessIdentityServiceTransport -from .grpc import BusinessIdentityServiceGrpcTransport -from .grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport -from .rest import BusinessIdentityServiceRestTransport -from .rest import BusinessIdentityServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessIdentityServiceTransport]] -_transport_registry['grpc'] = BusinessIdentityServiceGrpcTransport -_transport_registry['grpc_asyncio'] = BusinessIdentityServiceGrpcAsyncIOTransport -_transport_registry['rest'] = BusinessIdentityServiceRestTransport - -__all__ = ( - 'BusinessIdentityServiceTransport', - 'BusinessIdentityServiceGrpcTransport', - 'BusinessIdentityServiceGrpcAsyncIOTransport', - 'BusinessIdentityServiceRestTransport', - 'BusinessIdentityServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py deleted file mode 100644 index d0f37244bc6d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import businessidentity - -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 BusinessIdentityServiceTransport(abc.ABC): - """Abstract transport class for BusinessIdentityService.""" - - 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.get_business_identity: gapic_v1.method.wrap_method( - self.get_business_identity, - default_timeout=None, - client_info=client_info, - ), - self.update_business_identity: gapic_v1.method.wrap_method( - self.update_business_identity, - 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 get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - Union[ - businessidentity.BusinessIdentity, - Awaitable[businessidentity.BusinessIdentity] - ]]: - raise NotImplementedError() - - @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - Union[ - businessidentity.BusinessIdentity, - Awaitable[businessidentity.BusinessIdentity] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'BusinessIdentityServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py deleted file mode 100644 index 8365cef3bc93..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc.py +++ /dev/null @@ -1,375 +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.shopping.merchant_accounts_v1beta.types import businessidentity -from .base import BusinessIdentityServiceTransport, 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.accounts.v1beta.BusinessIdentityService", - "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.accounts.v1beta.BusinessIdentityService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class BusinessIdentityServiceGrpcTransport(BusinessIdentityServiceTransport): - """gRPC backend transport for BusinessIdentityService. - - Service to support `business - identity `__ - API. - - 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 get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - businessidentity.BusinessIdentity]: - r"""Return a callable for the get business identity method over gRPC. - - Retrieves the business identity of an account. - - Returns: - Callable[[~.GetBusinessIdentityRequest], - ~.BusinessIdentity]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_business_identity' not in self._stubs: - self._stubs['get_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/GetBusinessIdentity', - request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, - response_deserializer=businessidentity.BusinessIdentity.deserialize, - ) - return self._stubs['get_business_identity'] - - @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - businessidentity.BusinessIdentity]: - r"""Return a callable for the update business identity method over gRPC. - - Updates the business identity of an account. - Executing this method requires admin access. - - Returns: - Callable[[~.UpdateBusinessIdentityRequest], - ~.BusinessIdentity]: - 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 'update_business_identity' not in self._stubs: - self._stubs['update_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/UpdateBusinessIdentity', - request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, - response_deserializer=businessidentity.BusinessIdentity.deserialize, - ) - return self._stubs['update_business_identity'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'BusinessIdentityServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py deleted file mode 100644 index 7346ea703c54..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,401 +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.shopping.merchant_accounts_v1beta.types import businessidentity -from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import BusinessIdentityServiceGrpcTransport - -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.accounts.v1beta.BusinessIdentityService", - "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.accounts.v1beta.BusinessIdentityService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class BusinessIdentityServiceGrpcAsyncIOTransport(BusinessIdentityServiceTransport): - """gRPC AsyncIO backend transport for BusinessIdentityService. - - Service to support `business - identity `__ - API. - - 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 get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - Awaitable[businessidentity.BusinessIdentity]]: - r"""Return a callable for the get business identity method over gRPC. - - Retrieves the business identity of an account. - - Returns: - Callable[[~.GetBusinessIdentityRequest], - Awaitable[~.BusinessIdentity]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_business_identity' not in self._stubs: - self._stubs['get_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/GetBusinessIdentity', - request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, - response_deserializer=businessidentity.BusinessIdentity.deserialize, - ) - return self._stubs['get_business_identity'] - - @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - Awaitable[businessidentity.BusinessIdentity]]: - r"""Return a callable for the update business identity method over gRPC. - - Updates the business identity of an account. - Executing this method requires admin access. - - Returns: - Callable[[~.UpdateBusinessIdentityRequest], - Awaitable[~.BusinessIdentity]]: - 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 'update_business_identity' not in self._stubs: - self._stubs['update_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessIdentityService/UpdateBusinessIdentity', - request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, - response_deserializer=businessidentity.BusinessIdentity.deserialize, - ) - return self._stubs['update_business_identity'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_business_identity: self._wrap_method( - self.get_business_identity, - default_timeout=None, - client_info=client_info, - ), - self.update_business_identity: self._wrap_method( - self.update_business_identity, - 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__ = ( - 'BusinessIdentityServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py deleted file mode 100644 index f1c66a816840..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest.py +++ /dev/null @@ -1,532 +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.shopping.merchant_accounts_v1beta.types import businessidentity - - -from .rest_base import _BaseBusinessIdentityServiceRestTransport -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 BusinessIdentityServiceRestInterceptor: - """Interceptor for BusinessIdentityService. - - 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 BusinessIdentityServiceRestTransport. - - .. code-block:: python - class MyCustomBusinessIdentityServiceInterceptor(BusinessIdentityServiceRestInterceptor): - def pre_get_business_identity(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_business_identity(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_business_identity(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_business_identity(self, response): - logging.log(f"Received response: {response}") - return response - - transport = BusinessIdentityServiceRestTransport(interceptor=MyCustomBusinessIdentityServiceInterceptor()) - client = BusinessIdentityServiceClient(transport=transport) - - - """ - def pre_get_business_identity(self, request: businessidentity.GetBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_business_identity - - Override in a subclass to manipulate the request or metadata - before they are sent to the BusinessIdentityService server. - """ - return request, metadata - - def post_get_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: - """Post-rpc interceptor for get_business_identity - - DEPRECATED. Please use the `post_get_business_identity_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the BusinessIdentityService server but before - it is returned to user code. This `post_get_business_identity` interceptor runs - before the `post_get_business_identity_with_metadata` interceptor. - """ - return response - - def post_get_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_business_identity - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the BusinessIdentityService server but before it is returned to user code. - - We recommend only using this `post_get_business_identity_with_metadata` - interceptor in new development instead of the `post_get_business_identity` interceptor. - When both interceptors are used, this `post_get_business_identity_with_metadata` interceptor runs after the - `post_get_business_identity` interceptor. The (possibly modified) response returned by - `post_get_business_identity` will be passed to - `post_get_business_identity_with_metadata`. - """ - return response, metadata - - def pre_update_business_identity(self, request: businessidentity.UpdateBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_business_identity - - Override in a subclass to manipulate the request or metadata - before they are sent to the BusinessIdentityService server. - """ - return request, metadata - - def post_update_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: - """Post-rpc interceptor for update_business_identity - - DEPRECATED. Please use the `post_update_business_identity_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the BusinessIdentityService server but before - it is returned to user code. This `post_update_business_identity` interceptor runs - before the `post_update_business_identity_with_metadata` interceptor. - """ - return response - - def post_update_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_business_identity - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the BusinessIdentityService server but before it is returned to user code. - - We recommend only using this `post_update_business_identity_with_metadata` - interceptor in new development instead of the `post_update_business_identity` interceptor. - When both interceptors are used, this `post_update_business_identity_with_metadata` interceptor runs after the - `post_update_business_identity` interceptor. The (possibly modified) response returned by - `post_update_business_identity` will be passed to - `post_update_business_identity_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class BusinessIdentityServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: BusinessIdentityServiceRestInterceptor - - -class BusinessIdentityServiceRestTransport(_BaseBusinessIdentityServiceRestTransport): - """REST backend synchronous transport for BusinessIdentityService. - - Service to support `business - identity `__ - API. - - 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[BusinessIdentityServiceRestInterceptor] = 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 BusinessIdentityServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity, BusinessIdentityServiceRestStub): - def __hash__(self): - return hash("BusinessIdentityServiceRestTransport.GetBusinessIdentity") - - @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: businessidentity.GetBusinessIdentityRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessidentity.BusinessIdentity: - r"""Call the get business identity method over HTTP. - - Args: - request (~.businessidentity.GetBusinessIdentityRequest): - The request object. Request message for the ``GetBusinessIdentity`` 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: - ~.businessidentity.BusinessIdentity: - Collection of information related to the `identity of a - business `__. - - """ - - http_options = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_http_options() - - request, metadata = self._interceptor.pre_get_business_identity(request, metadata) - transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessIdentityServiceClient.GetBusinessIdentity", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "rpcName": "GetBusinessIdentity", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = BusinessIdentityServiceRestTransport._GetBusinessIdentity._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 = businessidentity.BusinessIdentity() - pb_resp = businessidentity.BusinessIdentity.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_business_identity(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_business_identity_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = businessidentity.BusinessIdentity.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.accounts_v1beta.BusinessIdentityServiceClient.get_business_identity", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "rpcName": "GetBusinessIdentity", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity, BusinessIdentityServiceRestStub): - def __hash__(self): - return hash("BusinessIdentityServiceRestTransport.UpdateBusinessIdentity") - - @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: businessidentity.UpdateBusinessIdentityRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessidentity.BusinessIdentity: - r"""Call the update business identity method over HTTP. - - Args: - request (~.businessidentity.UpdateBusinessIdentityRequest): - The request object. Request message for the ``UpdateBusinessIdentity`` - 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: - ~.businessidentity.BusinessIdentity: - Collection of information related to the `identity of a - business `__. - - """ - - http_options = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_http_options() - - request, metadata = self._interceptor.pre_update_business_identity(request, metadata) - transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_transcoded_request(http_options, request) - - body = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessIdentityServiceClient.UpdateBusinessIdentity", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "rpcName": "UpdateBusinessIdentity", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = BusinessIdentityServiceRestTransport._UpdateBusinessIdentity._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 = businessidentity.BusinessIdentity() - pb_resp = businessidentity.BusinessIdentity.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_business_identity(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_business_identity_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = businessidentity.BusinessIdentity.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.accounts_v1beta.BusinessIdentityServiceClient.update_business_identity", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "rpcName": "UpdateBusinessIdentity", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - businessidentity.BusinessIdentity]: - # 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._GetBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - businessidentity.BusinessIdentity]: - # 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._UpdateBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'BusinessIdentityServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py deleted file mode 100644 index 1294de519fd2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_identity_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import businessidentity - - -class _BaseBusinessIdentityServiceRestTransport(BusinessIdentityServiceTransport): - """Base REST backend transport for BusinessIdentityService. - - 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 _BaseGetBusinessIdentity: - 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': '/accounts/v1beta/{name=accounts/*/businessIdentity}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = businessidentity.GetBusinessIdentityRequest.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(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateBusinessIdentity: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{business_identity.name=accounts/*/businessIdentity}', - 'body': 'business_identity', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = businessidentity.UpdateBusinessIdentityRequest.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(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseBusinessIdentityServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py deleted file mode 100644 index e96e7e15208b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/async_client.py +++ /dev/null @@ -1,488 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import businessinfo -from google.shopping.merchant_accounts_v1beta.types import customerservice -from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate -from google.type import phone_number_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore -from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport -from .client import BusinessInfoServiceClient - -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 BusinessInfoServiceAsyncClient: - """Service to support business info API.""" - - _client: BusinessInfoServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = BusinessInfoServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = BusinessInfoServiceClient._DEFAULT_UNIVERSE - - business_info_path = staticmethod(BusinessInfoServiceClient.business_info_path) - parse_business_info_path = staticmethod(BusinessInfoServiceClient.parse_business_info_path) - common_billing_account_path = staticmethod(BusinessInfoServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BusinessInfoServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(BusinessInfoServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(BusinessInfoServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(BusinessInfoServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(BusinessInfoServiceClient.parse_common_organization_path) - common_project_path = staticmethod(BusinessInfoServiceClient.common_project_path) - parse_common_project_path = staticmethod(BusinessInfoServiceClient.parse_common_project_path) - common_location_path = staticmethod(BusinessInfoServiceClient.common_location_path) - parse_common_location_path = staticmethod(BusinessInfoServiceClient.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: - BusinessInfoServiceAsyncClient: The constructed client. - """ - return BusinessInfoServiceClient.from_service_account_info.__func__(BusinessInfoServiceAsyncClient, 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: - BusinessInfoServiceAsyncClient: The constructed client. - """ - return BusinessInfoServiceClient.from_service_account_file.__func__(BusinessInfoServiceAsyncClient, 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 BusinessInfoServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> BusinessInfoServiceTransport: - """Returns the transport used by the client instance. - - Returns: - BusinessInfoServiceTransport: 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 = BusinessInfoServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the business info 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,BusinessInfoServiceTransport,Callable[..., BusinessInfoServiceTransport]]]): - 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 BusinessInfoServiceTransport 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 = BusinessInfoServiceClient( - 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.accounts_v1beta.BusinessInfoServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "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.accounts.v1beta.BusinessInfoService", - "credentialsType": None, - } - ) - - async def get_business_info(self, - request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: - r"""Retrieves the business info of an 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_accounts_v1beta - - async def sample_get_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.get_business_info(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest, dict]]): - The request object. Request message for the ``GetBusinessInfo`` method. - name (:class:`str`): - Required. The resource name of the business info. - Format: ``accounts/{account}/businessInfo`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.BusinessInfo: - Collection of information related to - a business. - - """ - # 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, businessinfo.GetBusinessInfoRequest): - request = businessinfo.GetBusinessInfoRequest(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.get_business_info] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_business_info(self, - request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, - *, - business_info: Optional[businessinfo.BusinessInfo] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: - r"""Updates the business info of an account. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_update_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( - ) - - # Make the request - response = await client.update_business_info(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest, dict]]): - The request object. Request message for the ``UpdateBusinessInfo`` method. - business_info (:class:`google.shopping.merchant_accounts_v1beta.types.BusinessInfo`): - Required. The new version of the - business info. - - This corresponds to the ``business_info`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessInfo: - Collection of information related to - a business. - - """ - # 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 = [business_info, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, businessinfo.UpdateBusinessInfoRequest): - request = businessinfo.UpdateBusinessInfoRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if business_info is not None: - request.business_info = business_info - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_info] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_info.name", request.business_info.name), - )), - ) - - # 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 __aenter__(self) -> "BusinessInfoServiceAsyncClient": - 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__ = ( - "BusinessInfoServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py deleted file mode 100644 index bb89b973829c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/client.py +++ /dev/null @@ -1,847 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import businessinfo -from google.shopping.merchant_accounts_v1beta.types import customerservice -from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate -from google.type import phone_number_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore -from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import BusinessInfoServiceGrpcTransport -from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport -from .transports.rest import BusinessInfoServiceRestTransport - - -class BusinessInfoServiceClientMeta(type): - """Metaclass for the BusinessInfoService 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[BusinessInfoServiceTransport]] - _transport_registry["grpc"] = BusinessInfoServiceGrpcTransport - _transport_registry["grpc_asyncio"] = BusinessInfoServiceGrpcAsyncIOTransport - _transport_registry["rest"] = BusinessInfoServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[BusinessInfoServiceTransport]: - """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 BusinessInfoServiceClient(metaclass=BusinessInfoServiceClientMeta): - """Service to support business info API.""" - - @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: - BusinessInfoServiceClient: 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: - BusinessInfoServiceClient: 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) -> BusinessInfoServiceTransport: - """Returns the transport used by the client instance. - - Returns: - BusinessInfoServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def business_info_path(account: str,) -> str: - """Returns a fully-qualified business_info string.""" - return "accounts/{account}/businessInfo".format(account=account, ) - - @staticmethod - def parse_business_info_path(path: str) -> Dict[str,str]: - """Parses a business_info path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/businessInfo$", 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 = BusinessInfoServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = BusinessInfoServiceClient._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 = BusinessInfoServiceClient._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, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the business info 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,BusinessInfoServiceTransport,Callable[..., BusinessInfoServiceTransport]]]): - 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 BusinessInfoServiceTransport 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 = BusinessInfoServiceClient._read_environment_variables() - self._client_cert_source = BusinessInfoServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = BusinessInfoServiceClient._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, BusinessInfoServiceTransport) - if transport_provided: - # transport is a BusinessInfoServiceTransport 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(BusinessInfoServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - BusinessInfoServiceClient._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[BusinessInfoServiceTransport], Callable[..., BusinessInfoServiceTransport]] = ( - BusinessInfoServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., BusinessInfoServiceTransport], 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.accounts_v1beta.BusinessInfoServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "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.accounts.v1beta.BusinessInfoService", - "credentialsType": None, - } - ) - - def get_business_info(self, - request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: - r"""Retrieves the business info of an 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_accounts_v1beta - - def sample_get_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessInfoRequest( - name="name_value", - ) - - # Make the request - response = client.get_business_info(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest, dict]): - The request object. Request message for the ``GetBusinessInfo`` method. - name (str): - Required. The resource name of the business info. - Format: ``accounts/{account}/businessInfo`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.BusinessInfo: - Collection of information related to - a business. - - """ - # 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, businessinfo.GetBusinessInfoRequest): - request = businessinfo.GetBusinessInfoRequest(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.get_business_info] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_business_info(self, - request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, - *, - business_info: Optional[businessinfo.BusinessInfo] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: - r"""Updates the business info of an account. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - def sample_update_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( - ) - - # Make the request - response = client.update_business_info(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest, dict]): - The request object. Request message for the ``UpdateBusinessInfo`` method. - business_info (google.shopping.merchant_accounts_v1beta.types.BusinessInfo): - Required. The new version of the - business info. - - This corresponds to the ``business_info`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.BusinessInfo: - Collection of information related to - a business. - - """ - # 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 = [business_info, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, businessinfo.UpdateBusinessInfoRequest): - request = businessinfo.UpdateBusinessInfoRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if business_info is not None: - request.business_info = business_info - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_business_info] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_info.name", request.business_info.name), - )), - ) - - # 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 __enter__(self) -> "BusinessInfoServiceClient": - 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__ = ( - "BusinessInfoServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst deleted file mode 100644 index 1024050406f9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`BusinessInfoServiceTransport` is the ABC for all transports. -- public child `BusinessInfoServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `BusinessInfoServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseBusinessInfoServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `BusinessInfoServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py deleted file mode 100644 index fef070afb0f2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import businessinfo - -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 BusinessInfoServiceTransport(abc.ABC): - """Abstract transport class for BusinessInfoService.""" - - 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.get_business_info: gapic_v1.method.wrap_method( - self.get_business_info, - default_timeout=None, - client_info=client_info, - ), - self.update_business_info: gapic_v1.method.wrap_method( - self.update_business_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! - """ - raise NotImplementedError() - - @property - def get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - Union[ - businessinfo.BusinessInfo, - Awaitable[businessinfo.BusinessInfo] - ]]: - raise NotImplementedError() - - @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - Union[ - businessinfo.BusinessInfo, - Awaitable[businessinfo.BusinessInfo] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'BusinessInfoServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py deleted file mode 100644 index dc1e8c008e62..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc.py +++ /dev/null @@ -1,373 +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.shopping.merchant_accounts_v1beta.types import businessinfo -from .base import BusinessInfoServiceTransport, 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.accounts.v1beta.BusinessInfoService", - "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.accounts.v1beta.BusinessInfoService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class BusinessInfoServiceGrpcTransport(BusinessInfoServiceTransport): - """gRPC backend transport for BusinessInfoService. - - Service to support business info API. - - 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 get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - businessinfo.BusinessInfo]: - r"""Return a callable for the get business info method over gRPC. - - Retrieves the business info of an account. - - Returns: - Callable[[~.GetBusinessInfoRequest], - ~.BusinessInfo]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_business_info' not in self._stubs: - self._stubs['get_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/GetBusinessInfo', - request_serializer=businessinfo.GetBusinessInfoRequest.serialize, - response_deserializer=businessinfo.BusinessInfo.deserialize, - ) - return self._stubs['get_business_info'] - - @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - businessinfo.BusinessInfo]: - r"""Return a callable for the update business info method over gRPC. - - Updates the business info of an account. Executing - this method requires admin access. - - Returns: - Callable[[~.UpdateBusinessInfoRequest], - ~.BusinessInfo]: - 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 'update_business_info' not in self._stubs: - self._stubs['update_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/UpdateBusinessInfo', - request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, - response_deserializer=businessinfo.BusinessInfo.deserialize, - ) - return self._stubs['update_business_info'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'BusinessInfoServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py deleted file mode 100644 index d5f55c65110b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,399 +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.shopping.merchant_accounts_v1beta.types import businessinfo -from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import BusinessInfoServiceGrpcTransport - -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.accounts.v1beta.BusinessInfoService", - "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.accounts.v1beta.BusinessInfoService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class BusinessInfoServiceGrpcAsyncIOTransport(BusinessInfoServiceTransport): - """gRPC AsyncIO backend transport for BusinessInfoService. - - Service to support business info API. - - 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 get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - Awaitable[businessinfo.BusinessInfo]]: - r"""Return a callable for the get business info method over gRPC. - - Retrieves the business info of an account. - - Returns: - Callable[[~.GetBusinessInfoRequest], - Awaitable[~.BusinessInfo]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_business_info' not in self._stubs: - self._stubs['get_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/GetBusinessInfo', - request_serializer=businessinfo.GetBusinessInfoRequest.serialize, - response_deserializer=businessinfo.BusinessInfo.deserialize, - ) - return self._stubs['get_business_info'] - - @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - Awaitable[businessinfo.BusinessInfo]]: - r"""Return a callable for the update business info method over gRPC. - - Updates the business info of an account. Executing - this method requires admin access. - - Returns: - Callable[[~.UpdateBusinessInfoRequest], - Awaitable[~.BusinessInfo]]: - 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 'update_business_info' not in self._stubs: - self._stubs['update_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.BusinessInfoService/UpdateBusinessInfo', - request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, - response_deserializer=businessinfo.BusinessInfo.deserialize, - ) - return self._stubs['update_business_info'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_business_info: self._wrap_method( - self.get_business_info, - default_timeout=None, - client_info=client_info, - ), - self.update_business_info: self._wrap_method( - self.update_business_info, - 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__ = ( - 'BusinessInfoServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py deleted file mode 100644 index 9e8ce6c7ea6c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest.py +++ /dev/null @@ -1,529 +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.shopping.merchant_accounts_v1beta.types import businessinfo - - -from .rest_base import _BaseBusinessInfoServiceRestTransport -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 BusinessInfoServiceRestInterceptor: - """Interceptor for BusinessInfoService. - - 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 BusinessInfoServiceRestTransport. - - .. code-block:: python - class MyCustomBusinessInfoServiceInterceptor(BusinessInfoServiceRestInterceptor): - def pre_get_business_info(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_business_info(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_business_info(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_business_info(self, response): - logging.log(f"Received response: {response}") - return response - - transport = BusinessInfoServiceRestTransport(interceptor=MyCustomBusinessInfoServiceInterceptor()) - client = BusinessInfoServiceClient(transport=transport) - - - """ - def pre_get_business_info(self, request: businessinfo.GetBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_business_info - - Override in a subclass to manipulate the request or metadata - before they are sent to the BusinessInfoService server. - """ - return request, metadata - - def post_get_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: - """Post-rpc interceptor for get_business_info - - DEPRECATED. Please use the `post_get_business_info_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the BusinessInfoService server but before - it is returned to user code. This `post_get_business_info` interceptor runs - before the `post_get_business_info_with_metadata` interceptor. - """ - return response - - def post_get_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_business_info - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the BusinessInfoService server but before it is returned to user code. - - We recommend only using this `post_get_business_info_with_metadata` - interceptor in new development instead of the `post_get_business_info` interceptor. - When both interceptors are used, this `post_get_business_info_with_metadata` interceptor runs after the - `post_get_business_info` interceptor. The (possibly modified) response returned by - `post_get_business_info` will be passed to - `post_get_business_info_with_metadata`. - """ - return response, metadata - - def pre_update_business_info(self, request: businessinfo.UpdateBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_business_info - - Override in a subclass to manipulate the request or metadata - before they are sent to the BusinessInfoService server. - """ - return request, metadata - - def post_update_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: - """Post-rpc interceptor for update_business_info - - DEPRECATED. Please use the `post_update_business_info_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the BusinessInfoService server but before - it is returned to user code. This `post_update_business_info` interceptor runs - before the `post_update_business_info_with_metadata` interceptor. - """ - return response - - def post_update_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_business_info - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the BusinessInfoService server but before it is returned to user code. - - We recommend only using this `post_update_business_info_with_metadata` - interceptor in new development instead of the `post_update_business_info` interceptor. - When both interceptors are used, this `post_update_business_info_with_metadata` interceptor runs after the - `post_update_business_info` interceptor. The (possibly modified) response returned by - `post_update_business_info` will be passed to - `post_update_business_info_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class BusinessInfoServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: BusinessInfoServiceRestInterceptor - - -class BusinessInfoServiceRestTransport(_BaseBusinessInfoServiceRestTransport): - """REST backend synchronous transport for BusinessInfoService. - - Service to support business info API. - - 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[BusinessInfoServiceRestInterceptor] = 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 BusinessInfoServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo, BusinessInfoServiceRestStub): - def __hash__(self): - return hash("BusinessInfoServiceRestTransport.GetBusinessInfo") - - @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: businessinfo.GetBusinessInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessinfo.BusinessInfo: - r"""Call the get business info method over HTTP. - - Args: - request (~.businessinfo.GetBusinessInfoRequest): - The request object. Request message for the ``GetBusinessInfo`` 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: - ~.businessinfo.BusinessInfo: - Collection of information related to - a business. - - """ - - http_options = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_http_options() - - request, metadata = self._interceptor.pre_get_business_info(request, metadata) - transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessInfoServiceClient.GetBusinessInfo", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "rpcName": "GetBusinessInfo", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = BusinessInfoServiceRestTransport._GetBusinessInfo._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 = businessinfo.BusinessInfo() - pb_resp = businessinfo.BusinessInfo.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_business_info(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_business_info_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = businessinfo.BusinessInfo.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.accounts_v1beta.BusinessInfoServiceClient.get_business_info", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "rpcName": "GetBusinessInfo", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo, BusinessInfoServiceRestStub): - def __hash__(self): - return hash("BusinessInfoServiceRestTransport.UpdateBusinessInfo") - - @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: businessinfo.UpdateBusinessInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessinfo.BusinessInfo: - r"""Call the update business info method over HTTP. - - Args: - request (~.businessinfo.UpdateBusinessInfoRequest): - The request object. Request message for the ``UpdateBusinessInfo`` 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: - ~.businessinfo.BusinessInfo: - Collection of information related to - a business. - - """ - - http_options = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_http_options() - - request, metadata = self._interceptor.pre_update_business_info(request, metadata) - transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_transcoded_request(http_options, request) - - body = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.BusinessInfoServiceClient.UpdateBusinessInfo", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "rpcName": "UpdateBusinessInfo", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = BusinessInfoServiceRestTransport._UpdateBusinessInfo._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 = businessinfo.BusinessInfo() - pb_resp = businessinfo.BusinessInfo.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_business_info(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_business_info_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = businessinfo.BusinessInfo.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.accounts_v1beta.BusinessInfoServiceClient.update_business_info", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "rpcName": "UpdateBusinessInfo", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - businessinfo.BusinessInfo]: - # 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._GetBusinessInfo(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - businessinfo.BusinessInfo]: - # 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._UpdateBusinessInfo(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'BusinessInfoServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py deleted file mode 100644 index 769d8b6f81f0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import businessinfo - - -class _BaseBusinessInfoServiceRestTransport(BusinessInfoServiceTransport): - """Base REST backend transport for BusinessInfoService. - - 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 _BaseGetBusinessInfo: - 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': '/accounts/v1beta/{name=accounts/*/businessInfo}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = businessinfo.GetBusinessInfoRequest.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(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateBusinessInfo: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{business_info.name=accounts/*/businessInfo}', - 'body': 'business_info', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = businessinfo.UpdateBusinessInfoRequest.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(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseBusinessInfoServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/__init__.py deleted file mode 100644 index d3119c55bf22..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_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 CheckoutSettingsServiceClient -from .async_client import CheckoutSettingsServiceAsyncClient - -__all__ = ( - 'CheckoutSettingsServiceClient', - 'CheckoutSettingsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py deleted file mode 100644 index 818e9eeda5c6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/async_client.py +++ /dev/null @@ -1,706 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import checkoutsettings -from google.shopping.type.types import types -from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport -from .client import CheckoutSettingsServiceClient - -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 CheckoutSettingsServiceAsyncClient: - """Service for supporting `checkout - settings `__. - """ - - _client: CheckoutSettingsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - - checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.checkout_settings_path) - parse_checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.parse_checkout_settings_path) - common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CheckoutSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CheckoutSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CheckoutSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CheckoutSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CheckoutSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(CheckoutSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(CheckoutSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(CheckoutSettingsServiceClient.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: - CheckoutSettingsServiceAsyncClient: The constructed client. - """ - return CheckoutSettingsServiceClient.from_service_account_info.__func__(CheckoutSettingsServiceAsyncClient, 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: - CheckoutSettingsServiceAsyncClient: The constructed client. - """ - return CheckoutSettingsServiceClient.from_service_account_file.__func__(CheckoutSettingsServiceAsyncClient, 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 CheckoutSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CheckoutSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CheckoutSettingsServiceTransport: 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 = CheckoutSettingsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the checkout settings 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,CheckoutSettingsServiceTransport,Callable[..., CheckoutSettingsServiceTransport]]]): - 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 CheckoutSettingsServiceTransport 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 = CheckoutSettingsServiceClient( - 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.accounts_v1beta.CheckoutSettingsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "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.accounts.v1beta.CheckoutSettingsService", - "credentialsType": None, - } - ) - - async def get_checkout_settings(self, - request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: - r"""Gets ``CheckoutSettings`` for the given merchant. This includes - information about review state, enrollment state and URL - settings. - - .. 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_accounts_v1beta - - async def sample_get_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_checkout_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest, dict]]): - The request object. Request message for ``GetCheckoutSettings`` method. - name (:class:`str`): - Required. The name/identifier of the merchant account. - Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.CheckoutSettings: - [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for - a specific merchant. - - """ - # 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, checkoutsettings.GetCheckoutSettingsRequest): - request = checkoutsettings.GetCheckoutSettingsRequest(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.get_checkout_settings] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_checkout_settings(self, - request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: - r"""Creates ``CheckoutSettings`` for the given merchant. - - .. 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_accounts_v1beta - - async def sample_create_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_checkout_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest, dict]]): - The request object. Request message for the ``CreateCheckoutSettings`` - method. - parent (:class:`str`): - Required. The merchant account for which the - ``CheckoutSettings`` will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - checkout_settings (:class:`google.shopping.merchant_accounts_v1beta.types.CheckoutSettings`): - Required. The ``CheckoutSettings`` object to create. - This corresponds to the ``checkout_settings`` 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_accounts_v1beta.types.CheckoutSettings: - [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for - a specific merchant. - - """ - # 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, checkout_settings] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, checkoutsettings.CreateCheckoutSettingsRequest): - request = checkoutsettings.CreateCheckoutSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if checkout_settings is not None: - request.checkout_settings = checkout_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_checkout_settings] - - # 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 update_checkout_settings(self, - request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, - *, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: - r"""Updates ``CheckoutSettings`` for the given merchant. - - .. 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_accounts_v1beta - - async def sample_update_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( - ) - - # Make the request - response = await client.update_checkout_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest, dict]]): - The request object. Request message for the ``UpdateCheckoutSettings`` - method. - checkout_settings (:class:`google.shopping.merchant_accounts_v1beta.types.CheckoutSettings`): - Required. The updated version of the - ``CheckoutSettings``. The ``name`` field is used to - identify the ``CheckoutSettings``. Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - - This corresponds to the ``checkout_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being updated. The following - fields are supported (in both ``snake_case`` and - ``lowerCamelCase``): - - - ``eligible_destinations`` - - ``uri_settings`` - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.CheckoutSettings: - [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for - a specific merchant. - - """ - # 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 = [checkout_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, checkoutsettings.UpdateCheckoutSettingsRequest): - request = checkoutsettings.UpdateCheckoutSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if checkout_settings is not None: - request.checkout_settings = checkout_settings - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_checkout_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("checkout_settings.name", request.checkout_settings.name), - )), - ) - - # 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_checkout_settings(self, - request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, - *, - name: 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 ``CheckoutSettings`` and unenrolls merchant from - ``Checkout`` program. - - .. 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_accounts_v1beta - - async def sample_delete_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - await client.delete_checkout_settings(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest, dict]]): - The request object. Request message for the ``DeleteCheckoutSettings`` - method. - name (:class:`str`): - Required. The name/identifier of the merchant account. - Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - - 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, checkoutsettings.DeleteCheckoutSettingsRequest): - request = checkoutsettings.DeleteCheckoutSettingsRequest(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_checkout_settings] - - # 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) -> "CheckoutSettingsServiceAsyncClient": - 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__ = ( - "CheckoutSettingsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py deleted file mode 100644 index 75bc7c0c2b6d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/client.py +++ /dev/null @@ -1,1063 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import checkoutsettings -from google.shopping.type.types import types -from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CheckoutSettingsServiceGrpcTransport -from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport -from .transports.rest import CheckoutSettingsServiceRestTransport - - -class CheckoutSettingsServiceClientMeta(type): - """Metaclass for the CheckoutSettingsService 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[CheckoutSettingsServiceTransport]] - _transport_registry["grpc"] = CheckoutSettingsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CheckoutSettingsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = CheckoutSettingsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CheckoutSettingsServiceTransport]: - """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 CheckoutSettingsServiceClient(metaclass=CheckoutSettingsServiceClientMeta): - """Service for supporting `checkout - settings `__. - """ - - @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: - CheckoutSettingsServiceClient: 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: - CheckoutSettingsServiceClient: 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) -> CheckoutSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CheckoutSettingsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def checkout_settings_path(account: str,program: str,) -> str: - """Returns a fully-qualified checkout_settings string.""" - return "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) - - @staticmethod - def parse_checkout_settings_path(path: str) -> Dict[str,str]: - """Parses a checkout_settings path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/programs/(?P.+?)/checkoutSettings$", 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 = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient._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, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the checkout settings 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,CheckoutSettingsServiceTransport,Callable[..., CheckoutSettingsServiceTransport]]]): - 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 CheckoutSettingsServiceTransport 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 = CheckoutSettingsServiceClient._read_environment_variables() - self._client_cert_source = CheckoutSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = CheckoutSettingsServiceClient._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, CheckoutSettingsServiceTransport) - if transport_provided: - # transport is a CheckoutSettingsServiceTransport 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(CheckoutSettingsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - CheckoutSettingsServiceClient._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[CheckoutSettingsServiceTransport], Callable[..., CheckoutSettingsServiceTransport]] = ( - CheckoutSettingsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., CheckoutSettingsServiceTransport], 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.accounts_v1beta.CheckoutSettingsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "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.accounts.v1beta.CheckoutSettingsService", - "credentialsType": None, - } - ) - - def get_checkout_settings(self, - request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: - r"""Gets ``CheckoutSettings`` for the given merchant. This includes - information about review state, enrollment state and URL - settings. - - .. 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_accounts_v1beta - - def sample_get_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_checkout_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest, dict]): - The request object. Request message for ``GetCheckoutSettings`` method. - name (str): - Required. The name/identifier of the merchant account. - Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.CheckoutSettings: - [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for - a specific merchant. - - """ - # 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, checkoutsettings.GetCheckoutSettingsRequest): - request = checkoutsettings.GetCheckoutSettingsRequest(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.get_checkout_settings] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_checkout_settings(self, - request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: - r"""Creates ``CheckoutSettings`` for the given merchant. - - .. 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_accounts_v1beta - - def sample_create_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_checkout_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest, dict]): - The request object. Request message for the ``CreateCheckoutSettings`` - method. - parent (str): - Required. The merchant account for which the - ``CheckoutSettings`` will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): - Required. The ``CheckoutSettings`` object to create. - This corresponds to the ``checkout_settings`` 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_accounts_v1beta.types.CheckoutSettings: - [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for - a specific merchant. - - """ - # 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, checkout_settings] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, checkoutsettings.CreateCheckoutSettingsRequest): - request = checkoutsettings.CreateCheckoutSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if checkout_settings is not None: - request.checkout_settings = checkout_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_checkout_settings] - - # 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 update_checkout_settings(self, - request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, - *, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: - r"""Updates ``CheckoutSettings`` for the given merchant. - - .. 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_accounts_v1beta - - def sample_update_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( - ) - - # Make the request - response = client.update_checkout_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest, dict]): - The request object. Request message for the ``UpdateCheckoutSettings`` - method. - checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): - Required. The updated version of the - ``CheckoutSettings``. The ``name`` field is used to - identify the ``CheckoutSettings``. Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - - This corresponds to the ``checkout_settings`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. The following - fields are supported (in both ``snake_case`` and - ``lowerCamelCase``): - - - ``eligible_destinations`` - - ``uri_settings`` - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.CheckoutSettings: - [CheckoutSettings](https://support.google.com/merchants/answer/13945960) for - a specific merchant. - - """ - # 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 = [checkout_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, checkoutsettings.UpdateCheckoutSettingsRequest): - request = checkoutsettings.UpdateCheckoutSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if checkout_settings is not None: - request.checkout_settings = checkout_settings - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_checkout_settings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("checkout_settings.name", request.checkout_settings.name), - )), - ) - - # 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_checkout_settings(self, - request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, - *, - name: 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 ``CheckoutSettings`` and unenrolls merchant from - ``Checkout`` program. - - .. 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_accounts_v1beta - - def sample_delete_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - client.delete_checkout_settings(request=request) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest, dict]): - The request object. Request message for the ``DeleteCheckoutSettings`` - method. - name (str): - Required. The name/identifier of the merchant account. - Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - - 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, checkoutsettings.DeleteCheckoutSettingsRequest): - request = checkoutsettings.DeleteCheckoutSettingsRequest(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_checkout_settings] - - # 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) -> "CheckoutSettingsServiceClient": - 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__ = ( - "CheckoutSettingsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst deleted file mode 100644 index 95c14e3fa6f8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`CheckoutSettingsServiceTransport` is the ABC for all transports. -- public child `CheckoutSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `CheckoutSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseCheckoutSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `CheckoutSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py deleted file mode 100644 index 55cf215ccd10..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/base.py +++ /dev/null @@ -1,202 +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_accounts_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_accounts_v1beta.types import checkoutsettings - -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 CheckoutSettingsServiceTransport(abc.ABC): - """Abstract transport class for CheckoutSettingsService.""" - - 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.get_checkout_settings: gapic_v1.method.wrap_method( - self.get_checkout_settings, - default_timeout=None, - client_info=client_info, - ), - self.create_checkout_settings: gapic_v1.method.wrap_method( - self.create_checkout_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_checkout_settings: gapic_v1.method.wrap_method( - self.update_checkout_settings, - default_timeout=None, - client_info=client_info, - ), - self.delete_checkout_settings: gapic_v1.method.wrap_method( - self.delete_checkout_settings, - 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 get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - Union[ - checkoutsettings.CheckoutSettings, - Awaitable[checkoutsettings.CheckoutSettings] - ]]: - raise NotImplementedError() - - @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - Union[ - checkoutsettings.CheckoutSettings, - Awaitable[checkoutsettings.CheckoutSettings] - ]]: - raise NotImplementedError() - - @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - Union[ - checkoutsettings.CheckoutSettings, - Awaitable[checkoutsettings.CheckoutSettings] - ]]: - raise NotImplementedError() - - @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CheckoutSettingsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py deleted file mode 100644 index 6a1defe9f5db..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc.py +++ /dev/null @@ -1,429 +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_accounts_v1beta.types import checkoutsettings -from .base import CheckoutSettingsServiceTransport, 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.accounts.v1beta.CheckoutSettingsService", - "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.accounts.v1beta.CheckoutSettingsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class CheckoutSettingsServiceGrpcTransport(CheckoutSettingsServiceTransport): - """gRPC backend transport for CheckoutSettingsService. - - Service for supporting `checkout - settings `__. - - 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 get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: - r"""Return a callable for the get checkout settings method over gRPC. - - Gets ``CheckoutSettings`` for the given merchant. This includes - information about review state, enrollment state and URL - settings. - - Returns: - Callable[[~.GetCheckoutSettingsRequest], - ~.CheckoutSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_checkout_settings' not in self._stubs: - self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/GetCheckoutSettings', - request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, - response_deserializer=checkoutsettings.CheckoutSettings.deserialize, - ) - return self._stubs['get_checkout_settings'] - - @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: - r"""Return a callable for the create checkout settings method over gRPC. - - Creates ``CheckoutSettings`` for the given merchant. - - Returns: - Callable[[~.CreateCheckoutSettingsRequest], - ~.CheckoutSettings]: - 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 'create_checkout_settings' not in self._stubs: - self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/CreateCheckoutSettings', - request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, - response_deserializer=checkoutsettings.CheckoutSettings.deserialize, - ) - return self._stubs['create_checkout_settings'] - - @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: - r"""Return a callable for the update checkout settings method over gRPC. - - Updates ``CheckoutSettings`` for the given merchant. - - Returns: - Callable[[~.UpdateCheckoutSettingsRequest], - ~.CheckoutSettings]: - 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 'update_checkout_settings' not in self._stubs: - self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/UpdateCheckoutSettings', - request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, - response_deserializer=checkoutsettings.CheckoutSettings.deserialize, - ) - return self._stubs['update_checkout_settings'] - - @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete checkout settings method over gRPC. - - Deletes ``CheckoutSettings`` and unenrolls merchant from - ``Checkout`` program. - - Returns: - Callable[[~.DeleteCheckoutSettingsRequest], - ~.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_checkout_settings' not in self._stubs: - self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/DeleteCheckoutSettings', - request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_checkout_settings'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CheckoutSettingsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py deleted file mode 100644 index 8db843ef7fbc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,465 +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_accounts_v1beta.types import checkoutsettings -from .base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CheckoutSettingsServiceGrpcTransport - -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.accounts.v1beta.CheckoutSettingsService", - "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.accounts.v1beta.CheckoutSettingsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class CheckoutSettingsServiceGrpcAsyncIOTransport(CheckoutSettingsServiceTransport): - """gRPC AsyncIO backend transport for CheckoutSettingsService. - - Service for supporting `checkout - settings `__. - - 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 get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - Awaitable[checkoutsettings.CheckoutSettings]]: - r"""Return a callable for the get checkout settings method over gRPC. - - Gets ``CheckoutSettings`` for the given merchant. This includes - information about review state, enrollment state and URL - settings. - - Returns: - Callable[[~.GetCheckoutSettingsRequest], - Awaitable[~.CheckoutSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_checkout_settings' not in self._stubs: - self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/GetCheckoutSettings', - request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, - response_deserializer=checkoutsettings.CheckoutSettings.deserialize, - ) - return self._stubs['get_checkout_settings'] - - @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - Awaitable[checkoutsettings.CheckoutSettings]]: - r"""Return a callable for the create checkout settings method over gRPC. - - Creates ``CheckoutSettings`` for the given merchant. - - Returns: - Callable[[~.CreateCheckoutSettingsRequest], - Awaitable[~.CheckoutSettings]]: - 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 'create_checkout_settings' not in self._stubs: - self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/CreateCheckoutSettings', - request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, - response_deserializer=checkoutsettings.CheckoutSettings.deserialize, - ) - return self._stubs['create_checkout_settings'] - - @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - Awaitable[checkoutsettings.CheckoutSettings]]: - r"""Return a callable for the update checkout settings method over gRPC. - - Updates ``CheckoutSettings`` for the given merchant. - - Returns: - Callable[[~.UpdateCheckoutSettingsRequest], - Awaitable[~.CheckoutSettings]]: - 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 'update_checkout_settings' not in self._stubs: - self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/UpdateCheckoutSettings', - request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, - response_deserializer=checkoutsettings.CheckoutSettings.deserialize, - ) - return self._stubs['update_checkout_settings'] - - @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete checkout settings method over gRPC. - - Deletes ``CheckoutSettings`` and unenrolls merchant from - ``Checkout`` program. - - Returns: - Callable[[~.DeleteCheckoutSettingsRequest], - 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_checkout_settings' not in self._stubs: - self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.CheckoutSettingsService/DeleteCheckoutSettings', - request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_checkout_settings'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_checkout_settings: self._wrap_method( - self.get_checkout_settings, - default_timeout=None, - client_info=client_info, - ), - self.create_checkout_settings: self._wrap_method( - self.create_checkout_settings, - default_timeout=None, - client_info=client_info, - ), - self.update_checkout_settings: self._wrap_method( - self.update_checkout_settings, - default_timeout=None, - client_info=client_info, - ), - self.delete_checkout_settings: self._wrap_method( - self.delete_checkout_settings, - 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__ = ( - 'CheckoutSettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py deleted file mode 100644 index a2a905a21da7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest.py +++ /dev/null @@ -1,815 +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_accounts_v1beta.types import checkoutsettings - - -from .rest_base import _BaseCheckoutSettingsServiceRestTransport -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 CheckoutSettingsServiceRestInterceptor: - """Interceptor for CheckoutSettingsService. - - 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 CheckoutSettingsServiceRestTransport. - - .. code-block:: python - class MyCustomCheckoutSettingsServiceInterceptor(CheckoutSettingsServiceRestInterceptor): - def pre_create_checkout_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_checkout_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_checkout_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_checkout_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_checkout_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_checkout_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_checkout_settings(self, response): - logging.log(f"Received response: {response}") - return response - - transport = CheckoutSettingsServiceRestTransport(interceptor=MyCustomCheckoutSettingsServiceInterceptor()) - client = CheckoutSettingsServiceClient(transport=transport) - - - """ - def pre_create_checkout_settings(self, request: checkoutsettings.CreateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CreateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_checkout_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the CheckoutSettingsService server. - """ - return request, metadata - - def post_create_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: - """Post-rpc interceptor for create_checkout_settings - - DEPRECATED. Please use the `post_create_checkout_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the CheckoutSettingsService server but before - it is returned to user code. This `post_create_checkout_settings` interceptor runs - before the `post_create_checkout_settings_with_metadata` interceptor. - """ - return response - - def post_create_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_checkout_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the CheckoutSettingsService server but before it is returned to user code. - - We recommend only using this `post_create_checkout_settings_with_metadata` - interceptor in new development instead of the `post_create_checkout_settings` interceptor. - When both interceptors are used, this `post_create_checkout_settings_with_metadata` interceptor runs after the - `post_create_checkout_settings` interceptor. The (possibly modified) response returned by - `post_create_checkout_settings` will be passed to - `post_create_checkout_settings_with_metadata`. - """ - return response, metadata - - def pre_delete_checkout_settings(self, request: checkoutsettings.DeleteCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.DeleteCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_checkout_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the CheckoutSettingsService server. - """ - return request, metadata - - def pre_get_checkout_settings(self, request: checkoutsettings.GetCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.GetCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_checkout_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the CheckoutSettingsService server. - """ - return request, metadata - - def post_get_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: - """Post-rpc interceptor for get_checkout_settings - - DEPRECATED. Please use the `post_get_checkout_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the CheckoutSettingsService server but before - it is returned to user code. This `post_get_checkout_settings` interceptor runs - before the `post_get_checkout_settings_with_metadata` interceptor. - """ - return response - - def post_get_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_checkout_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the CheckoutSettingsService server but before it is returned to user code. - - We recommend only using this `post_get_checkout_settings_with_metadata` - interceptor in new development instead of the `post_get_checkout_settings` interceptor. - When both interceptors are used, this `post_get_checkout_settings_with_metadata` interceptor runs after the - `post_get_checkout_settings` interceptor. The (possibly modified) response returned by - `post_get_checkout_settings` will be passed to - `post_get_checkout_settings_with_metadata`. - """ - return response, metadata - - def pre_update_checkout_settings(self, request: checkoutsettings.UpdateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.UpdateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_checkout_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the CheckoutSettingsService server. - """ - return request, metadata - - def post_update_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: - """Post-rpc interceptor for update_checkout_settings - - DEPRECATED. Please use the `post_update_checkout_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the CheckoutSettingsService server but before - it is returned to user code. This `post_update_checkout_settings` interceptor runs - before the `post_update_checkout_settings_with_metadata` interceptor. - """ - return response - - def post_update_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_checkout_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the CheckoutSettingsService server but before it is returned to user code. - - We recommend only using this `post_update_checkout_settings_with_metadata` - interceptor in new development instead of the `post_update_checkout_settings` interceptor. - When both interceptors are used, this `post_update_checkout_settings_with_metadata` interceptor runs after the - `post_update_checkout_settings` interceptor. The (possibly modified) response returned by - `post_update_checkout_settings` will be passed to - `post_update_checkout_settings_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class CheckoutSettingsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: CheckoutSettingsServiceRestInterceptor - - -class CheckoutSettingsServiceRestTransport(_BaseCheckoutSettingsServiceRestTransport): - """REST backend synchronous transport for CheckoutSettingsService. - - Service for supporting `checkout - settings `__. - - 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[CheckoutSettingsServiceRestInterceptor] = 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 CheckoutSettingsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings, CheckoutSettingsServiceRestStub): - def __hash__(self): - return hash("CheckoutSettingsServiceRestTransport.CreateCheckoutSettings") - - @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: checkoutsettings.CreateCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> checkoutsettings.CheckoutSettings: - r"""Call the create checkout settings method over HTTP. - - Args: - request (~.checkoutsettings.CreateCheckoutSettingsRequest): - The request object. Request message for the ``CreateCheckoutSettings`` - 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: - ~.checkoutsettings.CheckoutSettings: - `CheckoutSettings `__ - for a specific merchant. - - """ - - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_http_options() - - request, metadata = self._interceptor.pre_create_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_transcoded_request(http_options, request) - - body = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.CreateCheckoutSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "CreateCheckoutSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CheckoutSettingsServiceRestTransport._CreateCheckoutSettings._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 = checkoutsettings.CheckoutSettings() - pb_resp = checkoutsettings.CheckoutSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_checkout_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_checkout_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1beta.CheckoutSettingsServiceClient.create_checkout_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "CreateCheckoutSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings, CheckoutSettingsServiceRestStub): - def __hash__(self): - return hash("CheckoutSettingsServiceRestTransport.DeleteCheckoutSettings") - - @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: checkoutsettings.DeleteCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete checkout settings method over HTTP. - - Args: - request (~.checkoutsettings.DeleteCheckoutSettingsRequest): - The request object. Request message for the ``DeleteCheckoutSettings`` - 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 = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_http_options() - - request, metadata = self._interceptor.pre_delete_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.DeleteCheckoutSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "DeleteCheckoutSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CheckoutSettingsServiceRestTransport._DeleteCheckoutSettings._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 _GetCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings, CheckoutSettingsServiceRestStub): - def __hash__(self): - return hash("CheckoutSettingsServiceRestTransport.GetCheckoutSettings") - - @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: checkoutsettings.GetCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> checkoutsettings.CheckoutSettings: - r"""Call the get checkout settings method over HTTP. - - Args: - request (~.checkoutsettings.GetCheckoutSettingsRequest): - The request object. Request message for ``GetCheckoutSettings`` 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: - ~.checkoutsettings.CheckoutSettings: - `CheckoutSettings `__ - for a specific merchant. - - """ - - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_http_options() - - request, metadata = self._interceptor.pre_get_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.GetCheckoutSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "GetCheckoutSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CheckoutSettingsServiceRestTransport._GetCheckoutSettings._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 = checkoutsettings.CheckoutSettings() - pb_resp = checkoutsettings.CheckoutSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_checkout_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_checkout_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1beta.CheckoutSettingsServiceClient.get_checkout_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "GetCheckoutSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings, CheckoutSettingsServiceRestStub): - def __hash__(self): - return hash("CheckoutSettingsServiceRestTransport.UpdateCheckoutSettings") - - @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: checkoutsettings.UpdateCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> checkoutsettings.CheckoutSettings: - r"""Call the update checkout settings method over HTTP. - - Args: - request (~.checkoutsettings.UpdateCheckoutSettingsRequest): - The request object. Request message for the ``UpdateCheckoutSettings`` - 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: - ~.checkoutsettings.CheckoutSettings: - `CheckoutSettings `__ - for a specific merchant. - - """ - - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_http_options() - - request, metadata = self._interceptor.pre_update_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_transcoded_request(http_options, request) - - body = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.CheckoutSettingsServiceClient.UpdateCheckoutSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "UpdateCheckoutSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = CheckoutSettingsServiceRestTransport._UpdateCheckoutSettings._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 = checkoutsettings.CheckoutSettings() - pb_resp = checkoutsettings.CheckoutSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_checkout_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_checkout_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1beta.CheckoutSettingsServiceClient.update_checkout_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "rpcName": "UpdateCheckoutSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: - # 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._CreateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - 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._DeleteCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: - # 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._GetCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: - # 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._UpdateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'CheckoutSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py deleted file mode 100644 index 889ee8285a68..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/rest_base.py +++ /dev/null @@ -1,260 +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 CheckoutSettingsServiceTransport, 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_accounts_v1beta.types import checkoutsettings - - -class _BaseCheckoutSettingsServiceRestTransport(CheckoutSettingsServiceTransport): - """Base REST backend transport for CheckoutSettingsService. - - 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 _BaseCreateCheckoutSettings: - 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': '/accounts/v1beta/{parent=accounts/*/programs/*}/checkoutSettings', - 'body': 'checkout_settings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = checkoutsettings.CreateCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteCheckoutSettings: - 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': '/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = checkoutsettings.DeleteCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetCheckoutSettings: - 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': '/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = checkoutsettings.GetCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateCheckoutSettings: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}', - 'body': 'checkout_settings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = checkoutsettings.UpdateCheckoutSettingsRequest.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(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseCheckoutSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/__init__.py deleted file mode 100644 index d5ee3fce97c1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_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 EmailPreferencesServiceClient -from .async_client import EmailPreferencesServiceAsyncClient - -__all__ = ( - 'EmailPreferencesServiceClient', - 'EmailPreferencesServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py deleted file mode 100644 index 89c8ffe57304..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/async_client.py +++ /dev/null @@ -1,511 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import emailpreferences -from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport -from .client import EmailPreferencesServiceClient - -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 EmailPreferencesServiceAsyncClient: - """Service to support the ``EmailPreferences`` API. - - This service only permits retrieving and updating email preferences - for the authenticated user. - """ - - _client: EmailPreferencesServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - - email_preferences_path = staticmethod(EmailPreferencesServiceClient.email_preferences_path) - parse_email_preferences_path = staticmethod(EmailPreferencesServiceClient.parse_email_preferences_path) - common_billing_account_path = staticmethod(EmailPreferencesServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EmailPreferencesServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EmailPreferencesServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(EmailPreferencesServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(EmailPreferencesServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(EmailPreferencesServiceClient.parse_common_organization_path) - common_project_path = staticmethod(EmailPreferencesServiceClient.common_project_path) - parse_common_project_path = staticmethod(EmailPreferencesServiceClient.parse_common_project_path) - common_location_path = staticmethod(EmailPreferencesServiceClient.common_location_path) - parse_common_location_path = staticmethod(EmailPreferencesServiceClient.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: - EmailPreferencesServiceAsyncClient: The constructed client. - """ - return EmailPreferencesServiceClient.from_service_account_info.__func__(EmailPreferencesServiceAsyncClient, 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: - EmailPreferencesServiceAsyncClient: The constructed client. - """ - return EmailPreferencesServiceClient.from_service_account_file.__func__(EmailPreferencesServiceAsyncClient, 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 EmailPreferencesServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EmailPreferencesServiceTransport: - """Returns the transport used by the client instance. - - Returns: - EmailPreferencesServiceTransport: 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 = EmailPreferencesServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the email preferences 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,EmailPreferencesServiceTransport,Callable[..., EmailPreferencesServiceTransport]]]): - 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 EmailPreferencesServiceTransport 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 = EmailPreferencesServiceClient( - 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.accounts_v1beta.EmailPreferencesServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "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.accounts.v1beta.EmailPreferencesService", - "credentialsType": None, - } - ) - - async def get_email_preferences(self, - request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: - r"""Returns the email preferences for a Merchant Center account - user. - - Use the name=accounts/*/users/me/emailPreferences alias to get - preferences for the authenticated user. - - .. 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_accounts_v1beta - - async def sample_get_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetEmailPreferencesRequest( - name="name_value", - ) - - # Make the request - response = await client.get_email_preferences(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest, dict]]): - The request object. Request message for - GetEmailPreferences method. - name (:class:`str`): - Required. The name of the ``EmailPreferences`` resource. - Format: - ``accounts/{account}/users/{email}/emailPreferences`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.EmailPreferences: - The categories of notifications the - user opted into / opted out of. The - email preferences do not include - mandatory announcements as users can't - opt out of them. - - """ - # 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, emailpreferences.GetEmailPreferencesRequest): - request = emailpreferences.GetEmailPreferencesRequest(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.get_email_preferences] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_email_preferences(self, - request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, - *, - email_preferences: Optional[emailpreferences.EmailPreferences] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: - r"""Updates the email preferences for a Merchant Center account - user. MCA users should specify the MCA account rather than a - sub-account of the MCA. - - Preferences which are not explicitly selected in the update mask - will not be updated. - - It is invalid for updates to specify an UNCONFIRMED opt-in - status value. - - Use the name=accounts/*/users/me/emailPreferences alias to - update preferences for the authenticated user. - - .. 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_accounts_v1beta - - async def sample_update_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( - ) - - # Make the request - response = await client.update_email_preferences(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest, dict]]): - The request object. Request message for - UpdateEmailPreferences method. - email_preferences (:class:`google.shopping.merchant_accounts_v1beta.types.EmailPreferences`): - Required. Email Preferences to be - updated. - - This corresponds to the ``email_preferences`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.EmailPreferences: - The categories of notifications the - user opted into / opted out of. The - email preferences do not include - mandatory announcements as users can't - opt out of them. - - """ - # 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 = [email_preferences, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, emailpreferences.UpdateEmailPreferencesRequest): - request = emailpreferences.UpdateEmailPreferencesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if email_preferences is not None: - request.email_preferences = email_preferences - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_email_preferences] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("email_preferences.name", request.email_preferences.name), - )), - ) - - # 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 __aenter__(self) -> "EmailPreferencesServiceAsyncClient": - 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__ = ( - "EmailPreferencesServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py deleted file mode 100644 index 7cb796ba2b36..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/client.py +++ /dev/null @@ -1,870 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import emailpreferences -from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EmailPreferencesServiceGrpcTransport -from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport -from .transports.rest import EmailPreferencesServiceRestTransport - - -class EmailPreferencesServiceClientMeta(type): - """Metaclass for the EmailPreferencesService 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[EmailPreferencesServiceTransport]] - _transport_registry["grpc"] = EmailPreferencesServiceGrpcTransport - _transport_registry["grpc_asyncio"] = EmailPreferencesServiceGrpcAsyncIOTransport - _transport_registry["rest"] = EmailPreferencesServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EmailPreferencesServiceTransport]: - """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 EmailPreferencesServiceClient(metaclass=EmailPreferencesServiceClientMeta): - """Service to support the ``EmailPreferences`` API. - - This service only permits retrieving and updating email preferences - for the authenticated user. - """ - - @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: - EmailPreferencesServiceClient: 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: - EmailPreferencesServiceClient: 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) -> EmailPreferencesServiceTransport: - """Returns the transport used by the client instance. - - Returns: - EmailPreferencesServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def email_preferences_path(account: str,email: str,) -> str: - """Returns a fully-qualified email_preferences string.""" - return "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) - - @staticmethod - def parse_email_preferences_path(path: str) -> Dict[str,str]: - """Parses a email_preferences path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/users/(?P.+?)/emailPreferences$", 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 = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient._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, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the email preferences 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,EmailPreferencesServiceTransport,Callable[..., EmailPreferencesServiceTransport]]]): - 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 EmailPreferencesServiceTransport 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 = EmailPreferencesServiceClient._read_environment_variables() - self._client_cert_source = EmailPreferencesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EmailPreferencesServiceClient._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, EmailPreferencesServiceTransport) - if transport_provided: - # transport is a EmailPreferencesServiceTransport 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(EmailPreferencesServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EmailPreferencesServiceClient._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[EmailPreferencesServiceTransport], Callable[..., EmailPreferencesServiceTransport]] = ( - EmailPreferencesServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EmailPreferencesServiceTransport], 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.accounts_v1beta.EmailPreferencesServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "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.accounts.v1beta.EmailPreferencesService", - "credentialsType": None, - } - ) - - def get_email_preferences(self, - request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: - r"""Returns the email preferences for a Merchant Center account - user. - - Use the name=accounts/*/users/me/emailPreferences alias to get - preferences for the authenticated user. - - .. 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_accounts_v1beta - - def sample_get_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetEmailPreferencesRequest( - name="name_value", - ) - - # Make the request - response = client.get_email_preferences(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest, dict]): - The request object. Request message for - GetEmailPreferences method. - name (str): - Required. The name of the ``EmailPreferences`` resource. - Format: - ``accounts/{account}/users/{email}/emailPreferences`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.EmailPreferences: - The categories of notifications the - user opted into / opted out of. The - email preferences do not include - mandatory announcements as users can't - opt out of them. - - """ - # 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, emailpreferences.GetEmailPreferencesRequest): - request = emailpreferences.GetEmailPreferencesRequest(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.get_email_preferences] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_email_preferences(self, - request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, - *, - email_preferences: Optional[emailpreferences.EmailPreferences] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: - r"""Updates the email preferences for a Merchant Center account - user. MCA users should specify the MCA account rather than a - sub-account of the MCA. - - Preferences which are not explicitly selected in the update mask - will not be updated. - - It is invalid for updates to specify an UNCONFIRMED opt-in - status value. - - Use the name=accounts/*/users/me/emailPreferences alias to - update preferences for the authenticated user. - - .. 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_accounts_v1beta - - def sample_update_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( - ) - - # Make the request - response = client.update_email_preferences(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest, dict]): - The request object. Request message for - UpdateEmailPreferences method. - email_preferences (google.shopping.merchant_accounts_v1beta.types.EmailPreferences): - Required. Email Preferences to be - updated. - - This corresponds to the ``email_preferences`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.EmailPreferences: - The categories of notifications the - user opted into / opted out of. The - email preferences do not include - mandatory announcements as users can't - opt out of them. - - """ - # 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 = [email_preferences, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, emailpreferences.UpdateEmailPreferencesRequest): - request = emailpreferences.UpdateEmailPreferencesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if email_preferences is not None: - request.email_preferences = email_preferences - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_email_preferences] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("email_preferences.name", request.email_preferences.name), - )), - ) - - # 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 __enter__(self) -> "EmailPreferencesServiceClient": - 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__ = ( - "EmailPreferencesServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst deleted file mode 100644 index 210db60dee0d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`EmailPreferencesServiceTransport` is the ABC for all transports. -- public child `EmailPreferencesServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `EmailPreferencesServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseEmailPreferencesServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `EmailPreferencesServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py deleted file mode 100644 index 97b309b8efa6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import emailpreferences - -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 EmailPreferencesServiceTransport(abc.ABC): - """Abstract transport class for EmailPreferencesService.""" - - 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.get_email_preferences: gapic_v1.method.wrap_method( - self.get_email_preferences, - default_timeout=None, - client_info=client_info, - ), - self.update_email_preferences: gapic_v1.method.wrap_method( - self.update_email_preferences, - 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 get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - Union[ - emailpreferences.EmailPreferences, - Awaitable[emailpreferences.EmailPreferences] - ]]: - raise NotImplementedError() - - @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - Union[ - emailpreferences.EmailPreferences, - Awaitable[emailpreferences.EmailPreferences] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EmailPreferencesServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py deleted file mode 100644 index fc2def7546ee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc.py +++ /dev/null @@ -1,390 +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.shopping.merchant_accounts_v1beta.types import emailpreferences -from .base import EmailPreferencesServiceTransport, 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.accounts.v1beta.EmailPreferencesService", - "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.accounts.v1beta.EmailPreferencesService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EmailPreferencesServiceGrpcTransport(EmailPreferencesServiceTransport): - """gRPC backend transport for EmailPreferencesService. - - Service to support the ``EmailPreferences`` API. - - This service only permits retrieving and updating email preferences - for the authenticated user. - - 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 get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - emailpreferences.EmailPreferences]: - r"""Return a callable for the get email preferences method over gRPC. - - Returns the email preferences for a Merchant Center account - user. - - Use the name=accounts/*/users/me/emailPreferences alias to get - preferences for the authenticated user. - - Returns: - Callable[[~.GetEmailPreferencesRequest], - ~.EmailPreferences]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_email_preferences' not in self._stubs: - self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/GetEmailPreferences', - request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, - response_deserializer=emailpreferences.EmailPreferences.deserialize, - ) - return self._stubs['get_email_preferences'] - - @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - emailpreferences.EmailPreferences]: - r"""Return a callable for the update email preferences method over gRPC. - - Updates the email preferences for a Merchant Center account - user. MCA users should specify the MCA account rather than a - sub-account of the MCA. - - Preferences which are not explicitly selected in the update mask - will not be updated. - - It is invalid for updates to specify an UNCONFIRMED opt-in - status value. - - Use the name=accounts/*/users/me/emailPreferences alias to - update preferences for the authenticated user. - - Returns: - Callable[[~.UpdateEmailPreferencesRequest], - ~.EmailPreferences]: - 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 'update_email_preferences' not in self._stubs: - self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/UpdateEmailPreferences', - request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, - response_deserializer=emailpreferences.EmailPreferences.deserialize, - ) - return self._stubs['update_email_preferences'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EmailPreferencesServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py deleted file mode 100644 index 40c3f11f0d17..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,416 +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.shopping.merchant_accounts_v1beta.types import emailpreferences -from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import EmailPreferencesServiceGrpcTransport - -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.accounts.v1beta.EmailPreferencesService", - "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.accounts.v1beta.EmailPreferencesService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class EmailPreferencesServiceGrpcAsyncIOTransport(EmailPreferencesServiceTransport): - """gRPC AsyncIO backend transport for EmailPreferencesService. - - Service to support the ``EmailPreferences`` API. - - This service only permits retrieving and updating email preferences - for the authenticated user. - - 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 get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - Awaitable[emailpreferences.EmailPreferences]]: - r"""Return a callable for the get email preferences method over gRPC. - - Returns the email preferences for a Merchant Center account - user. - - Use the name=accounts/*/users/me/emailPreferences alias to get - preferences for the authenticated user. - - Returns: - Callable[[~.GetEmailPreferencesRequest], - Awaitable[~.EmailPreferences]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_email_preferences' not in self._stubs: - self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/GetEmailPreferences', - request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, - response_deserializer=emailpreferences.EmailPreferences.deserialize, - ) - return self._stubs['get_email_preferences'] - - @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - Awaitable[emailpreferences.EmailPreferences]]: - r"""Return a callable for the update email preferences method over gRPC. - - Updates the email preferences for a Merchant Center account - user. MCA users should specify the MCA account rather than a - sub-account of the MCA. - - Preferences which are not explicitly selected in the update mask - will not be updated. - - It is invalid for updates to specify an UNCONFIRMED opt-in - status value. - - Use the name=accounts/*/users/me/emailPreferences alias to - update preferences for the authenticated user. - - Returns: - Callable[[~.UpdateEmailPreferencesRequest], - Awaitable[~.EmailPreferences]]: - 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 'update_email_preferences' not in self._stubs: - self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.EmailPreferencesService/UpdateEmailPreferences', - request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, - response_deserializer=emailpreferences.EmailPreferences.deserialize, - ) - return self._stubs['update_email_preferences'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_email_preferences: self._wrap_method( - self.get_email_preferences, - default_timeout=None, - client_info=client_info, - ), - self.update_email_preferences: self._wrap_method( - self.update_email_preferences, - 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__ = ( - 'EmailPreferencesServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py deleted file mode 100644 index 0a85982cd5a1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest.py +++ /dev/null @@ -1,540 +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.shopping.merchant_accounts_v1beta.types import emailpreferences - - -from .rest_base import _BaseEmailPreferencesServiceRestTransport -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 EmailPreferencesServiceRestInterceptor: - """Interceptor for EmailPreferencesService. - - 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 EmailPreferencesServiceRestTransport. - - .. code-block:: python - class MyCustomEmailPreferencesServiceInterceptor(EmailPreferencesServiceRestInterceptor): - def pre_get_email_preferences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_email_preferences(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_email_preferences(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_email_preferences(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EmailPreferencesServiceRestTransport(interceptor=MyCustomEmailPreferencesServiceInterceptor()) - client = EmailPreferencesServiceClient(transport=transport) - - - """ - def pre_get_email_preferences(self, request: emailpreferences.GetEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_email_preferences - - Override in a subclass to manipulate the request or metadata - before they are sent to the EmailPreferencesService server. - """ - return request, metadata - - def post_get_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: - """Post-rpc interceptor for get_email_preferences - - DEPRECATED. Please use the `post_get_email_preferences_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the EmailPreferencesService server but before - it is returned to user code. This `post_get_email_preferences` interceptor runs - before the `post_get_email_preferences_with_metadata` interceptor. - """ - return response - - def post_get_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_email_preferences - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the EmailPreferencesService server but before it is returned to user code. - - We recommend only using this `post_get_email_preferences_with_metadata` - interceptor in new development instead of the `post_get_email_preferences` interceptor. - When both interceptors are used, this `post_get_email_preferences_with_metadata` interceptor runs after the - `post_get_email_preferences` interceptor. The (possibly modified) response returned by - `post_get_email_preferences` will be passed to - `post_get_email_preferences_with_metadata`. - """ - return response, metadata - - def pre_update_email_preferences(self, request: emailpreferences.UpdateEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_email_preferences - - Override in a subclass to manipulate the request or metadata - before they are sent to the EmailPreferencesService server. - """ - return request, metadata - - def post_update_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: - """Post-rpc interceptor for update_email_preferences - - DEPRECATED. Please use the `post_update_email_preferences_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the EmailPreferencesService server but before - it is returned to user code. This `post_update_email_preferences` interceptor runs - before the `post_update_email_preferences_with_metadata` interceptor. - """ - return response - - def post_update_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_email_preferences - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the EmailPreferencesService server but before it is returned to user code. - - We recommend only using this `post_update_email_preferences_with_metadata` - interceptor in new development instead of the `post_update_email_preferences` interceptor. - When both interceptors are used, this `post_update_email_preferences_with_metadata` interceptor runs after the - `post_update_email_preferences` interceptor. The (possibly modified) response returned by - `post_update_email_preferences` will be passed to - `post_update_email_preferences_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class EmailPreferencesServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EmailPreferencesServiceRestInterceptor - - -class EmailPreferencesServiceRestTransport(_BaseEmailPreferencesServiceRestTransport): - """REST backend synchronous transport for EmailPreferencesService. - - Service to support the ``EmailPreferences`` API. - - This service only permits retrieving and updating email preferences - for the authenticated user. - - 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[EmailPreferencesServiceRestInterceptor] = 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 EmailPreferencesServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences, EmailPreferencesServiceRestStub): - def __hash__(self): - return hash("EmailPreferencesServiceRestTransport.GetEmailPreferences") - - @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: emailpreferences.GetEmailPreferencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> emailpreferences.EmailPreferences: - r"""Call the get email preferences method over HTTP. - - Args: - request (~.emailpreferences.GetEmailPreferencesRequest): - The request object. Request message for - GetEmailPreferences 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: - ~.emailpreferences.EmailPreferences: - The categories of notifications the - user opted into / opted out of. The - email preferences do not include - mandatory announcements as users can't - opt out of them. - - """ - - http_options = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_http_options() - - request, metadata = self._interceptor.pre_get_email_preferences(request, metadata) - transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.EmailPreferencesServiceClient.GetEmailPreferences", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "rpcName": "GetEmailPreferences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EmailPreferencesServiceRestTransport._GetEmailPreferences._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 = emailpreferences.EmailPreferences() - pb_resp = emailpreferences.EmailPreferences.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_email_preferences(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_email_preferences_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = emailpreferences.EmailPreferences.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.accounts_v1beta.EmailPreferencesServiceClient.get_email_preferences", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "rpcName": "GetEmailPreferences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences, EmailPreferencesServiceRestStub): - def __hash__(self): - return hash("EmailPreferencesServiceRestTransport.UpdateEmailPreferences") - - @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: emailpreferences.UpdateEmailPreferencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> emailpreferences.EmailPreferences: - r"""Call the update email preferences method over HTTP. - - Args: - request (~.emailpreferences.UpdateEmailPreferencesRequest): - The request object. Request message for - UpdateEmailPreferences 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: - ~.emailpreferences.EmailPreferences: - The categories of notifications the - user opted into / opted out of. The - email preferences do not include - mandatory announcements as users can't - opt out of them. - - """ - - http_options = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_http_options() - - request, metadata = self._interceptor.pre_update_email_preferences(request, metadata) - transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_transcoded_request(http_options, request) - - body = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.EmailPreferencesServiceClient.UpdateEmailPreferences", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "rpcName": "UpdateEmailPreferences", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = EmailPreferencesServiceRestTransport._UpdateEmailPreferences._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 = emailpreferences.EmailPreferences() - pb_resp = emailpreferences.EmailPreferences.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_email_preferences(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_email_preferences_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = emailpreferences.EmailPreferences.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.accounts_v1beta.EmailPreferencesServiceClient.update_email_preferences", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "rpcName": "UpdateEmailPreferences", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - emailpreferences.EmailPreferences]: - # 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._GetEmailPreferences(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - emailpreferences.EmailPreferences]: - # 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._UpdateEmailPreferences(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EmailPreferencesServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py deleted file mode 100644 index 659b72806a24..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import emailpreferences - - -class _BaseEmailPreferencesServiceRestTransport(EmailPreferencesServiceTransport): - """Base REST backend transport for EmailPreferencesService. - - 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 _BaseGetEmailPreferences: - 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': '/accounts/v1beta/{name=accounts/*/users/*/emailPreferences}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = emailpreferences.GetEmailPreferencesRequest.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(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateEmailPreferences: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{email_preferences.name=accounts/*/users/*/emailPreferences}', - 'body': 'email_preferences', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = emailpreferences.UpdateEmailPreferencesRequest.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(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseEmailPreferencesServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py deleted file mode 100644 index a2de8f492817..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/async_client.py +++ /dev/null @@ -1,502 +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_accounts_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.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import pagers -from google.shopping.merchant_accounts_v1beta.types import gbpaccounts -from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport -from .client import GbpAccountsServiceClient - -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 GbpAccountsServiceAsyncClient: - """The service facilitates the management of a merchant's Google - Business Profile (GBP) account settings. This API defines the - following resource model: - - - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] - """ - - _client: GbpAccountsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = GbpAccountsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = GbpAccountsServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(GbpAccountsServiceClient.account_path) - parse_account_path = staticmethod(GbpAccountsServiceClient.parse_account_path) - gbp_account_path = staticmethod(GbpAccountsServiceClient.gbp_account_path) - parse_gbp_account_path = staticmethod(GbpAccountsServiceClient.parse_gbp_account_path) - common_billing_account_path = staticmethod(GbpAccountsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(GbpAccountsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(GbpAccountsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(GbpAccountsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(GbpAccountsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(GbpAccountsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(GbpAccountsServiceClient.common_project_path) - parse_common_project_path = staticmethod(GbpAccountsServiceClient.parse_common_project_path) - common_location_path = staticmethod(GbpAccountsServiceClient.common_location_path) - parse_common_location_path = staticmethod(GbpAccountsServiceClient.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: - GbpAccountsServiceAsyncClient: The constructed client. - """ - return GbpAccountsServiceClient.from_service_account_info.__func__(GbpAccountsServiceAsyncClient, 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: - GbpAccountsServiceAsyncClient: The constructed client. - """ - return GbpAccountsServiceClient.from_service_account_file.__func__(GbpAccountsServiceAsyncClient, 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 GbpAccountsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> GbpAccountsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - GbpAccountsServiceTransport: 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 = GbpAccountsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the gbp accounts 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,GbpAccountsServiceTransport,Callable[..., GbpAccountsServiceTransport]]]): - 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 GbpAccountsServiceTransport 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 = GbpAccountsServiceClient( - 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.accounts_v1beta.GbpAccountsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "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.accounts.v1beta.GbpAccountsService", - "credentialsType": None, - } - ) - - async def list_gbp_accounts(self, - request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsAsyncPager: - r"""List the GBP accounts for a given merchant. - - .. 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_accounts_v1beta - - async def sample_list_gbp_accounts(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListGbpAccountsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gbp_accounts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest, dict]]): - The request object. Request message for the - ListGbpAccounts method. - parent (:class:`str`): - Required. The name of the parent resource under which - the GBP accounts are listed. Format: - ``accounts/{account}``. - - 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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsAsyncPager: - Response message for the - ListGbpAccounts 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, gbpaccounts.ListGbpAccountsRequest): - request = gbpaccounts.ListGbpAccountsRequest(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_gbp_accounts] - - # 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.ListGbpAccountsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def link_gbp_account(self, - request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), - ) -> gbpaccounts.LinkGbpAccountResponse: - r"""Link the specified merchant to a GBP account for all - countries. - - .. 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_accounts_v1beta - - async def sample_link_gbp_account(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkGbpAccountRequest( - parent="parent_value", - gbp_email="gbp_email_value", - ) - - # Make the request - response = await client.link_gbp_account(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest, dict]]): - The request object. Request message for the - LinkGbpAccount method. - parent (:class:`str`): - Required. The name of the parent resource to which the - GBP account is linked. Format: ``accounts/{account}``. - - 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_accounts_v1beta.types.LinkGbpAccountResponse: - Response message for the - LinkGbpAccount method. - - """ - # 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, gbpaccounts.LinkGbpAccountRequest): - request = gbpaccounts.LinkGbpAccountRequest(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.link_gbp_account] - - # 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 __aenter__(self) -> "GbpAccountsServiceAsyncClient": - 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__ = ( - "GbpAccountsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py deleted file mode 100644 index 784e95feb0ea..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/client.py +++ /dev/null @@ -1,870 +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_accounts_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.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import pagers -from google.shopping.merchant_accounts_v1beta.types import gbpaccounts -from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import GbpAccountsServiceGrpcTransport -from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport -from .transports.rest import GbpAccountsServiceRestTransport - - -class GbpAccountsServiceClientMeta(type): - """Metaclass for the GbpAccountsService 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[GbpAccountsServiceTransport]] - _transport_registry["grpc"] = GbpAccountsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = GbpAccountsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = GbpAccountsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[GbpAccountsServiceTransport]: - """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 GbpAccountsServiceClient(metaclass=GbpAccountsServiceClientMeta): - """The service facilitates the management of a merchant's Google - Business Profile (GBP) account settings. This API defines the - following resource model: - - - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] - """ - - @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: - GbpAccountsServiceClient: 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: - GbpAccountsServiceClient: 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) -> GbpAccountsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - GbpAccountsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def gbp_account_path(account: str,gbp_account: str,) -> str: - """Returns a fully-qualified gbp_account string.""" - return "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) - - @staticmethod - def parse_gbp_account_path(path: str) -> Dict[str,str]: - """Parses a gbp_account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/gbpAccounts/(?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 = GbpAccountsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = GbpAccountsServiceClient._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 = GbpAccountsServiceClient._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, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the gbp accounts 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,GbpAccountsServiceTransport,Callable[..., GbpAccountsServiceTransport]]]): - 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 GbpAccountsServiceTransport 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 = GbpAccountsServiceClient._read_environment_variables() - self._client_cert_source = GbpAccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = GbpAccountsServiceClient._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, GbpAccountsServiceTransport) - if transport_provided: - # transport is a GbpAccountsServiceTransport 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(GbpAccountsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - GbpAccountsServiceClient._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[GbpAccountsServiceTransport], Callable[..., GbpAccountsServiceTransport]] = ( - GbpAccountsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., GbpAccountsServiceTransport], 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.accounts_v1beta.GbpAccountsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "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.accounts.v1beta.GbpAccountsService", - "credentialsType": None, - } - ) - - def list_gbp_accounts(self, - request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsPager: - r"""List the GBP accounts for a given merchant. - - .. 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_accounts_v1beta - - def sample_list_gbp_accounts(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListGbpAccountsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gbp_accounts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest, dict]): - The request object. Request message for the - ListGbpAccounts method. - parent (str): - Required. The name of the parent resource under which - the GBP accounts are listed. Format: - ``accounts/{account}``. - - 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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsPager: - Response message for the - ListGbpAccounts 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, gbpaccounts.ListGbpAccountsRequest): - request = gbpaccounts.ListGbpAccountsRequest(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_gbp_accounts] - - # 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.ListGbpAccountsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def link_gbp_account(self, - request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), - ) -> gbpaccounts.LinkGbpAccountResponse: - r"""Link the specified merchant to a GBP account for all - countries. - - .. 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_accounts_v1beta - - def sample_link_gbp_account(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkGbpAccountRequest( - parent="parent_value", - gbp_email="gbp_email_value", - ) - - # Make the request - response = client.link_gbp_account(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest, dict]): - The request object. Request message for the - LinkGbpAccount method. - parent (str): - Required. The name of the parent resource to which the - GBP account is linked. Format: ``accounts/{account}``. - - 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_accounts_v1beta.types.LinkGbpAccountResponse: - Response message for the - LinkGbpAccount method. - - """ - # 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, gbpaccounts.LinkGbpAccountRequest): - request = gbpaccounts.LinkGbpAccountRequest(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.link_gbp_account] - - # 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 __enter__(self) -> "GbpAccountsServiceClient": - 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__ = ( - "GbpAccountsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/pagers.py deleted file mode 100644 index 60cac6505c7b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_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_accounts_v1beta.types import gbpaccounts - - -class ListGbpAccountsPager: - """A pager for iterating through ``list_gbp_accounts`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``gbp_accounts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListGbpAccounts`` requests and continue to iterate - through the ``gbp_accounts`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` - 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[..., gbpaccounts.ListGbpAccountsResponse], - request: gbpaccounts.ListGbpAccountsRequest, - response: gbpaccounts.ListGbpAccountsResponse, - *, - 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_accounts_v1beta.types.ListGbpAccountsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse): - 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 = gbpaccounts.ListGbpAccountsRequest(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[gbpaccounts.ListGbpAccountsResponse]: - 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[gbpaccounts.GbpAccount]: - for page in self.pages: - yield from page.gbp_accounts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListGbpAccountsAsyncPager: - """A pager for iterating through ``list_gbp_accounts`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``gbp_accounts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListGbpAccounts`` requests and continue to iterate - through the ``gbp_accounts`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse` - 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[gbpaccounts.ListGbpAccountsResponse]], - request: gbpaccounts.ListGbpAccountsRequest, - response: gbpaccounts.ListGbpAccountsResponse, - *, - 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_accounts_v1beta.types.ListGbpAccountsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsResponse): - 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 = gbpaccounts.ListGbpAccountsRequest(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[gbpaccounts.ListGbpAccountsResponse]: - 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[gbpaccounts.GbpAccount]: - async def async_generator(): - async for page in self.pages: - for response in page.gbp_accounts: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst deleted file mode 100644 index a6f7710d74a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`GbpAccountsServiceTransport` is the ABC for all transports. -- public child `GbpAccountsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `GbpAccountsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseGbpAccountsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `GbpAccountsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py deleted file mode 100644 index cfe39135bc52..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import gbpaccounts - -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 GbpAccountsServiceTransport(abc.ABC): - """Abstract transport class for GbpAccountsService.""" - - 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_gbp_accounts: gapic_v1.method.wrap_method( - self.list_gbp_accounts, - default_timeout=None, - client_info=client_info, - ), - self.link_gbp_account: gapic_v1.method.wrap_method( - self.link_gbp_account, - 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_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - Union[ - gbpaccounts.ListGbpAccountsResponse, - Awaitable[gbpaccounts.ListGbpAccountsResponse] - ]]: - raise NotImplementedError() - - @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - Union[ - gbpaccounts.LinkGbpAccountResponse, - Awaitable[gbpaccounts.LinkGbpAccountResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'GbpAccountsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py deleted file mode 100644 index 5c856f73d726..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc.py +++ /dev/null @@ -1,377 +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.shopping.merchant_accounts_v1beta.types import gbpaccounts -from .base import GbpAccountsServiceTransport, 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.accounts.v1beta.GbpAccountsService", - "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.accounts.v1beta.GbpAccountsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class GbpAccountsServiceGrpcTransport(GbpAccountsServiceTransport): - """gRPC backend transport for GbpAccountsService. - - The service facilitates the management of a merchant's Google - Business Profile (GBP) account settings. This API defines the - following resource model: - - - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] - - 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_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - gbpaccounts.ListGbpAccountsResponse]: - r"""Return a callable for the list gbp accounts method over gRPC. - - List the GBP accounts for a given merchant. - - Returns: - Callable[[~.ListGbpAccountsRequest], - ~.ListGbpAccountsResponse]: - 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_gbp_accounts' not in self._stubs: - self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/ListGbpAccounts', - request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, - response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, - ) - return self._stubs['list_gbp_accounts'] - - @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - gbpaccounts.LinkGbpAccountResponse]: - r"""Return a callable for the link gbp account method over gRPC. - - Link the specified merchant to a GBP account for all - countries. - - Returns: - Callable[[~.LinkGbpAccountRequest], - ~.LinkGbpAccountResponse]: - 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 'link_gbp_account' not in self._stubs: - self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/LinkGbpAccount', - request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, - response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, - ) - return self._stubs['link_gbp_account'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'GbpAccountsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py deleted file mode 100644 index 62bbcfae57d4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,403 +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.shopping.merchant_accounts_v1beta.types import gbpaccounts -from .base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import GbpAccountsServiceGrpcTransport - -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.accounts.v1beta.GbpAccountsService", - "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.accounts.v1beta.GbpAccountsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class GbpAccountsServiceGrpcAsyncIOTransport(GbpAccountsServiceTransport): - """gRPC AsyncIO backend transport for GbpAccountsService. - - The service facilitates the management of a merchant's Google - Business Profile (GBP) account settings. This API defines the - following resource model: - - - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] - - 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_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - Awaitable[gbpaccounts.ListGbpAccountsResponse]]: - r"""Return a callable for the list gbp accounts method over gRPC. - - List the GBP accounts for a given merchant. - - Returns: - Callable[[~.ListGbpAccountsRequest], - Awaitable[~.ListGbpAccountsResponse]]: - 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_gbp_accounts' not in self._stubs: - self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/ListGbpAccounts', - request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, - response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, - ) - return self._stubs['list_gbp_accounts'] - - @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - Awaitable[gbpaccounts.LinkGbpAccountResponse]]: - r"""Return a callable for the link gbp account method over gRPC. - - Link the specified merchant to a GBP account for all - countries. - - Returns: - Callable[[~.LinkGbpAccountRequest], - Awaitable[~.LinkGbpAccountResponse]]: - 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 'link_gbp_account' not in self._stubs: - self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.GbpAccountsService/LinkGbpAccount', - request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, - response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, - ) - return self._stubs['link_gbp_account'] - - 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_gbp_accounts: self._wrap_method( - self.list_gbp_accounts, - default_timeout=None, - client_info=client_info, - ), - self.link_gbp_account: self._wrap_method( - self.link_gbp_account, - 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__ = ( - 'GbpAccountsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py deleted file mode 100644 index 3ea28bfe2c6b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest.py +++ /dev/null @@ -1,535 +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.shopping.merchant_accounts_v1beta.types import gbpaccounts - - -from .rest_base import _BaseGbpAccountsServiceRestTransport -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 GbpAccountsServiceRestInterceptor: - """Interceptor for GbpAccountsService. - - 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 GbpAccountsServiceRestTransport. - - .. code-block:: python - class MyCustomGbpAccountsServiceInterceptor(GbpAccountsServiceRestInterceptor): - def pre_link_gbp_account(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_link_gbp_account(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_gbp_accounts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_gbp_accounts(self, response): - logging.log(f"Received response: {response}") - return response - - transport = GbpAccountsServiceRestTransport(interceptor=MyCustomGbpAccountsServiceInterceptor()) - client = GbpAccountsServiceClient(transport=transport) - - - """ - def pre_link_gbp_account(self, request: gbpaccounts.LinkGbpAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for link_gbp_account - - Override in a subclass to manipulate the request or metadata - before they are sent to the GbpAccountsService server. - """ - return request, metadata - - def post_link_gbp_account(self, response: gbpaccounts.LinkGbpAccountResponse) -> gbpaccounts.LinkGbpAccountResponse: - """Post-rpc interceptor for link_gbp_account - - DEPRECATED. Please use the `post_link_gbp_account_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the GbpAccountsService server but before - it is returned to user code. This `post_link_gbp_account` interceptor runs - before the `post_link_gbp_account_with_metadata` interceptor. - """ - return response - - def post_link_gbp_account_with_metadata(self, response: gbpaccounts.LinkGbpAccountResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for link_gbp_account - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the GbpAccountsService server but before it is returned to user code. - - We recommend only using this `post_link_gbp_account_with_metadata` - interceptor in new development instead of the `post_link_gbp_account` interceptor. - When both interceptors are used, this `post_link_gbp_account_with_metadata` interceptor runs after the - `post_link_gbp_account` interceptor. The (possibly modified) response returned by - `post_link_gbp_account` will be passed to - `post_link_gbp_account_with_metadata`. - """ - return response, metadata - - def pre_list_gbp_accounts(self, request: gbpaccounts.ListGbpAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_gbp_accounts - - Override in a subclass to manipulate the request or metadata - before they are sent to the GbpAccountsService server. - """ - return request, metadata - - def post_list_gbp_accounts(self, response: gbpaccounts.ListGbpAccountsResponse) -> gbpaccounts.ListGbpAccountsResponse: - """Post-rpc interceptor for list_gbp_accounts - - DEPRECATED. Please use the `post_list_gbp_accounts_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the GbpAccountsService server but before - it is returned to user code. This `post_list_gbp_accounts` interceptor runs - before the `post_list_gbp_accounts_with_metadata` interceptor. - """ - return response - - def post_list_gbp_accounts_with_metadata(self, response: gbpaccounts.ListGbpAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_gbp_accounts - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the GbpAccountsService server but before it is returned to user code. - - We recommend only using this `post_list_gbp_accounts_with_metadata` - interceptor in new development instead of the `post_list_gbp_accounts` interceptor. - When both interceptors are used, this `post_list_gbp_accounts_with_metadata` interceptor runs after the - `post_list_gbp_accounts` interceptor. The (possibly modified) response returned by - `post_list_gbp_accounts` will be passed to - `post_list_gbp_accounts_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class GbpAccountsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: GbpAccountsServiceRestInterceptor - - -class GbpAccountsServiceRestTransport(_BaseGbpAccountsServiceRestTransport): - """REST backend synchronous transport for GbpAccountsService. - - The service facilitates the management of a merchant's Google - Business Profile (GBP) account settings. This API defines the - following resource model: - - - [GbpAccount][google.shopping.merchant.accounts.v1.GbpAccount] - - 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[GbpAccountsServiceRestInterceptor] = 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 GbpAccountsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _LinkGbpAccount(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount, GbpAccountsServiceRestStub): - def __hash__(self): - return hash("GbpAccountsServiceRestTransport.LinkGbpAccount") - - @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: gbpaccounts.LinkGbpAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gbpaccounts.LinkGbpAccountResponse: - r"""Call the link gbp account method over HTTP. - - Args: - request (~.gbpaccounts.LinkGbpAccountRequest): - The request object. Request message for the - LinkGbpAccount 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: - ~.gbpaccounts.LinkGbpAccountResponse: - Response message for the - LinkGbpAccount method. - - """ - - http_options = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_http_options() - - request, metadata = self._interceptor.pre_link_gbp_account(request, metadata) - transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_transcoded_request(http_options, request) - - body = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.GbpAccountsServiceClient.LinkGbpAccount", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "rpcName": "LinkGbpAccount", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GbpAccountsServiceRestTransport._LinkGbpAccount._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 = gbpaccounts.LinkGbpAccountResponse() - pb_resp = gbpaccounts.LinkGbpAccountResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_link_gbp_account(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_link_gbp_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gbpaccounts.LinkGbpAccountResponse.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.accounts_v1beta.GbpAccountsServiceClient.link_gbp_account", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "rpcName": "LinkGbpAccount", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListGbpAccounts(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts, GbpAccountsServiceRestStub): - def __hash__(self): - return hash("GbpAccountsServiceRestTransport.ListGbpAccounts") - - @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: gbpaccounts.ListGbpAccountsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gbpaccounts.ListGbpAccountsResponse: - r"""Call the list gbp accounts method over HTTP. - - Args: - request (~.gbpaccounts.ListGbpAccountsRequest): - The request object. Request message for the - ListGbpAccounts 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: - ~.gbpaccounts.ListGbpAccountsResponse: - Response message for the - ListGbpAccounts method. - - """ - - http_options = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_http_options() - - request, metadata = self._interceptor.pre_list_gbp_accounts(request, metadata) - transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.GbpAccountsServiceClient.ListGbpAccounts", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "rpcName": "ListGbpAccounts", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = GbpAccountsServiceRestTransport._ListGbpAccounts._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 = gbpaccounts.ListGbpAccountsResponse() - pb_resp = gbpaccounts.ListGbpAccountsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_gbp_accounts(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_gbp_accounts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gbpaccounts.ListGbpAccountsResponse.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.accounts_v1beta.GbpAccountsServiceClient.list_gbp_accounts", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "rpcName": "ListGbpAccounts", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - gbpaccounts.LinkGbpAccountResponse]: - # 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._LinkGbpAccount(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - gbpaccounts.ListGbpAccountsResponse]: - # 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._ListGbpAccounts(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'GbpAccountsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py deleted file mode 100644 index 4a9cd1330bde..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import gbpaccounts - - -class _BaseGbpAccountsServiceRestTransport(GbpAccountsServiceTransport): - """Base REST backend transport for GbpAccountsService. - - 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 _BaseLinkGbpAccount: - 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': '/accounts/v1beta/{parent=accounts/*}/gbpAccounts:linkGbpAccount', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gbpaccounts.LinkGbpAccountRequest.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(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListGbpAccounts: - 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': '/accounts/v1beta/{parent=accounts/*}/gbpAccounts', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gbpaccounts.ListGbpAccountsRequest.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(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseGbpAccountsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/__init__.py deleted file mode 100644 index 96d41fc82ad2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_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 HomepageServiceClient -from .async_client import HomepageServiceAsyncClient - -__all__ = ( - 'HomepageServiceClient', - 'HomepageServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py deleted file mode 100644 index 248ff620d044..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/async_client.py +++ /dev/null @@ -1,658 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage -from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport -from .client import HomepageServiceClient - -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 HomepageServiceAsyncClient: - """Service to support an API for a store's homepage.""" - - _client: HomepageServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = HomepageServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = HomepageServiceClient._DEFAULT_UNIVERSE - - homepage_path = staticmethod(HomepageServiceClient.homepage_path) - parse_homepage_path = staticmethod(HomepageServiceClient.parse_homepage_path) - common_billing_account_path = staticmethod(HomepageServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(HomepageServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(HomepageServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(HomepageServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(HomepageServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(HomepageServiceClient.parse_common_organization_path) - common_project_path = staticmethod(HomepageServiceClient.common_project_path) - parse_common_project_path = staticmethod(HomepageServiceClient.parse_common_project_path) - common_location_path = staticmethod(HomepageServiceClient.common_location_path) - parse_common_location_path = staticmethod(HomepageServiceClient.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: - HomepageServiceAsyncClient: The constructed client. - """ - return HomepageServiceClient.from_service_account_info.__func__(HomepageServiceAsyncClient, 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: - HomepageServiceAsyncClient: The constructed client. - """ - return HomepageServiceClient.from_service_account_file.__func__(HomepageServiceAsyncClient, 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 HomepageServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> HomepageServiceTransport: - """Returns the transport used by the client instance. - - Returns: - HomepageServiceTransport: 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 = HomepageServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the homepage 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,HomepageServiceTransport,Callable[..., HomepageServiceTransport]]]): - 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 HomepageServiceTransport 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 = HomepageServiceClient( - 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.accounts_v1beta.HomepageServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "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.accounts.v1beta.HomepageService", - "credentialsType": None, - } - ) - - async def get_homepage(self, - request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: - r"""Retrieves a store's homepage. - - .. 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_accounts_v1beta - - async def sample_get_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetHomepageRequest( - name="name_value", - ) - - # Make the request - response = await client.get_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest, dict]]): - The request object. Request message for the ``GetHomepage`` method. - name (:class:`str`): - Required. The name of the homepage to retrieve. Format: - ``accounts/{account}/homepage`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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, homepage.GetHomepageRequest): - request = homepage.GetHomepageRequest(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.get_homepage] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_homepage(self, - request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, - *, - homepage: Optional[gsma_homepage.Homepage] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_homepage.Homepage: - r"""Updates a store's homepage. Executing this method - requires admin access. - - .. 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_accounts_v1beta - - async def sample_update_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateHomepageRequest( - ) - - # Make the request - response = await client.update_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest, dict]]): - The request object. Request message for the ``UpdateHomepage`` method. - homepage (:class:`google.shopping.merchant_accounts_v1beta.types.Homepage`): - Required. The new version of the - homepage. - - This corresponds to the ``homepage`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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 = [homepage, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_homepage.UpdateHomepageRequest): - request = gsma_homepage.UpdateHomepageRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if homepage is not None: - request.homepage = homepage - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_homepage] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("homepage.name", request.homepage.name), - )), - ) - - # 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 claim_homepage(self, - request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: - r"""Claims a store's homepage. Executing this method requires admin - access. - - If the homepage is already claimed, this will recheck the - verification (unless the merchant is exempted from claiming, - which also exempts from verification) and return a successful - response. If ownership can no longer be verified, it will return - an error, but it won't clear the claim. In case of failure, a - canonical error message will be returned: \* PERMISSION_DENIED: - user doesn't have the necessary permissions on this MC account; - \* FAILED_PRECONDITION: - The account is not a Merchant Center - account; - MC account doesn't have a homepage; - claiming failed - (in this case the error message will contain more details). - - .. 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_accounts_v1beta - - async def sample_claim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ClaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = await client.claim_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest, dict]]): - The request object. Request message for the ``ClaimHomepage`` 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_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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, homepage.ClaimHomepageRequest): - request = homepage.ClaimHomepageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.claim_homepage] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def unclaim_homepage(self, - request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: - r"""Unclaims a store's homepage. Executing this method - requires admin access. - - .. 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_accounts_v1beta - - async def sample_unclaim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UnclaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = await client.unclaim_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest, dict]]): - The request object. Request message for the ``UnclaimHomepage`` 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_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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, homepage.UnclaimHomepageRequest): - request = homepage.UnclaimHomepageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.unclaim_homepage] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "HomepageServiceAsyncClient": - 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__ = ( - "HomepageServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py deleted file mode 100644 index 17c17564ada4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/client.py +++ /dev/null @@ -1,1017 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage -from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import HomepageServiceGrpcTransport -from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport -from .transports.rest import HomepageServiceRestTransport - - -class HomepageServiceClientMeta(type): - """Metaclass for the HomepageService 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[HomepageServiceTransport]] - _transport_registry["grpc"] = HomepageServiceGrpcTransport - _transport_registry["grpc_asyncio"] = HomepageServiceGrpcAsyncIOTransport - _transport_registry["rest"] = HomepageServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[HomepageServiceTransport]: - """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 HomepageServiceClient(metaclass=HomepageServiceClientMeta): - """Service to support an API for a store's homepage.""" - - @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: - HomepageServiceClient: 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: - HomepageServiceClient: 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) -> HomepageServiceTransport: - """Returns the transport used by the client instance. - - Returns: - HomepageServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def homepage_path(account: str,) -> str: - """Returns a fully-qualified homepage string.""" - return "accounts/{account}/homepage".format(account=account, ) - - @staticmethod - def parse_homepage_path(path: str) -> Dict[str,str]: - """Parses a homepage path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/homepage$", 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 = HomepageServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = HomepageServiceClient._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 = HomepageServiceClient._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, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the homepage 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,HomepageServiceTransport,Callable[..., HomepageServiceTransport]]]): - 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 HomepageServiceTransport 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 = HomepageServiceClient._read_environment_variables() - self._client_cert_source = HomepageServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = HomepageServiceClient._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, HomepageServiceTransport) - if transport_provided: - # transport is a HomepageServiceTransport 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(HomepageServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - HomepageServiceClient._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[HomepageServiceTransport], Callable[..., HomepageServiceTransport]] = ( - HomepageServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., HomepageServiceTransport], 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.accounts_v1beta.HomepageServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "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.accounts.v1beta.HomepageService", - "credentialsType": None, - } - ) - - def get_homepage(self, - request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: - r"""Retrieves a store's homepage. - - .. 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_accounts_v1beta - - def sample_get_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetHomepageRequest( - name="name_value", - ) - - # Make the request - response = client.get_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest, dict]): - The request object. Request message for the ``GetHomepage`` method. - name (str): - Required. The name of the homepage to retrieve. Format: - ``accounts/{account}/homepage`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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, homepage.GetHomepageRequest): - request = homepage.GetHomepageRequest(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.get_homepage] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_homepage(self, - request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, - *, - homepage: Optional[gsma_homepage.Homepage] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_homepage.Homepage: - r"""Updates a store's homepage. Executing this method - requires admin access. - - .. 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_accounts_v1beta - - def sample_update_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateHomepageRequest( - ) - - # Make the request - response = client.update_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest, dict]): - The request object. Request message for the ``UpdateHomepage`` method. - homepage (google.shopping.merchant_accounts_v1beta.types.Homepage): - Required. The new version of the - homepage. - - This corresponds to the ``homepage`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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 = [homepage, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_homepage.UpdateHomepageRequest): - request = gsma_homepage.UpdateHomepageRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if homepage is not None: - request.homepage = homepage - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_homepage] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("homepage.name", request.homepage.name), - )), - ) - - # 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 claim_homepage(self, - request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: - r"""Claims a store's homepage. Executing this method requires admin - access. - - If the homepage is already claimed, this will recheck the - verification (unless the merchant is exempted from claiming, - which also exempts from verification) and return a successful - response. If ownership can no longer be verified, it will return - an error, but it won't clear the claim. In case of failure, a - canonical error message will be returned: \* PERMISSION_DENIED: - user doesn't have the necessary permissions on this MC account; - \* FAILED_PRECONDITION: - The account is not a Merchant Center - account; - MC account doesn't have a homepage; - claiming failed - (in this case the error message will contain more details). - - .. 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_accounts_v1beta - - def sample_claim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ClaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = client.claim_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest, dict]): - The request object. Request message for the ``ClaimHomepage`` 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_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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, homepage.ClaimHomepageRequest): - request = homepage.ClaimHomepageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.claim_homepage] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def unclaim_homepage(self, - request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: - r"""Unclaims a store's homepage. Executing this method - requires admin access. - - .. 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_accounts_v1beta - - def sample_unclaim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UnclaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = client.unclaim_homepage(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest, dict]): - The request object. Request message for the ``UnclaimHomepage`` 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_accounts_v1beta.types.Homepage: - A store's homepage. - """ - # 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, homepage.UnclaimHomepageRequest): - request = homepage.UnclaimHomepageRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.unclaim_homepage] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "HomepageServiceClient": - 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__ = ( - "HomepageServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst deleted file mode 100644 index 8c0def729b79..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`HomepageServiceTransport` is the ABC for all transports. -- public child `HomepageServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `HomepageServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseHomepageServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `HomepageServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/__init__.py deleted file mode 100644 index e935fb45c364..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_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 HomepageServiceTransport -from .grpc import HomepageServiceGrpcTransport -from .grpc_asyncio import HomepageServiceGrpcAsyncIOTransport -from .rest import HomepageServiceRestTransport -from .rest import HomepageServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[HomepageServiceTransport]] -_transport_registry['grpc'] = HomepageServiceGrpcTransport -_transport_registry['grpc_asyncio'] = HomepageServiceGrpcAsyncIOTransport -_transport_registry['rest'] = HomepageServiceRestTransport - -__all__ = ( - 'HomepageServiceTransport', - 'HomepageServiceGrpcTransport', - 'HomepageServiceGrpcAsyncIOTransport', - 'HomepageServiceRestTransport', - 'HomepageServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py deleted file mode 100644 index 974ef00c8ba6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/base.py +++ /dev/null @@ -1,202 +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_accounts_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.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage - -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 HomepageServiceTransport(abc.ABC): - """Abstract transport class for HomepageService.""" - - 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.get_homepage: gapic_v1.method.wrap_method( - self.get_homepage, - default_timeout=None, - client_info=client_info, - ), - self.update_homepage: gapic_v1.method.wrap_method( - self.update_homepage, - default_timeout=None, - client_info=client_info, - ), - self.claim_homepage: gapic_v1.method.wrap_method( - self.claim_homepage, - default_timeout=None, - client_info=client_info, - ), - self.unclaim_homepage: gapic_v1.method.wrap_method( - self.unclaim_homepage, - 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 get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - Union[ - homepage.Homepage, - Awaitable[homepage.Homepage] - ]]: - raise NotImplementedError() - - @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - Union[ - gsma_homepage.Homepage, - Awaitable[gsma_homepage.Homepage] - ]]: - raise NotImplementedError() - - @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - Union[ - homepage.Homepage, - Awaitable[homepage.Homepage] - ]]: - raise NotImplementedError() - - @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - Union[ - homepage.Homepage, - Awaitable[homepage.Homepage] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'HomepageServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py deleted file mode 100644 index 22d2ae117431..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc.py +++ /dev/null @@ -1,439 +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.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage -from .base import HomepageServiceTransport, 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.accounts.v1beta.HomepageService", - "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.accounts.v1beta.HomepageService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class HomepageServiceGrpcTransport(HomepageServiceTransport): - """gRPC backend transport for HomepageService. - - Service to support an API for a store's homepage. - - 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 get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - homepage.Homepage]: - r"""Return a callable for the get homepage method over gRPC. - - Retrieves a store's homepage. - - Returns: - Callable[[~.GetHomepageRequest], - ~.Homepage]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_homepage' not in self._stubs: - self._stubs['get_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/GetHomepage', - request_serializer=homepage.GetHomepageRequest.serialize, - response_deserializer=homepage.Homepage.deserialize, - ) - return self._stubs['get_homepage'] - - @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - gsma_homepage.Homepage]: - r"""Return a callable for the update homepage method over gRPC. - - Updates a store's homepage. Executing this method - requires admin access. - - Returns: - Callable[[~.UpdateHomepageRequest], - ~.Homepage]: - 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 'update_homepage' not in self._stubs: - self._stubs['update_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/UpdateHomepage', - request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, - response_deserializer=gsma_homepage.Homepage.deserialize, - ) - return self._stubs['update_homepage'] - - @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - homepage.Homepage]: - r"""Return a callable for the claim homepage method over gRPC. - - Claims a store's homepage. Executing this method requires admin - access. - - If the homepage is already claimed, this will recheck the - verification (unless the merchant is exempted from claiming, - which also exempts from verification) and return a successful - response. If ownership can no longer be verified, it will return - an error, but it won't clear the claim. In case of failure, a - canonical error message will be returned: \* PERMISSION_DENIED: - user doesn't have the necessary permissions on this MC account; - \* FAILED_PRECONDITION: - The account is not a Merchant Center - account; - MC account doesn't have a homepage; - claiming failed - (in this case the error message will contain more details). - - Returns: - Callable[[~.ClaimHomepageRequest], - ~.Homepage]: - 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 'claim_homepage' not in self._stubs: - self._stubs['claim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/ClaimHomepage', - request_serializer=homepage.ClaimHomepageRequest.serialize, - response_deserializer=homepage.Homepage.deserialize, - ) - return self._stubs['claim_homepage'] - - @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - homepage.Homepage]: - r"""Return a callable for the unclaim homepage method over gRPC. - - Unclaims a store's homepage. Executing this method - requires admin access. - - Returns: - Callable[[~.UnclaimHomepageRequest], - ~.Homepage]: - 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 'unclaim_homepage' not in self._stubs: - self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/UnclaimHomepage', - request_serializer=homepage.UnclaimHomepageRequest.serialize, - response_deserializer=homepage.Homepage.deserialize, - ) - return self._stubs['unclaim_homepage'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'HomepageServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py deleted file mode 100644 index d942602731e8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,475 +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.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage -from .base import HomepageServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import HomepageServiceGrpcTransport - -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.accounts.v1beta.HomepageService", - "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.accounts.v1beta.HomepageService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class HomepageServiceGrpcAsyncIOTransport(HomepageServiceTransport): - """gRPC AsyncIO backend transport for HomepageService. - - Service to support an API for a store's homepage. - - 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 get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - Awaitable[homepage.Homepage]]: - r"""Return a callable for the get homepage method over gRPC. - - Retrieves a store's homepage. - - Returns: - Callable[[~.GetHomepageRequest], - Awaitable[~.Homepage]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_homepage' not in self._stubs: - self._stubs['get_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/GetHomepage', - request_serializer=homepage.GetHomepageRequest.serialize, - response_deserializer=homepage.Homepage.deserialize, - ) - return self._stubs['get_homepage'] - - @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - Awaitable[gsma_homepage.Homepage]]: - r"""Return a callable for the update homepage method over gRPC. - - Updates a store's homepage. Executing this method - requires admin access. - - Returns: - Callable[[~.UpdateHomepageRequest], - Awaitable[~.Homepage]]: - 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 'update_homepage' not in self._stubs: - self._stubs['update_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/UpdateHomepage', - request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, - response_deserializer=gsma_homepage.Homepage.deserialize, - ) - return self._stubs['update_homepage'] - - @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - Awaitable[homepage.Homepage]]: - r"""Return a callable for the claim homepage method over gRPC. - - Claims a store's homepage. Executing this method requires admin - access. - - If the homepage is already claimed, this will recheck the - verification (unless the merchant is exempted from claiming, - which also exempts from verification) and return a successful - response. If ownership can no longer be verified, it will return - an error, but it won't clear the claim. In case of failure, a - canonical error message will be returned: \* PERMISSION_DENIED: - user doesn't have the necessary permissions on this MC account; - \* FAILED_PRECONDITION: - The account is not a Merchant Center - account; - MC account doesn't have a homepage; - claiming failed - (in this case the error message will contain more details). - - Returns: - Callable[[~.ClaimHomepageRequest], - Awaitable[~.Homepage]]: - 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 'claim_homepage' not in self._stubs: - self._stubs['claim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/ClaimHomepage', - request_serializer=homepage.ClaimHomepageRequest.serialize, - response_deserializer=homepage.Homepage.deserialize, - ) - return self._stubs['claim_homepage'] - - @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - Awaitable[homepage.Homepage]]: - r"""Return a callable for the unclaim homepage method over gRPC. - - Unclaims a store's homepage. Executing this method - requires admin access. - - Returns: - Callable[[~.UnclaimHomepageRequest], - Awaitable[~.Homepage]]: - 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 'unclaim_homepage' not in self._stubs: - self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.HomepageService/UnclaimHomepage', - request_serializer=homepage.UnclaimHomepageRequest.serialize, - response_deserializer=homepage.Homepage.deserialize, - ) - return self._stubs['unclaim_homepage'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_homepage: self._wrap_method( - self.get_homepage, - default_timeout=None, - client_info=client_info, - ), - self.update_homepage: self._wrap_method( - self.update_homepage, - default_timeout=None, - client_info=client_info, - ), - self.claim_homepage: self._wrap_method( - self.claim_homepage, - default_timeout=None, - client_info=client_info, - ), - self.unclaim_homepage: self._wrap_method( - self.unclaim_homepage, - 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__ = ( - 'HomepageServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py deleted file mode 100644 index 9b11be9cd643..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest.py +++ /dev/null @@ -1,874 +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.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage - - -from .rest_base import _BaseHomepageServiceRestTransport -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 HomepageServiceRestInterceptor: - """Interceptor for HomepageService. - - 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 HomepageServiceRestTransport. - - .. code-block:: python - class MyCustomHomepageServiceInterceptor(HomepageServiceRestInterceptor): - def pre_claim_homepage(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_claim_homepage(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_homepage(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_homepage(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_unclaim_homepage(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_unclaim_homepage(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_homepage(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_homepage(self, response): - logging.log(f"Received response: {response}") - return response - - transport = HomepageServiceRestTransport(interceptor=MyCustomHomepageServiceInterceptor()) - client = HomepageServiceClient(transport=transport) - - - """ - def pre_claim_homepage(self, request: homepage.ClaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for claim_homepage - - Override in a subclass to manipulate the request or metadata - before they are sent to the HomepageService server. - """ - return request, metadata - - def post_claim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: - """Post-rpc interceptor for claim_homepage - - DEPRECATED. Please use the `post_claim_homepage_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. This `post_claim_homepage` interceptor runs - before the `post_claim_homepage_with_metadata` interceptor. - """ - return response - - def post_claim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for claim_homepage - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the HomepageService server but before it is returned to user code. - - We recommend only using this `post_claim_homepage_with_metadata` - interceptor in new development instead of the `post_claim_homepage` interceptor. - When both interceptors are used, this `post_claim_homepage_with_metadata` interceptor runs after the - `post_claim_homepage` interceptor. The (possibly modified) response returned by - `post_claim_homepage` will be passed to - `post_claim_homepage_with_metadata`. - """ - return response, metadata - - def pre_get_homepage(self, request: homepage.GetHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_homepage - - Override in a subclass to manipulate the request or metadata - before they are sent to the HomepageService server. - """ - return request, metadata - - def post_get_homepage(self, response: homepage.Homepage) -> homepage.Homepage: - """Post-rpc interceptor for get_homepage - - DEPRECATED. Please use the `post_get_homepage_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. This `post_get_homepage` interceptor runs - before the `post_get_homepage_with_metadata` interceptor. - """ - return response - - def post_get_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_homepage - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the HomepageService server but before it is returned to user code. - - We recommend only using this `post_get_homepage_with_metadata` - interceptor in new development instead of the `post_get_homepage` interceptor. - When both interceptors are used, this `post_get_homepage_with_metadata` interceptor runs after the - `post_get_homepage` interceptor. The (possibly modified) response returned by - `post_get_homepage` will be passed to - `post_get_homepage_with_metadata`. - """ - return response, metadata - - def pre_unclaim_homepage(self, request: homepage.UnclaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for unclaim_homepage - - Override in a subclass to manipulate the request or metadata - before they are sent to the HomepageService server. - """ - return request, metadata - - def post_unclaim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: - """Post-rpc interceptor for unclaim_homepage - - DEPRECATED. Please use the `post_unclaim_homepage_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. This `post_unclaim_homepage` interceptor runs - before the `post_unclaim_homepage_with_metadata` interceptor. - """ - return response - - def post_unclaim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for unclaim_homepage - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the HomepageService server but before it is returned to user code. - - We recommend only using this `post_unclaim_homepage_with_metadata` - interceptor in new development instead of the `post_unclaim_homepage` interceptor. - When both interceptors are used, this `post_unclaim_homepage_with_metadata` interceptor runs after the - `post_unclaim_homepage` interceptor. The (possibly modified) response returned by - `post_unclaim_homepage` will be passed to - `post_unclaim_homepage_with_metadata`. - """ - return response, metadata - - def pre_update_homepage(self, request: gsma_homepage.UpdateHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_homepage - - Override in a subclass to manipulate the request or metadata - before they are sent to the HomepageService server. - """ - return request, metadata - - def post_update_homepage(self, response: gsma_homepage.Homepage) -> gsma_homepage.Homepage: - """Post-rpc interceptor for update_homepage - - DEPRECATED. Please use the `post_update_homepage_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the HomepageService server but before - it is returned to user code. This `post_update_homepage` interceptor runs - before the `post_update_homepage_with_metadata` interceptor. - """ - return response - - def post_update_homepage_with_metadata(self, response: gsma_homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_homepage - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the HomepageService server but before it is returned to user code. - - We recommend only using this `post_update_homepage_with_metadata` - interceptor in new development instead of the `post_update_homepage` interceptor. - When both interceptors are used, this `post_update_homepage_with_metadata` interceptor runs after the - `post_update_homepage` interceptor. The (possibly modified) response returned by - `post_update_homepage` will be passed to - `post_update_homepage_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class HomepageServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: HomepageServiceRestInterceptor - - -class HomepageServiceRestTransport(_BaseHomepageServiceRestTransport): - """REST backend synchronous transport for HomepageService. - - Service to support an API for a store's homepage. - - 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[HomepageServiceRestInterceptor] = 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 HomepageServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ClaimHomepage(_BaseHomepageServiceRestTransport._BaseClaimHomepage, HomepageServiceRestStub): - def __hash__(self): - return hash("HomepageServiceRestTransport.ClaimHomepage") - - @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: homepage.ClaimHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> homepage.Homepage: - r"""Call the claim homepage method over HTTP. - - Args: - request (~.homepage.ClaimHomepageRequest): - The request object. Request message for the ``ClaimHomepage`` 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: - ~.homepage.Homepage: - A store's homepage. - """ - - http_options = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_http_options() - - request, metadata = self._interceptor.pre_claim_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_transcoded_request(http_options, request) - - body = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.ClaimHomepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "ClaimHomepage", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = HomepageServiceRestTransport._ClaimHomepage._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 = homepage.Homepage() - pb_resp = homepage.Homepage.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_claim_homepage(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_claim_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.claim_homepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "ClaimHomepage", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetHomepage(_BaseHomepageServiceRestTransport._BaseGetHomepage, HomepageServiceRestStub): - def __hash__(self): - return hash("HomepageServiceRestTransport.GetHomepage") - - @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: homepage.GetHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> homepage.Homepage: - r"""Call the get homepage method over HTTP. - - Args: - request (~.homepage.GetHomepageRequest): - The request object. Request message for the ``GetHomepage`` 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: - ~.homepage.Homepage: - A store's homepage. - """ - - http_options = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_http_options() - - request, metadata = self._interceptor.pre_get_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.GetHomepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "GetHomepage", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = HomepageServiceRestTransport._GetHomepage._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 = homepage.Homepage() - pb_resp = homepage.Homepage.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_homepage(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.get_homepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "GetHomepage", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UnclaimHomepage(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage, HomepageServiceRestStub): - def __hash__(self): - return hash("HomepageServiceRestTransport.UnclaimHomepage") - - @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: homepage.UnclaimHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> homepage.Homepage: - r"""Call the unclaim homepage method over HTTP. - - Args: - request (~.homepage.UnclaimHomepageRequest): - The request object. Request message for the ``UnclaimHomepage`` 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: - ~.homepage.Homepage: - A store's homepage. - """ - - http_options = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_http_options() - - request, metadata = self._interceptor.pre_unclaim_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_transcoded_request(http_options, request) - - body = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.UnclaimHomepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "UnclaimHomepage", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = HomepageServiceRestTransport._UnclaimHomepage._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 = homepage.Homepage() - pb_resp = homepage.Homepage.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_unclaim_homepage(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_unclaim_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.unclaim_homepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "UnclaimHomepage", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateHomepage(_BaseHomepageServiceRestTransport._BaseUpdateHomepage, HomepageServiceRestStub): - def __hash__(self): - return hash("HomepageServiceRestTransport.UpdateHomepage") - - @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: gsma_homepage.UpdateHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_homepage.Homepage: - r"""Call the update homepage method over HTTP. - - Args: - request (~.gsma_homepage.UpdateHomepageRequest): - The request object. Request message for the ``UpdateHomepage`` 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: - ~.gsma_homepage.Homepage: - A store's homepage. - """ - - http_options = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_http_options() - - request, metadata = self._interceptor.pre_update_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_transcoded_request(http_options, request) - - body = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.HomepageServiceClient.UpdateHomepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "UpdateHomepage", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = HomepageServiceRestTransport._UpdateHomepage._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 = gsma_homepage.Homepage() - pb_resp = gsma_homepage.Homepage.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_homepage(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gsma_homepage.Homepage.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.accounts_v1beta.HomepageServiceClient.update_homepage", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "rpcName": "UpdateHomepage", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - homepage.Homepage]: - # 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._ClaimHomepage(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - homepage.Homepage]: - # 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._GetHomepage(self._session, self._host, self._interceptor) # type: ignore - - @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - homepage.Homepage]: - # 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._UnclaimHomepage(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - gsma_homepage.Homepage]: - # 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._UpdateHomepage(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'HomepageServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py deleted file mode 100644 index b9664f2922e0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/homepage_service/transports/rest_base.py +++ /dev/null @@ -1,270 +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 HomepageServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage - - -class _BaseHomepageServiceRestTransport(HomepageServiceTransport): - """Base REST backend transport for HomepageService. - - 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 _BaseClaimHomepage: - 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': '/accounts/v1beta/{name=accounts/*/homepage}:claim', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = homepage.ClaimHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseClaimHomepage._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetHomepage: - 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': '/accounts/v1beta/{name=accounts/*/homepage}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = homepage.GetHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseGetHomepage._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUnclaimHomepage: - 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': '/accounts/v1beta/{name=accounts/*/homepage}:unclaim', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = homepage.UnclaimHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateHomepage: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{homepage.name=accounts/*/homepage}', - 'body': 'homepage', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gsma_homepage.UpdateHomepageRequest.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(_BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseHomepageServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/__init__.py deleted file mode 100644 index bdfa6c11d195..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_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 LfpProvidersServiceClient -from .async_client import LfpProvidersServiceAsyncClient - -__all__ = ( - 'LfpProvidersServiceClient', - 'LfpProvidersServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py deleted file mode 100644 index 568e636b870f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/async_client.py +++ /dev/null @@ -1,503 +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_accounts_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.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import pagers -from google.shopping.merchant_accounts_v1beta.types import lfpproviders -from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport -from .client import LfpProvidersServiceClient - -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 LfpProvidersServiceAsyncClient: - """The service facilitates the management of a merchant's LFP provider - settings. This API defines the following resource model: - - - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] - """ - - _client: LfpProvidersServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = LfpProvidersServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = LfpProvidersServiceClient._DEFAULT_UNIVERSE - - lfp_provider_path = staticmethod(LfpProvidersServiceClient.lfp_provider_path) - parse_lfp_provider_path = staticmethod(LfpProvidersServiceClient.parse_lfp_provider_path) - omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.omnichannel_setting_path) - parse_omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.parse_omnichannel_setting_path) - common_billing_account_path = staticmethod(LfpProvidersServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LfpProvidersServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(LfpProvidersServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LfpProvidersServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LfpProvidersServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LfpProvidersServiceClient.parse_common_organization_path) - common_project_path = staticmethod(LfpProvidersServiceClient.common_project_path) - parse_common_project_path = staticmethod(LfpProvidersServiceClient.parse_common_project_path) - common_location_path = staticmethod(LfpProvidersServiceClient.common_location_path) - parse_common_location_path = staticmethod(LfpProvidersServiceClient.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: - LfpProvidersServiceAsyncClient: The constructed client. - """ - return LfpProvidersServiceClient.from_service_account_info.__func__(LfpProvidersServiceAsyncClient, 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: - LfpProvidersServiceAsyncClient: The constructed client. - """ - return LfpProvidersServiceClient.from_service_account_file.__func__(LfpProvidersServiceAsyncClient, 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 LfpProvidersServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> LfpProvidersServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpProvidersServiceTransport: 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 = LfpProvidersServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lfp providers 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,LfpProvidersServiceTransport,Callable[..., LfpProvidersServiceTransport]]]): - 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 LfpProvidersServiceTransport 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 = LfpProvidersServiceClient( - 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.accounts_v1beta.LfpProvidersServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "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.accounts.v1beta.LfpProvidersService", - "credentialsType": None, - } - ) - - async def find_lfp_providers(self, - request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersAsyncPager: - r"""Find the LFP provider candidates in a given country. - - .. 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_accounts_v1beta - - async def sample_find_lfp_providers(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.FindLfpProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.find_lfp_providers(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest, dict]]): - The request object. Request message for the - FindLfpProviders method. - parent (:class:`str`): - Required. The name of the parent resource under which - the LFP providers are found. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. - - 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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersAsyncPager: - Response message for the - FindLfpProviders 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, lfpproviders.FindLfpProvidersRequest): - request = lfpproviders.FindLfpProvidersRequest(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.find_lfp_providers] - - # 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.FindLfpProvidersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def link_lfp_provider(self, - request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpproviders.LinkLfpProviderResponse: - r"""Link the specified merchant to a LFP provider for the - specified country. - - .. 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_accounts_v1beta - - async def sample_link_lfp_provider(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkLfpProviderRequest( - name="name_value", - external_account_id="external_account_id_value", - ) - - # Make the request - response = await client.link_lfp_provider(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest, dict]]): - The request object. Request message for the - LinkLfpProvider method. - name (:class:`str`): - Required. The name of the LFP provider resource to link. - Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. - The ``lfp_provider`` is the LFP provider ID. - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse: - Response message for the - LinkLfpProvider method. - - """ - # 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, lfpproviders.LinkLfpProviderRequest): - request = lfpproviders.LinkLfpProviderRequest(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.link_lfp_provider] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "LfpProvidersServiceAsyncClient": - 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__ = ( - "LfpProvidersServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py deleted file mode 100644 index 28f3b739a88e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/client.py +++ /dev/null @@ -1,871 +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_accounts_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.protobuf import empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import pagers -from google.shopping.merchant_accounts_v1beta.types import lfpproviders -from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import LfpProvidersServiceGrpcTransport -from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport -from .transports.rest import LfpProvidersServiceRestTransport - - -class LfpProvidersServiceClientMeta(type): - """Metaclass for the LfpProvidersService 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[LfpProvidersServiceTransport]] - _transport_registry["grpc"] = LfpProvidersServiceGrpcTransport - _transport_registry["grpc_asyncio"] = LfpProvidersServiceGrpcAsyncIOTransport - _transport_registry["rest"] = LfpProvidersServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LfpProvidersServiceTransport]: - """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 LfpProvidersServiceClient(metaclass=LfpProvidersServiceClientMeta): - """The service facilitates the management of a merchant's LFP provider - settings. This API defines the following resource model: - - - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] - """ - - @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: - LfpProvidersServiceClient: 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: - LfpProvidersServiceClient: 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) -> LfpProvidersServiceTransport: - """Returns the transport used by the client instance. - - Returns: - LfpProvidersServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def lfp_provider_path(account: str,omnichannel_setting: str,lfp_provider: str,) -> str: - """Returns a fully-qualified lfp_provider string.""" - return "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) - - @staticmethod - def parse_lfp_provider_path(path: str) -> Dict[str,str]: - """Parses a lfp_provider path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)/lfpProviders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: - """Returns a fully-qualified omnichannel_setting string.""" - return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) - - @staticmethod - def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: - """Parses a omnichannel_setting path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?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 = LfpProvidersServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = LfpProvidersServiceClient._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 = LfpProvidersServiceClient._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, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the lfp providers 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,LfpProvidersServiceTransport,Callable[..., LfpProvidersServiceTransport]]]): - 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 LfpProvidersServiceTransport 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 = LfpProvidersServiceClient._read_environment_variables() - self._client_cert_source = LfpProvidersServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LfpProvidersServiceClient._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, LfpProvidersServiceTransport) - if transport_provided: - # transport is a LfpProvidersServiceTransport 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(LfpProvidersServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - LfpProvidersServiceClient._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[LfpProvidersServiceTransport], Callable[..., LfpProvidersServiceTransport]] = ( - LfpProvidersServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., LfpProvidersServiceTransport], 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.accounts_v1beta.LfpProvidersServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "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.accounts.v1beta.LfpProvidersService", - "credentialsType": None, - } - ) - - def find_lfp_providers(self, - request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersPager: - r"""Find the LFP provider candidates in a given country. - - .. 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_accounts_v1beta - - def sample_find_lfp_providers(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.FindLfpProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.find_lfp_providers(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest, dict]): - The request object. Request message for the - FindLfpProviders method. - parent (str): - Required. The name of the parent resource under which - the LFP providers are found. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. - - 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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersPager: - Response message for the - FindLfpProviders 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, lfpproviders.FindLfpProvidersRequest): - request = lfpproviders.FindLfpProvidersRequest(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.find_lfp_providers] - - # 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.FindLfpProvidersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def link_lfp_provider(self, - request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpproviders.LinkLfpProviderResponse: - r"""Link the specified merchant to a LFP provider for the - specified country. - - .. 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_accounts_v1beta - - def sample_link_lfp_provider(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkLfpProviderRequest( - name="name_value", - external_account_id="external_account_id_value", - ) - - # Make the request - response = client.link_lfp_provider(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest, dict]): - The request object. Request message for the - LinkLfpProvider method. - name (str): - Required. The name of the LFP provider resource to link. - Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. - The ``lfp_provider`` is the LFP provider ID. - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse: - Response message for the - LinkLfpProvider method. - - """ - # 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, lfpproviders.LinkLfpProviderRequest): - request = lfpproviders.LinkLfpProviderRequest(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.link_lfp_provider] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "LfpProvidersServiceClient": - 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__ = ( - "LfpProvidersServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/pagers.py deleted file mode 100644 index 805c4d815ee2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_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_accounts_v1beta.types import lfpproviders - - -class FindLfpProvidersPager: - """A pager for iterating through ``find_lfp_providers`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``lfp_providers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``FindLfpProviders`` requests and continue to iterate - through the ``lfp_providers`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` - 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[..., lfpproviders.FindLfpProvidersResponse], - request: lfpproviders.FindLfpProvidersRequest, - response: lfpproviders.FindLfpProvidersResponse, - *, - 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_accounts_v1beta.types.FindLfpProvidersRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse): - 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 = lfpproviders.FindLfpProvidersRequest(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[lfpproviders.FindLfpProvidersResponse]: - 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[lfpproviders.LfpProvider]: - for page in self.pages: - yield from page.lfp_providers - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class FindLfpProvidersAsyncPager: - """A pager for iterating through ``find_lfp_providers`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``lfp_providers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``FindLfpProviders`` requests and continue to iterate - through the ``lfp_providers`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse` - 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[lfpproviders.FindLfpProvidersResponse]], - request: lfpproviders.FindLfpProvidersRequest, - response: lfpproviders.FindLfpProvidersResponse, - *, - 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_accounts_v1beta.types.FindLfpProvidersRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersResponse): - 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 = lfpproviders.FindLfpProvidersRequest(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[lfpproviders.FindLfpProvidersResponse]: - 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[lfpproviders.LfpProvider]: - async def async_generator(): - async for page in self.pages: - for response in page.lfp_providers: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst deleted file mode 100644 index 9ef07da24bc0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`LfpProvidersServiceTransport` is the ABC for all transports. -- public child `LfpProvidersServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `LfpProvidersServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseLfpProvidersServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `LfpProvidersServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py deleted file mode 100644 index 4ef183de0240..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import lfpproviders - -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 LfpProvidersServiceTransport(abc.ABC): - """Abstract transport class for LfpProvidersService.""" - - 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.find_lfp_providers: gapic_v1.method.wrap_method( - self.find_lfp_providers, - default_timeout=None, - client_info=client_info, - ), - self.link_lfp_provider: gapic_v1.method.wrap_method( - self.link_lfp_provider, - 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 find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - Union[ - lfpproviders.FindLfpProvidersResponse, - Awaitable[lfpproviders.FindLfpProvidersResponse] - ]]: - raise NotImplementedError() - - @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - Union[ - lfpproviders.LinkLfpProviderResponse, - Awaitable[lfpproviders.LinkLfpProviderResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'LfpProvidersServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py deleted file mode 100644 index 3b895a104779..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc.py +++ /dev/null @@ -1,376 +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.shopping.merchant_accounts_v1beta.types import lfpproviders -from .base import LfpProvidersServiceTransport, 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.accounts.v1beta.LfpProvidersService", - "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.accounts.v1beta.LfpProvidersService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpProvidersServiceGrpcTransport(LfpProvidersServiceTransport): - """gRPC backend transport for LfpProvidersService. - - The service facilitates the management of a merchant's LFP provider - settings. This API defines the following resource model: - - - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] - - 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 find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - lfpproviders.FindLfpProvidersResponse]: - r"""Return a callable for the find lfp providers method over gRPC. - - Find the LFP provider candidates in a given country. - - Returns: - Callable[[~.FindLfpProvidersRequest], - ~.FindLfpProvidersResponse]: - 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 'find_lfp_providers' not in self._stubs: - self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/FindLfpProviders', - request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, - response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, - ) - return self._stubs['find_lfp_providers'] - - @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - lfpproviders.LinkLfpProviderResponse]: - r"""Return a callable for the link lfp provider method over gRPC. - - Link the specified merchant to a LFP provider for the - specified country. - - Returns: - Callable[[~.LinkLfpProviderRequest], - ~.LinkLfpProviderResponse]: - 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 'link_lfp_provider' not in self._stubs: - self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/LinkLfpProvider', - request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, - response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, - ) - return self._stubs['link_lfp_provider'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'LfpProvidersServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py deleted file mode 100644 index 74eacd7b3931..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,402 +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.shopping.merchant_accounts_v1beta.types import lfpproviders -from .base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import LfpProvidersServiceGrpcTransport - -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.accounts.v1beta.LfpProvidersService", - "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.accounts.v1beta.LfpProvidersService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class LfpProvidersServiceGrpcAsyncIOTransport(LfpProvidersServiceTransport): - """gRPC AsyncIO backend transport for LfpProvidersService. - - The service facilitates the management of a merchant's LFP provider - settings. This API defines the following resource model: - - - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] - - 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 find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - Awaitable[lfpproviders.FindLfpProvidersResponse]]: - r"""Return a callable for the find lfp providers method over gRPC. - - Find the LFP provider candidates in a given country. - - Returns: - Callable[[~.FindLfpProvidersRequest], - Awaitable[~.FindLfpProvidersResponse]]: - 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 'find_lfp_providers' not in self._stubs: - self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/FindLfpProviders', - request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, - response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, - ) - return self._stubs['find_lfp_providers'] - - @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - Awaitable[lfpproviders.LinkLfpProviderResponse]]: - r"""Return a callable for the link lfp provider method over gRPC. - - Link the specified merchant to a LFP provider for the - specified country. - - Returns: - Callable[[~.LinkLfpProviderRequest], - Awaitable[~.LinkLfpProviderResponse]]: - 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 'link_lfp_provider' not in self._stubs: - self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.LfpProvidersService/LinkLfpProvider', - request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, - response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, - ) - return self._stubs['link_lfp_provider'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.find_lfp_providers: self._wrap_method( - self.find_lfp_providers, - default_timeout=None, - client_info=client_info, - ), - self.link_lfp_provider: self._wrap_method( - self.link_lfp_provider, - 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__ = ( - 'LfpProvidersServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py deleted file mode 100644 index 7657118ca9e6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest.py +++ /dev/null @@ -1,534 +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.shopping.merchant_accounts_v1beta.types import lfpproviders - - -from .rest_base import _BaseLfpProvidersServiceRestTransport -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 LfpProvidersServiceRestInterceptor: - """Interceptor for LfpProvidersService. - - 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 LfpProvidersServiceRestTransport. - - .. code-block:: python - class MyCustomLfpProvidersServiceInterceptor(LfpProvidersServiceRestInterceptor): - def pre_find_lfp_providers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_find_lfp_providers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_link_lfp_provider(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_link_lfp_provider(self, response): - logging.log(f"Received response: {response}") - return response - - transport = LfpProvidersServiceRestTransport(interceptor=MyCustomLfpProvidersServiceInterceptor()) - client = LfpProvidersServiceClient(transport=transport) - - - """ - def pre_find_lfp_providers(self, request: lfpproviders.FindLfpProvidersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for find_lfp_providers - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpProvidersService server. - """ - return request, metadata - - def post_find_lfp_providers(self, response: lfpproviders.FindLfpProvidersResponse) -> lfpproviders.FindLfpProvidersResponse: - """Post-rpc interceptor for find_lfp_providers - - DEPRECATED. Please use the `post_find_lfp_providers_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the LfpProvidersService server but before - it is returned to user code. This `post_find_lfp_providers` interceptor runs - before the `post_find_lfp_providers_with_metadata` interceptor. - """ - return response - - def post_find_lfp_providers_with_metadata(self, response: lfpproviders.FindLfpProvidersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for find_lfp_providers - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the LfpProvidersService server but before it is returned to user code. - - We recommend only using this `post_find_lfp_providers_with_metadata` - interceptor in new development instead of the `post_find_lfp_providers` interceptor. - When both interceptors are used, this `post_find_lfp_providers_with_metadata` interceptor runs after the - `post_find_lfp_providers` interceptor. The (possibly modified) response returned by - `post_find_lfp_providers` will be passed to - `post_find_lfp_providers_with_metadata`. - """ - return response, metadata - - def pre_link_lfp_provider(self, request: lfpproviders.LinkLfpProviderRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for link_lfp_provider - - Override in a subclass to manipulate the request or metadata - before they are sent to the LfpProvidersService server. - """ - return request, metadata - - def post_link_lfp_provider(self, response: lfpproviders.LinkLfpProviderResponse) -> lfpproviders.LinkLfpProviderResponse: - """Post-rpc interceptor for link_lfp_provider - - DEPRECATED. Please use the `post_link_lfp_provider_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the LfpProvidersService server but before - it is returned to user code. This `post_link_lfp_provider` interceptor runs - before the `post_link_lfp_provider_with_metadata` interceptor. - """ - return response - - def post_link_lfp_provider_with_metadata(self, response: lfpproviders.LinkLfpProviderResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for link_lfp_provider - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the LfpProvidersService server but before it is returned to user code. - - We recommend only using this `post_link_lfp_provider_with_metadata` - interceptor in new development instead of the `post_link_lfp_provider` interceptor. - When both interceptors are used, this `post_link_lfp_provider_with_metadata` interceptor runs after the - `post_link_lfp_provider` interceptor. The (possibly modified) response returned by - `post_link_lfp_provider` will be passed to - `post_link_lfp_provider_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class LfpProvidersServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: LfpProvidersServiceRestInterceptor - - -class LfpProvidersServiceRestTransport(_BaseLfpProvidersServiceRestTransport): - """REST backend synchronous transport for LfpProvidersService. - - The service facilitates the management of a merchant's LFP provider - settings. This API defines the following resource model: - - - [LfpProvider][google.shopping.merchant.accounts.v1.LfpProvider] - - 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[LfpProvidersServiceRestInterceptor] = 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 LfpProvidersServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _FindLfpProviders(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders, LfpProvidersServiceRestStub): - def __hash__(self): - return hash("LfpProvidersServiceRestTransport.FindLfpProviders") - - @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: lfpproviders.FindLfpProvidersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpproviders.FindLfpProvidersResponse: - r"""Call the find lfp providers method over HTTP. - - Args: - request (~.lfpproviders.FindLfpProvidersRequest): - The request object. Request message for the - FindLfpProviders 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: - ~.lfpproviders.FindLfpProvidersResponse: - Response message for the - FindLfpProviders method. - - """ - - http_options = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_http_options() - - request, metadata = self._interceptor.pre_find_lfp_providers(request, metadata) - transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.LfpProvidersServiceClient.FindLfpProviders", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "rpcName": "FindLfpProviders", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpProvidersServiceRestTransport._FindLfpProviders._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 = lfpproviders.FindLfpProvidersResponse() - pb_resp = lfpproviders.FindLfpProvidersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_find_lfp_providers(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_find_lfp_providers_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpproviders.FindLfpProvidersResponse.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.accounts_v1beta.LfpProvidersServiceClient.find_lfp_providers", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "rpcName": "FindLfpProviders", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _LinkLfpProvider(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider, LfpProvidersServiceRestStub): - def __hash__(self): - return hash("LfpProvidersServiceRestTransport.LinkLfpProvider") - - @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: lfpproviders.LinkLfpProviderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpproviders.LinkLfpProviderResponse: - r"""Call the link lfp provider method over HTTP. - - Args: - request (~.lfpproviders.LinkLfpProviderRequest): - The request object. Request message for the - LinkLfpProvider 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: - ~.lfpproviders.LinkLfpProviderResponse: - Response message for the - LinkLfpProvider method. - - """ - - http_options = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_http_options() - - request, metadata = self._interceptor.pre_link_lfp_provider(request, metadata) - transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_transcoded_request(http_options, request) - - body = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.LfpProvidersServiceClient.LinkLfpProvider", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "rpcName": "LinkLfpProvider", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = LfpProvidersServiceRestTransport._LinkLfpProvider._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 = lfpproviders.LinkLfpProviderResponse() - pb_resp = lfpproviders.LinkLfpProviderResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_link_lfp_provider(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_link_lfp_provider_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = lfpproviders.LinkLfpProviderResponse.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.accounts_v1beta.LfpProvidersServiceClient.link_lfp_provider", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "rpcName": "LinkLfpProvider", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - lfpproviders.FindLfpProvidersResponse]: - # 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._FindLfpProviders(self._session, self._host, self._interceptor) # type: ignore - - @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - lfpproviders.LinkLfpProviderResponse]: - # 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._LinkLfpProvider(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'LfpProvidersServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py deleted file mode 100644 index eecd7728d991..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import lfpproviders - - -class _BaseLfpProvidersServiceRestTransport(LfpProvidersServiceTransport): - """Base REST backend transport for LfpProvidersService. - - 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 _BaseFindLfpProviders: - 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': '/accounts/v1beta/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpproviders.FindLfpProvidersRequest.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(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseLinkLfpProvider: - 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': '/accounts/v1beta/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = lfpproviders.LinkLfpProviderRequest.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(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseLfpProvidersServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/__init__.py deleted file mode 100644 index 242598846a6e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_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 OmnichannelSettingsServiceClient -from .async_client import OmnichannelSettingsServiceAsyncClient - -__all__ = ( - 'OmnichannelSettingsServiceClient', - 'OmnichannelSettingsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py deleted file mode 100644 index 7c890b9abcf5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/async_client.py +++ /dev/null @@ -1,866 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import pagers -from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings -from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport -from .client import OmnichannelSettingsServiceClient - -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 OmnichannelSettingsServiceAsyncClient: - """The service facilitates the management of a merchant's omnichannel - settings. - - This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] - """ - - _client: OmnichannelSettingsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(OmnichannelSettingsServiceClient.account_path) - parse_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_account_path) - omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.omnichannel_setting_path) - parse_omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.parse_omnichannel_setting_path) - common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OmnichannelSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OmnichannelSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OmnichannelSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(OmnichannelSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(OmnichannelSettingsServiceClient.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: - OmnichannelSettingsServiceAsyncClient: The constructed client. - """ - return OmnichannelSettingsServiceClient.from_service_account_info.__func__(OmnichannelSettingsServiceAsyncClient, 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: - OmnichannelSettingsServiceAsyncClient: The constructed client. - """ - return OmnichannelSettingsServiceClient.from_service_account_file.__func__(OmnichannelSettingsServiceAsyncClient, 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 OmnichannelSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> OmnichannelSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OmnichannelSettingsServiceTransport: 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 = OmnichannelSettingsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the omnichannel settings 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,OmnichannelSettingsServiceTransport,Callable[..., OmnichannelSettingsServiceTransport]]]): - 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 OmnichannelSettingsServiceTransport 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 = OmnichannelSettingsServiceClient( - 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.accounts_v1beta.OmnichannelSettingsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "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.accounts.v1beta.OmnichannelSettingsService", - "credentialsType": None, - } - ) - - async def get_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Get the omnichannel settings for a given merchant. - - .. 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_accounts_v1beta - - async def sample_get_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_omnichannel_setting(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest, dict]]): - The request object. Request message for the - GetOmnichannelSettings method. - name (:class:`str`): - Required. The name of the omnichannel setting to - retrieve. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - # 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, omnichannelsettings.GetOmnichannelSettingRequest): - request = omnichannelsettings.GetOmnichannelSettingRequest(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.get_omnichannel_setting] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_omnichannel_settings(self, - request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsAsyncPager: - r"""List all the omnichannel settings for a given - merchant. - - .. 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_accounts_v1beta - - async def sample_list_omnichannel_settings(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_omnichannel_settings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest, dict]]): - The request object. Request message for the - ListOmnichannelSettings method. - parent (:class:`str`): - Required. The parent, which owns this collection of - omnichannel settings. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsAsyncPager: - Response message for the - ListOmnichannelSettings 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, omnichannelsettings.ListOmnichannelSettingsRequest): - request = omnichannelsettings.ListOmnichannelSettingsRequest(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_omnichannel_settings] - - # 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.ListOmnichannelSettingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, - *, - parent: Optional[str] = None, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Create the omnichannel settings for a given merchant. - - .. 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_accounts_v1beta - - async def sample_create_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( - parent="parent_value", - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = await client.create_omnichannel_setting(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest, dict]]): - The request object. Request message for the - CreateOmnichannelSetting method. - parent (:class:`str`): - Required. The parent resource where this omnichannel - setting will be created. Format: ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - omnichannel_setting (:class:`google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting`): - Required. The omnichannel setting to - create. - - This corresponds to the ``omnichannel_setting`` 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_accounts_v1beta.types.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - # 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, omnichannel_setting] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, omnichannelsettings.CreateOmnichannelSettingRequest): - request = omnichannelsettings.CreateOmnichannelSettingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if omnichannel_setting is not None: - request.omnichannel_setting = omnichannel_setting - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_omnichannel_setting] - - # 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 update_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, - *, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Update the omnichannel setting for a given merchant - in a given country. - - .. 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_accounts_v1beta - - async def sample_update_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = await client.update_omnichannel_setting(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest, dict]]): - The request object. Request message for the - UpdateOmnichannelSetting method. - omnichannel_setting (:class:`google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting`): - Required. The omnichannel setting to update. - - The omnichannel setting's ``name`` field is used to - identify the omnichannel setting to be updated. - - This corresponds to the ``omnichannel_setting`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to be updated. - - The following fields are supported in snake_case only: - - - ``lsf_type`` - - ``in_stock`` - - ``pickup`` - - ``odo`` - - ``about`` - - ``inventory_verification`` - - Full replacement with wildcard ``*``\ is supported, - while empty/implied update mask is not. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - # 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 = [omnichannel_setting, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, omnichannelsettings.UpdateOmnichannelSettingRequest): - request = omnichannelsettings.UpdateOmnichannelSettingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if omnichannel_setting is not None: - request.omnichannel_setting = omnichannel_setting - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_omnichannel_setting] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("omnichannel_setting.name", request.omnichannel_setting.name), - )), - ) - - # 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 request_inventory_verification(self, - request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.RequestInventoryVerificationResponse: - r"""Requests inventory verification for a given merchant - in a given country. - - .. 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_accounts_v1beta - - async def sample_request_inventory_verification(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( - name="name_value", - ) - - # Make the request - response = await client.request_inventory_verification(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest, dict]]): - The request object. Request message for the - RequestInventoryVerification method. - name (:class:`str`): - Required. The name of the omnichannel setting to request - inventory verification. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse: - Response message for the - RequestInventoryVerification method. - - """ - # 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, omnichannelsettings.RequestInventoryVerificationRequest): - request = omnichannelsettings.RequestInventoryVerificationRequest(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.request_inventory_verification] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "OmnichannelSettingsServiceAsyncClient": - 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__ = ( - "OmnichannelSettingsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py deleted file mode 100644 index c7bf69f16a48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/client.py +++ /dev/null @@ -1,1231 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import pagers -from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings -from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import OmnichannelSettingsServiceGrpcTransport -from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport -from .transports.rest import OmnichannelSettingsServiceRestTransport - - -class OmnichannelSettingsServiceClientMeta(type): - """Metaclass for the OmnichannelSettingsService 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[OmnichannelSettingsServiceTransport]] - _transport_registry["grpc"] = OmnichannelSettingsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = OmnichannelSettingsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = OmnichannelSettingsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[OmnichannelSettingsServiceTransport]: - """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 OmnichannelSettingsServiceClient(metaclass=OmnichannelSettingsServiceClientMeta): - """The service facilitates the management of a merchant's omnichannel - settings. - - This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] - """ - - @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: - OmnichannelSettingsServiceClient: 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: - OmnichannelSettingsServiceClient: 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) -> OmnichannelSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OmnichannelSettingsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: - """Returns a fully-qualified omnichannel_setting string.""" - return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) - - @staticmethod - def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: - """Parses a omnichannel_setting path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?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 = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient._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, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the omnichannel settings 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,OmnichannelSettingsServiceTransport,Callable[..., OmnichannelSettingsServiceTransport]]]): - 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 OmnichannelSettingsServiceTransport 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 = OmnichannelSettingsServiceClient._read_environment_variables() - self._client_cert_source = OmnichannelSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = OmnichannelSettingsServiceClient._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, OmnichannelSettingsServiceTransport) - if transport_provided: - # transport is a OmnichannelSettingsServiceTransport 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(OmnichannelSettingsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - OmnichannelSettingsServiceClient._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[OmnichannelSettingsServiceTransport], Callable[..., OmnichannelSettingsServiceTransport]] = ( - OmnichannelSettingsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., OmnichannelSettingsServiceTransport], 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.accounts_v1beta.OmnichannelSettingsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "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.accounts.v1beta.OmnichannelSettingsService", - "credentialsType": None, - } - ) - - def get_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Get the omnichannel settings for a given merchant. - - .. 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_accounts_v1beta - - def sample_get_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( - name="name_value", - ) - - # Make the request - response = client.get_omnichannel_setting(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest, dict]): - The request object. Request message for the - GetOmnichannelSettings method. - name (str): - Required. The name of the omnichannel setting to - retrieve. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - # 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, omnichannelsettings.GetOmnichannelSettingRequest): - request = omnichannelsettings.GetOmnichannelSettingRequest(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.get_omnichannel_setting] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_omnichannel_settings(self, - request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsPager: - r"""List all the omnichannel settings for a given - merchant. - - .. 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_accounts_v1beta - - def sample_list_omnichannel_settings(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_omnichannel_settings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest, dict]): - The request object. Request message for the - ListOmnichannelSettings method. - parent (str): - Required. The parent, which owns this collection of - omnichannel settings. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsPager: - Response message for the - ListOmnichannelSettings 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, omnichannelsettings.ListOmnichannelSettingsRequest): - request = omnichannelsettings.ListOmnichannelSettingsRequest(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_omnichannel_settings] - - # 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.ListOmnichannelSettingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, - *, - parent: Optional[str] = None, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Create the omnichannel settings for a given merchant. - - .. 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_accounts_v1beta - - def sample_create_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( - parent="parent_value", - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = client.create_omnichannel_setting(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest, dict]): - The request object. Request message for the - CreateOmnichannelSetting method. - parent (str): - Required. The parent resource where this omnichannel - setting will be created. Format: ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): - Required. The omnichannel setting to - create. - - This corresponds to the ``omnichannel_setting`` 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_accounts_v1beta.types.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - # 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, omnichannel_setting] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, omnichannelsettings.CreateOmnichannelSettingRequest): - request = omnichannelsettings.CreateOmnichannelSettingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if omnichannel_setting is not None: - request.omnichannel_setting = omnichannel_setting - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_omnichannel_setting] - - # 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 update_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, - *, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Update the omnichannel setting for a given merchant - in a given country. - - .. 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_accounts_v1beta - - def sample_update_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = client.update_omnichannel_setting(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest, dict]): - The request object. Request message for the - UpdateOmnichannelSetting method. - omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): - Required. The omnichannel setting to update. - - The omnichannel setting's ``name`` field is used to - identify the omnichannel setting to be updated. - - This corresponds to the ``omnichannel_setting`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. - - The following fields are supported in snake_case only: - - - ``lsf_type`` - - ``in_stock`` - - ``pickup`` - - ``odo`` - - ``about`` - - ``inventory_verification`` - - Full replacement with wildcard ``*``\ is supported, - while empty/implied update mask is not. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - # 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 = [omnichannel_setting, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, omnichannelsettings.UpdateOmnichannelSettingRequest): - request = omnichannelsettings.UpdateOmnichannelSettingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if omnichannel_setting is not None: - request.omnichannel_setting = omnichannel_setting - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_omnichannel_setting] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("omnichannel_setting.name", request.omnichannel_setting.name), - )), - ) - - # 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 request_inventory_verification(self, - request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.RequestInventoryVerificationResponse: - r"""Requests inventory verification for a given merchant - in a given country. - - .. 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_accounts_v1beta - - def sample_request_inventory_verification(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( - name="name_value", - ) - - # Make the request - response = client.request_inventory_verification(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest, dict]): - The request object. Request message for the - RequestInventoryVerification method. - name (str): - Required. The name of the omnichannel setting to request - inventory verification. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse: - Response message for the - RequestInventoryVerification method. - - """ - # 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, omnichannelsettings.RequestInventoryVerificationRequest): - request = omnichannelsettings.RequestInventoryVerificationRequest(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.request_inventory_verification] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "OmnichannelSettingsServiceClient": - 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__ = ( - "OmnichannelSettingsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/pagers.py deleted file mode 100644 index 878a0a1d8f7a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_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_accounts_v1beta.types import omnichannelsettings - - -class ListOmnichannelSettingsPager: - """A pager for iterating through ``list_omnichannel_settings`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``omnichannel_settings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOmnichannelSettings`` requests and continue to iterate - through the ``omnichannel_settings`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` - 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[..., omnichannelsettings.ListOmnichannelSettingsResponse], - request: omnichannelsettings.ListOmnichannelSettingsRequest, - response: omnichannelsettings.ListOmnichannelSettingsResponse, - *, - 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_accounts_v1beta.types.ListOmnichannelSettingsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse): - 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 = omnichannelsettings.ListOmnichannelSettingsRequest(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[omnichannelsettings.ListOmnichannelSettingsResponse]: - 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[omnichannelsettings.OmnichannelSetting]: - for page in self.pages: - yield from page.omnichannel_settings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOmnichannelSettingsAsyncPager: - """A pager for iterating through ``list_omnichannel_settings`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``omnichannel_settings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOmnichannelSettings`` requests and continue to iterate - through the ``omnichannel_settings`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse` - 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[omnichannelsettings.ListOmnichannelSettingsResponse]], - request: omnichannelsettings.ListOmnichannelSettingsRequest, - response: omnichannelsettings.ListOmnichannelSettingsResponse, - *, - 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_accounts_v1beta.types.ListOmnichannelSettingsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsResponse): - 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 = omnichannelsettings.ListOmnichannelSettingsRequest(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[omnichannelsettings.ListOmnichannelSettingsResponse]: - 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[omnichannelsettings.OmnichannelSetting]: - async def async_generator(): - async for page in self.pages: - for response in page.omnichannel_settings: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst deleted file mode 100644 index 494c6b3d2bd7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`OmnichannelSettingsServiceTransport` is the ABC for all transports. -- public child `OmnichannelSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `OmnichannelSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseOmnichannelSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `OmnichannelSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/__init__.py deleted file mode 100644 index 60f6dbfcf9cd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_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 OmnichannelSettingsServiceTransport -from .grpc import OmnichannelSettingsServiceGrpcTransport -from .grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport -from .rest import OmnichannelSettingsServiceRestTransport -from .rest import OmnichannelSettingsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] -_transport_registry['grpc'] = OmnichannelSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OmnichannelSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = OmnichannelSettingsServiceRestTransport - -__all__ = ( - 'OmnichannelSettingsServiceTransport', - 'OmnichannelSettingsServiceGrpcTransport', - 'OmnichannelSettingsServiceGrpcAsyncIOTransport', - 'OmnichannelSettingsServiceRestTransport', - 'OmnichannelSettingsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py deleted file mode 100644 index f829a9364942..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/base.py +++ /dev/null @@ -1,215 +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_accounts_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.shopping.merchant_accounts_v1beta.types import omnichannelsettings - -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 OmnichannelSettingsServiceTransport(abc.ABC): - """Abstract transport class for OmnichannelSettingsService.""" - - 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.get_omnichannel_setting: gapic_v1.method.wrap_method( - self.get_omnichannel_setting, - default_timeout=None, - client_info=client_info, - ), - self.list_omnichannel_settings: gapic_v1.method.wrap_method( - self.list_omnichannel_settings, - default_timeout=None, - client_info=client_info, - ), - self.create_omnichannel_setting: gapic_v1.method.wrap_method( - self.create_omnichannel_setting, - default_timeout=None, - client_info=client_info, - ), - self.update_omnichannel_setting: gapic_v1.method.wrap_method( - self.update_omnichannel_setting, - default_timeout=None, - client_info=client_info, - ), - self.request_inventory_verification: gapic_v1.method.wrap_method( - self.request_inventory_verification, - 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 get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - Union[ - omnichannelsettings.OmnichannelSetting, - Awaitable[omnichannelsettings.OmnichannelSetting] - ]]: - raise NotImplementedError() - - @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - Union[ - omnichannelsettings.ListOmnichannelSettingsResponse, - Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse] - ]]: - raise NotImplementedError() - - @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - Union[ - omnichannelsettings.OmnichannelSetting, - Awaitable[omnichannelsettings.OmnichannelSetting] - ]]: - raise NotImplementedError() - - @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - Union[ - omnichannelsettings.OmnichannelSetting, - Awaitable[omnichannelsettings.OmnichannelSetting] - ]]: - raise NotImplementedError() - - @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - Union[ - omnichannelsettings.RequestInventoryVerificationResponse, - Awaitable[omnichannelsettings.RequestInventoryVerificationResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'OmnichannelSettingsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py deleted file mode 100644 index b2d67d4d7b40..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc.py +++ /dev/null @@ -1,459 +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.shopping.merchant_accounts_v1beta.types import omnichannelsettings -from .base import OmnichannelSettingsServiceTransport, 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.accounts.v1beta.OmnichannelSettingsService", - "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.accounts.v1beta.OmnichannelSettingsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class OmnichannelSettingsServiceGrpcTransport(OmnichannelSettingsServiceTransport): - """gRPC backend transport for OmnichannelSettingsService. - - The service facilitates the management of a merchant's omnichannel - settings. - - This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] - - 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 get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: - r"""Return a callable for the get omnichannel setting method over gRPC. - - Get the omnichannel settings for a given merchant. - - Returns: - Callable[[~.GetOmnichannelSettingRequest], - ~.OmnichannelSetting]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_omnichannel_setting' not in self._stubs: - self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/GetOmnichannelSetting', - request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, - response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, - ) - return self._stubs['get_omnichannel_setting'] - - @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - omnichannelsettings.ListOmnichannelSettingsResponse]: - r"""Return a callable for the list omnichannel settings method over gRPC. - - List all the omnichannel settings for a given - merchant. - - Returns: - Callable[[~.ListOmnichannelSettingsRequest], - ~.ListOmnichannelSettingsResponse]: - 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_omnichannel_settings' not in self._stubs: - self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/ListOmnichannelSettings', - request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, - response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, - ) - return self._stubs['list_omnichannel_settings'] - - @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: - r"""Return a callable for the create omnichannel setting method over gRPC. - - Create the omnichannel settings for a given merchant. - - Returns: - Callable[[~.CreateOmnichannelSettingRequest], - ~.OmnichannelSetting]: - 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 'create_omnichannel_setting' not in self._stubs: - self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/CreateOmnichannelSetting', - request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, - response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, - ) - return self._stubs['create_omnichannel_setting'] - - @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: - r"""Return a callable for the update omnichannel setting method over gRPC. - - Update the omnichannel setting for a given merchant - in a given country. - - Returns: - Callable[[~.UpdateOmnichannelSettingRequest], - ~.OmnichannelSetting]: - 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 'update_omnichannel_setting' not in self._stubs: - self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/UpdateOmnichannelSetting', - request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, - response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, - ) - return self._stubs['update_omnichannel_setting'] - - @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - omnichannelsettings.RequestInventoryVerificationResponse]: - r"""Return a callable for the request inventory verification method over gRPC. - - Requests inventory verification for a given merchant - in a given country. - - Returns: - Callable[[~.RequestInventoryVerificationRequest], - ~.RequestInventoryVerificationResponse]: - 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 'request_inventory_verification' not in self._stubs: - self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/RequestInventoryVerification', - request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, - response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, - ) - return self._stubs['request_inventory_verification'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'OmnichannelSettingsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py deleted file mode 100644 index 92d72348b164..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,500 +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.shopping.merchant_accounts_v1beta.types import omnichannelsettings -from .base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import OmnichannelSettingsServiceGrpcTransport - -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.accounts.v1beta.OmnichannelSettingsService", - "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.accounts.v1beta.OmnichannelSettingsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class OmnichannelSettingsServiceGrpcAsyncIOTransport(OmnichannelSettingsServiceTransport): - """gRPC AsyncIO backend transport for OmnichannelSettingsService. - - The service facilitates the management of a merchant's omnichannel - settings. - - This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] - - 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 get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - Awaitable[omnichannelsettings.OmnichannelSetting]]: - r"""Return a callable for the get omnichannel setting method over gRPC. - - Get the omnichannel settings for a given merchant. - - Returns: - Callable[[~.GetOmnichannelSettingRequest], - Awaitable[~.OmnichannelSetting]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_omnichannel_setting' not in self._stubs: - self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/GetOmnichannelSetting', - request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, - response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, - ) - return self._stubs['get_omnichannel_setting'] - - @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse]]: - r"""Return a callable for the list omnichannel settings method over gRPC. - - List all the omnichannel settings for a given - merchant. - - Returns: - Callable[[~.ListOmnichannelSettingsRequest], - Awaitable[~.ListOmnichannelSettingsResponse]]: - 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_omnichannel_settings' not in self._stubs: - self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/ListOmnichannelSettings', - request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, - response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, - ) - return self._stubs['list_omnichannel_settings'] - - @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - Awaitable[omnichannelsettings.OmnichannelSetting]]: - r"""Return a callable for the create omnichannel setting method over gRPC. - - Create the omnichannel settings for a given merchant. - - Returns: - Callable[[~.CreateOmnichannelSettingRequest], - Awaitable[~.OmnichannelSetting]]: - 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 'create_omnichannel_setting' not in self._stubs: - self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/CreateOmnichannelSetting', - request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, - response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, - ) - return self._stubs['create_omnichannel_setting'] - - @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - Awaitable[omnichannelsettings.OmnichannelSetting]]: - r"""Return a callable for the update omnichannel setting method over gRPC. - - Update the omnichannel setting for a given merchant - in a given country. - - Returns: - Callable[[~.UpdateOmnichannelSettingRequest], - Awaitable[~.OmnichannelSetting]]: - 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 'update_omnichannel_setting' not in self._stubs: - self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/UpdateOmnichannelSetting', - request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, - response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, - ) - return self._stubs['update_omnichannel_setting'] - - @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - Awaitable[omnichannelsettings.RequestInventoryVerificationResponse]]: - r"""Return a callable for the request inventory verification method over gRPC. - - Requests inventory verification for a given merchant - in a given country. - - Returns: - Callable[[~.RequestInventoryVerificationRequest], - Awaitable[~.RequestInventoryVerificationResponse]]: - 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 'request_inventory_verification' not in self._stubs: - self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService/RequestInventoryVerification', - request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, - response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, - ) - return self._stubs['request_inventory_verification'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_omnichannel_setting: self._wrap_method( - self.get_omnichannel_setting, - default_timeout=None, - client_info=client_info, - ), - self.list_omnichannel_settings: self._wrap_method( - self.list_omnichannel_settings, - default_timeout=None, - client_info=client_info, - ), - self.create_omnichannel_setting: self._wrap_method( - self.create_omnichannel_setting, - default_timeout=None, - client_info=client_info, - ), - self.update_omnichannel_setting: self._wrap_method( - self.update_omnichannel_setting, - default_timeout=None, - client_info=client_info, - ), - self.request_inventory_verification: self._wrap_method( - self.request_inventory_verification, - 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__ = ( - 'OmnichannelSettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py deleted file mode 100644 index 2e96b40c696d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest.py +++ /dev/null @@ -1,1068 +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.shopping.merchant_accounts_v1beta.types import omnichannelsettings - - -from .rest_base import _BaseOmnichannelSettingsServiceRestTransport -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 OmnichannelSettingsServiceRestInterceptor: - """Interceptor for OmnichannelSettingsService. - - 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 OmnichannelSettingsServiceRestTransport. - - .. code-block:: python - class MyCustomOmnichannelSettingsServiceInterceptor(OmnichannelSettingsServiceRestInterceptor): - def pre_create_omnichannel_setting(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_omnichannel_setting(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_omnichannel_setting(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_omnichannel_setting(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_omnichannel_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_omnichannel_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_request_inventory_verification(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_request_inventory_verification(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_omnichannel_setting(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_omnichannel_setting(self, response): - logging.log(f"Received response: {response}") - return response - - transport = OmnichannelSettingsServiceRestTransport(interceptor=MyCustomOmnichannelSettingsServiceInterceptor()) - client = OmnichannelSettingsServiceClient(transport=transport) - - - """ - def pre_create_omnichannel_setting(self, request: omnichannelsettings.CreateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.CreateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_omnichannel_setting - - Override in a subclass to manipulate the request or metadata - before they are sent to the OmnichannelSettingsService server. - """ - return request, metadata - - def post_create_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: - """Post-rpc interceptor for create_omnichannel_setting - - DEPRECATED. Please use the `post_create_omnichannel_setting_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OmnichannelSettingsService server but before - it is returned to user code. This `post_create_omnichannel_setting` interceptor runs - before the `post_create_omnichannel_setting_with_metadata` interceptor. - """ - return response - - def post_create_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_omnichannel_setting - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OmnichannelSettingsService server but before it is returned to user code. - - We recommend only using this `post_create_omnichannel_setting_with_metadata` - interceptor in new development instead of the `post_create_omnichannel_setting` interceptor. - When both interceptors are used, this `post_create_omnichannel_setting_with_metadata` interceptor runs after the - `post_create_omnichannel_setting` interceptor. The (possibly modified) response returned by - `post_create_omnichannel_setting` will be passed to - `post_create_omnichannel_setting_with_metadata`. - """ - return response, metadata - - def pre_get_omnichannel_setting(self, request: omnichannelsettings.GetOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.GetOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_omnichannel_setting - - Override in a subclass to manipulate the request or metadata - before they are sent to the OmnichannelSettingsService server. - """ - return request, metadata - - def post_get_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: - """Post-rpc interceptor for get_omnichannel_setting - - DEPRECATED. Please use the `post_get_omnichannel_setting_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OmnichannelSettingsService server but before - it is returned to user code. This `post_get_omnichannel_setting` interceptor runs - before the `post_get_omnichannel_setting_with_metadata` interceptor. - """ - return response - - def post_get_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_omnichannel_setting - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OmnichannelSettingsService server but before it is returned to user code. - - We recommend only using this `post_get_omnichannel_setting_with_metadata` - interceptor in new development instead of the `post_get_omnichannel_setting` interceptor. - When both interceptors are used, this `post_get_omnichannel_setting_with_metadata` interceptor runs after the - `post_get_omnichannel_setting` interceptor. The (possibly modified) response returned by - `post_get_omnichannel_setting` will be passed to - `post_get_omnichannel_setting_with_metadata`. - """ - return response, metadata - - def pre_list_omnichannel_settings(self, request: omnichannelsettings.ListOmnichannelSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_omnichannel_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the OmnichannelSettingsService server. - """ - return request, metadata - - def post_list_omnichannel_settings(self, response: omnichannelsettings.ListOmnichannelSettingsResponse) -> omnichannelsettings.ListOmnichannelSettingsResponse: - """Post-rpc interceptor for list_omnichannel_settings - - DEPRECATED. Please use the `post_list_omnichannel_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OmnichannelSettingsService server but before - it is returned to user code. This `post_list_omnichannel_settings` interceptor runs - before the `post_list_omnichannel_settings_with_metadata` interceptor. - """ - return response - - def post_list_omnichannel_settings_with_metadata(self, response: omnichannelsettings.ListOmnichannelSettingsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_omnichannel_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OmnichannelSettingsService server but before it is returned to user code. - - We recommend only using this `post_list_omnichannel_settings_with_metadata` - interceptor in new development instead of the `post_list_omnichannel_settings` interceptor. - When both interceptors are used, this `post_list_omnichannel_settings_with_metadata` interceptor runs after the - `post_list_omnichannel_settings` interceptor. The (possibly modified) response returned by - `post_list_omnichannel_settings` will be passed to - `post_list_omnichannel_settings_with_metadata`. - """ - return response, metadata - - def pre_request_inventory_verification(self, request: omnichannelsettings.RequestInventoryVerificationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for request_inventory_verification - - Override in a subclass to manipulate the request or metadata - before they are sent to the OmnichannelSettingsService server. - """ - return request, metadata - - def post_request_inventory_verification(self, response: omnichannelsettings.RequestInventoryVerificationResponse) -> omnichannelsettings.RequestInventoryVerificationResponse: - """Post-rpc interceptor for request_inventory_verification - - DEPRECATED. Please use the `post_request_inventory_verification_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OmnichannelSettingsService server but before - it is returned to user code. This `post_request_inventory_verification` interceptor runs - before the `post_request_inventory_verification_with_metadata` interceptor. - """ - return response - - def post_request_inventory_verification_with_metadata(self, response: omnichannelsettings.RequestInventoryVerificationResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for request_inventory_verification - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OmnichannelSettingsService server but before it is returned to user code. - - We recommend only using this `post_request_inventory_verification_with_metadata` - interceptor in new development instead of the `post_request_inventory_verification` interceptor. - When both interceptors are used, this `post_request_inventory_verification_with_metadata` interceptor runs after the - `post_request_inventory_verification` interceptor. The (possibly modified) response returned by - `post_request_inventory_verification` will be passed to - `post_request_inventory_verification_with_metadata`. - """ - return response, metadata - - def pre_update_omnichannel_setting(self, request: omnichannelsettings.UpdateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.UpdateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_omnichannel_setting - - Override in a subclass to manipulate the request or metadata - before they are sent to the OmnichannelSettingsService server. - """ - return request, metadata - - def post_update_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: - """Post-rpc interceptor for update_omnichannel_setting - - DEPRECATED. Please use the `post_update_omnichannel_setting_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OmnichannelSettingsService server but before - it is returned to user code. This `post_update_omnichannel_setting` interceptor runs - before the `post_update_omnichannel_setting_with_metadata` interceptor. - """ - return response - - def post_update_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_omnichannel_setting - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OmnichannelSettingsService server but before it is returned to user code. - - We recommend only using this `post_update_omnichannel_setting_with_metadata` - interceptor in new development instead of the `post_update_omnichannel_setting` interceptor. - When both interceptors are used, this `post_update_omnichannel_setting_with_metadata` interceptor runs after the - `post_update_omnichannel_setting` interceptor. The (possibly modified) response returned by - `post_update_omnichannel_setting` will be passed to - `post_update_omnichannel_setting_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class OmnichannelSettingsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: OmnichannelSettingsServiceRestInterceptor - - -class OmnichannelSettingsServiceRestTransport(_BaseOmnichannelSettingsServiceRestTransport): - """REST backend synchronous transport for OmnichannelSettingsService. - - The service facilitates the management of a merchant's omnichannel - settings. - - This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] - - 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[OmnichannelSettingsServiceRestInterceptor] = 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 OmnichannelSettingsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting, OmnichannelSettingsServiceRestStub): - def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.CreateOmnichannelSetting") - - @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: omnichannelsettings.CreateOmnichannelSettingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Call the create omnichannel - setting method over HTTP. - - Args: - request (~.omnichannelsettings.CreateOmnichannelSettingRequest): - The request object. Request message for the - CreateOmnichannelSetting 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: - ~.omnichannelsettings.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_http_options() - - request, metadata = self._interceptor.pre_create_omnichannel_setting(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_transcoded_request(http_options, request) - - body = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.CreateOmnichannelSetting", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "CreateOmnichannelSetting", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OmnichannelSettingsServiceRestTransport._CreateOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() - pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_omnichannel_setting(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_omnichannel_setting_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1beta.OmnichannelSettingsServiceClient.create_omnichannel_setting", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "CreateOmnichannelSetting", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting, OmnichannelSettingsServiceRestStub): - def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.GetOmnichannelSetting") - - @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: omnichannelsettings.GetOmnichannelSettingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Call the get omnichannel setting method over HTTP. - - Args: - request (~.omnichannelsettings.GetOmnichannelSettingRequest): - The request object. Request message for the - GetOmnichannelSettings 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: - ~.omnichannelsettings.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_http_options() - - request, metadata = self._interceptor.pre_get_omnichannel_setting(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.GetOmnichannelSetting", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "GetOmnichannelSetting", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OmnichannelSettingsServiceRestTransport._GetOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() - pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_omnichannel_setting(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_omnichannel_setting_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1beta.OmnichannelSettingsServiceClient.get_omnichannel_setting", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "GetOmnichannelSetting", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListOmnichannelSettings(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings, OmnichannelSettingsServiceRestStub): - def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.ListOmnichannelSettings") - - @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: omnichannelsettings.ListOmnichannelSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.ListOmnichannelSettingsResponse: - r"""Call the list omnichannel settings method over HTTP. - - Args: - request (~.omnichannelsettings.ListOmnichannelSettingsRequest): - The request object. Request message for the - ListOmnichannelSettings 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: - ~.omnichannelsettings.ListOmnichannelSettingsResponse: - Response message for the - ListOmnichannelSettings method. - - """ - - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_http_options() - - request, metadata = self._interceptor.pre_list_omnichannel_settings(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.ListOmnichannelSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "ListOmnichannelSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OmnichannelSettingsServiceRestTransport._ListOmnichannelSettings._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 = omnichannelsettings.ListOmnichannelSettingsResponse() - pb_resp = omnichannelsettings.ListOmnichannelSettingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_omnichannel_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_omnichannel_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = omnichannelsettings.ListOmnichannelSettingsResponse.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.accounts_v1beta.OmnichannelSettingsServiceClient.list_omnichannel_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "ListOmnichannelSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _RequestInventoryVerification(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification, OmnichannelSettingsServiceRestStub): - def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.RequestInventoryVerification") - - @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: omnichannelsettings.RequestInventoryVerificationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.RequestInventoryVerificationResponse: - r"""Call the request inventory - verification method over HTTP. - - Args: - request (~.omnichannelsettings.RequestInventoryVerificationRequest): - The request object. Request message for the - RequestInventoryVerification 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: - ~.omnichannelsettings.RequestInventoryVerificationResponse: - Response message for the - RequestInventoryVerification method. - - """ - - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_http_options() - - request, metadata = self._interceptor.pre_request_inventory_verification(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_transcoded_request(http_options, request) - - body = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.RequestInventoryVerification", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "RequestInventoryVerification", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OmnichannelSettingsServiceRestTransport._RequestInventoryVerification._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 = omnichannelsettings.RequestInventoryVerificationResponse() - pb_resp = omnichannelsettings.RequestInventoryVerificationResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_request_inventory_verification(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_request_inventory_verification_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = omnichannelsettings.RequestInventoryVerificationResponse.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.accounts_v1beta.OmnichannelSettingsServiceClient.request_inventory_verification", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "RequestInventoryVerification", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting, OmnichannelSettingsServiceRestStub): - def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.UpdateOmnichannelSetting") - - @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: omnichannelsettings.UpdateOmnichannelSettingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.OmnichannelSetting: - r"""Call the update omnichannel - setting method over HTTP. - - Args: - request (~.omnichannelsettings.UpdateOmnichannelSettingRequest): - The request object. Request message for the - UpdateOmnichannelSetting 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: - ~.omnichannelsettings.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. - - """ - - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_http_options() - - request, metadata = self._interceptor.pre_update_omnichannel_setting(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_transcoded_request(http_options, request) - - body = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OmnichannelSettingsServiceClient.UpdateOmnichannelSetting", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "UpdateOmnichannelSetting", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OmnichannelSettingsServiceRestTransport._UpdateOmnichannelSetting._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 = omnichannelsettings.OmnichannelSetting() - pb_resp = omnichannelsettings.OmnichannelSetting.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_omnichannel_setting(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_omnichannel_setting_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1beta.OmnichannelSettingsServiceClient.update_omnichannel_setting", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "rpcName": "UpdateOmnichannelSetting", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: - # 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._CreateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: - # 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._GetOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - omnichannelsettings.ListOmnichannelSettingsResponse]: - # 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._ListOmnichannelSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - omnichannelsettings.RequestInventoryVerificationResponse]: - # 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._RequestInventoryVerification(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: - # 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._UpdateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'OmnichannelSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py deleted file mode 100644 index b726584914c0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/omnichannel_settings_service/transports/rest_base.py +++ /dev/null @@ -1,306 +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 OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings - - -class _BaseOmnichannelSettingsServiceRestTransport(OmnichannelSettingsServiceTransport): - """Base REST backend transport for OmnichannelSettingsService. - - 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 _BaseCreateOmnichannelSetting: - 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': '/accounts/v1beta/{parent=accounts/*}/omnichannelSettings', - 'body': 'omnichannel_setting', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = omnichannelsettings.CreateOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOmnichannelSetting: - 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': '/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = omnichannelsettings.GetOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListOmnichannelSettings: - 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': '/accounts/v1beta/{parent=accounts/*}/omnichannelSettings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = omnichannelsettings.ListOmnichannelSettingsRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRequestInventoryVerification: - 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': '/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = omnichannelsettings.RequestInventoryVerificationRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateOmnichannelSetting: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}', - 'body': 'omnichannel_setting', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = omnichannelsettings.UpdateOmnichannelSettingRequest.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(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseOmnichannelSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/__init__.py deleted file mode 100644 index 856118f59e37..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_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 OnlineReturnPolicyServiceClient -from .async_client import OnlineReturnPolicyServiceAsyncClient - -__all__ = ( - 'OnlineReturnPolicyServiceClient', - 'OnlineReturnPolicyServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py deleted file mode 100644 index 84414ea78901..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/async_client.py +++ /dev/null @@ -1,860 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import pagers -from google.shopping.merchant_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy -from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport -from .client import OnlineReturnPolicyServiceClient - -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 OnlineReturnPolicyServiceAsyncClient: - """The service facilitates the management of a merchant's remorse - return policy configuration, encompassing return policies for both - ads and free listings - - programs. This API defines the following resource model: - -------------------------------------------------------- - - `OnlineReturnPolicy `__ - """ - - _client: OnlineReturnPolicyServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - - online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.online_return_policy_path) - parse_online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.parse_online_return_policy_path) - common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OnlineReturnPolicyServiceClient.common_project_path) - parse_common_project_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_project_path) - common_location_path = staticmethod(OnlineReturnPolicyServiceClient.common_location_path) - parse_common_location_path = staticmethod(OnlineReturnPolicyServiceClient.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: - OnlineReturnPolicyServiceAsyncClient: The constructed client. - """ - return OnlineReturnPolicyServiceClient.from_service_account_info.__func__(OnlineReturnPolicyServiceAsyncClient, 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: - OnlineReturnPolicyServiceAsyncClient: The constructed client. - """ - return OnlineReturnPolicyServiceClient.from_service_account_file.__func__(OnlineReturnPolicyServiceAsyncClient, 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 OnlineReturnPolicyServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> OnlineReturnPolicyServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OnlineReturnPolicyServiceTransport: 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 = OnlineReturnPolicyServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the online return policy 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,OnlineReturnPolicyServiceTransport,Callable[..., OnlineReturnPolicyServiceTransport]]]): - 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 OnlineReturnPolicyServiceTransport 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 = OnlineReturnPolicyServiceClient( - 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.accounts_v1beta.OnlineReturnPolicyServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "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.accounts.v1beta.OnlineReturnPolicyService", - "credentialsType": None, - } - ) - - async def get_online_return_policy(self, - request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> online_return_policy.OnlineReturnPolicy: - r"""Gets an existing return policy for a given merchant. - - .. 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_accounts_v1beta - - async def sample_get_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_online_return_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest, dict]]): - The request object. Request message for the ``GetOnlineReturnPolicy`` - method. - name (:class:`str`): - Required. The name of the return policy to retrieve. - Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy: - [Online return policy](\ https://support.google.com/merchants/answer/10220642) - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - # 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, online_return_policy.GetOnlineReturnPolicyRequest): - request = online_return_policy.GetOnlineReturnPolicyRequest(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.get_online_return_policy] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_online_return_policies(self, - request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesAsyncPager: - r"""Lists all existing return policies for a given - merchant. - - .. 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_accounts_v1beta - - async def sample_list_online_return_policies(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_online_return_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest, dict]]): - The request object. Request message for the ``ListOnlineReturnPolicies`` - method. - parent (:class:`str`): - Required. The merchant account for which to list return - policies. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager: - Response message for the ListOnlineReturnPolicies - 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, online_return_policy.ListOnlineReturnPoliciesRequest): - request = online_return_policy.ListOnlineReturnPoliciesRequest(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_online_return_policies] - - # 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.ListOnlineReturnPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_online_return_policy(self, - request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_online_return_policy.OnlineReturnPolicy: - r"""Creates a new return policy for a given merchant. - - .. 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_accounts_v1beta - - async def sample_create_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( - parent="parent_value", - online_return_policy=online_return_policy, - ) - - # Make the request - response = await client.create_online_return_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest, dict]]): - The request object. Request message for the ``CreateOnlineReturnPolicy`` - method. - parent (:class:`str`): - Required. The merchant account for which the return - policy will be created. Format: ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - online_return_policy (:class:`google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy`): - Required. The return policy object to - create. - - This corresponds to the ``online_return_policy`` 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_accounts_v1beta.types.OnlineReturnPolicy: - [Online return policy](\ https://support.google.com/merchants/answer/10220642) - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - # 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, online_return_policy] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if online_return_policy is not None: - request.online_return_policy = online_return_policy - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_online_return_policy] - - # 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 update_online_return_policy(self, - request: Optional[Union[gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, dict]] = None, - *, - online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_online_return_policy.OnlineReturnPolicy: - r"""Updates an existing return policy for a given - merchant. - - .. 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_accounts_v1beta - - async def sample_update_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( - online_return_policy=online_return_policy, - ) - - # Make the request - response = await client.update_online_return_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest, dict]]): - The request object. Request message for the ``UpdateOnlineReturnPolicy`` - method. The method supports field masks and when the - mask is provided, only the fields specified in the mask - are updated. - online_return_policy (:class:`google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy`): - Required. The online return policy to update. The online - return policy's ``name`` field is used to identify the - online return policy to be updated. - - This corresponds to the ``online_return_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. List of fields being updated. - - The following fields are supported (in both - ``snake_case`` and ``lowerCamelCase``): - - - ``accept_defective_only`` - - ``accept_exchange`` - - ``item_conditions`` - - ``policy`` - - ``process_refund_days`` - - ``restocking_fee`` - - ``return_methods`` - - ``return_policy_uri`` - - ``return_shipping_fee`` - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OnlineReturnPolicy: - [Online return policy](\ https://support.google.com/merchants/answer/10220642) - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - # 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 = [online_return_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): - request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if online_return_policy is not None: - request.online_return_policy = online_return_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_online_return_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("online_return_policy.name", request.online_return_policy.name), - )), - ) - - # 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_online_return_policy(self, - request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, - *, - name: 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 an existing return policy. - - .. 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_accounts_v1beta - - async def sample_delete_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - await client.delete_online_return_policy(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest, dict]]): - The request object. Request message for the ``DeleteOnlineReturnPolicy`` - method. - name (:class:`str`): - Required. The name of the return policy to delete. - Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - - 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, online_return_policy.DeleteOnlineReturnPolicyRequest): - request = online_return_policy.DeleteOnlineReturnPolicyRequest(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_online_return_policy] - - # 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) -> "OnlineReturnPolicyServiceAsyncClient": - 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__ = ( - "OnlineReturnPolicyServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py deleted file mode 100644 index eef815896c83..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/client.py +++ /dev/null @@ -1,1216 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import pagers -from google.shopping.merchant_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy -from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import OnlineReturnPolicyServiceGrpcTransport -from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport -from .transports.rest import OnlineReturnPolicyServiceRestTransport - - -class OnlineReturnPolicyServiceClientMeta(type): - """Metaclass for the OnlineReturnPolicyService 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[OnlineReturnPolicyServiceTransport]] - _transport_registry["grpc"] = OnlineReturnPolicyServiceGrpcTransport - _transport_registry["grpc_asyncio"] = OnlineReturnPolicyServiceGrpcAsyncIOTransport - _transport_registry["rest"] = OnlineReturnPolicyServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[OnlineReturnPolicyServiceTransport]: - """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 OnlineReturnPolicyServiceClient(metaclass=OnlineReturnPolicyServiceClientMeta): - """The service facilitates the management of a merchant's remorse - return policy configuration, encompassing return policies for both - ads and free listings - - programs. This API defines the following resource model: - -------------------------------------------------------- - - `OnlineReturnPolicy `__ - """ - - @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: - OnlineReturnPolicyServiceClient: 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: - OnlineReturnPolicyServiceClient: 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) -> OnlineReturnPolicyServiceTransport: - """Returns the transport used by the client instance. - - Returns: - OnlineReturnPolicyServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def online_return_policy_path(account: str,return_policy: str,) -> str: - """Returns a fully-qualified online_return_policy string.""" - return "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) - - @staticmethod - def parse_online_return_policy_path(path: str) -> Dict[str,str]: - """Parses a online_return_policy path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/onlineReturnPolicies/(?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 = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient._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, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the online return policy 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,OnlineReturnPolicyServiceTransport,Callable[..., OnlineReturnPolicyServiceTransport]]]): - 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 OnlineReturnPolicyServiceTransport 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 = OnlineReturnPolicyServiceClient._read_environment_variables() - self._client_cert_source = OnlineReturnPolicyServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = OnlineReturnPolicyServiceClient._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, OnlineReturnPolicyServiceTransport) - if transport_provided: - # transport is a OnlineReturnPolicyServiceTransport 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(OnlineReturnPolicyServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - OnlineReturnPolicyServiceClient._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[OnlineReturnPolicyServiceTransport], Callable[..., OnlineReturnPolicyServiceTransport]] = ( - OnlineReturnPolicyServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., OnlineReturnPolicyServiceTransport], 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.accounts_v1beta.OnlineReturnPolicyServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "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.accounts.v1beta.OnlineReturnPolicyService", - "credentialsType": None, - } - ) - - def get_online_return_policy(self, - request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> online_return_policy.OnlineReturnPolicy: - r"""Gets an existing return policy for a given merchant. - - .. 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_accounts_v1beta - - def sample_get_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_online_return_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest, dict]): - The request object. Request message for the ``GetOnlineReturnPolicy`` - method. - name (str): - Required. The name of the return policy to retrieve. - Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy: - [Online return policy](\ https://support.google.com/merchants/answer/10220642) - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - # 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, online_return_policy.GetOnlineReturnPolicyRequest): - request = online_return_policy.GetOnlineReturnPolicyRequest(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.get_online_return_policy] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_online_return_policies(self, - request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesPager: - r"""Lists all existing return policies for a given - merchant. - - .. 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_accounts_v1beta - - def sample_list_online_return_policies(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_online_return_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest, dict]): - The request object. Request message for the ``ListOnlineReturnPolicies`` - method. - parent (str): - Required. The merchant account for which to list return - policies. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager: - Response message for the ListOnlineReturnPolicies - 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, online_return_policy.ListOnlineReturnPoliciesRequest): - request = online_return_policy.ListOnlineReturnPoliciesRequest(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_online_return_policies] - - # 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.ListOnlineReturnPoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_online_return_policy(self, - request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_online_return_policy.OnlineReturnPolicy: - r"""Creates a new return policy for a given merchant. - - .. 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_accounts_v1beta - - def sample_create_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( - parent="parent_value", - online_return_policy=online_return_policy, - ) - - # Make the request - response = client.create_online_return_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest, dict]): - The request object. Request message for the ``CreateOnlineReturnPolicy`` - method. - parent (str): - Required. The merchant account for which the return - policy will be created. Format: ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): - Required. The return policy object to - create. - - This corresponds to the ``online_return_policy`` 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_accounts_v1beta.types.OnlineReturnPolicy: - [Online return policy](\ https://support.google.com/merchants/answer/10220642) - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - # 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, online_return_policy] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if online_return_policy is not None: - request.online_return_policy = online_return_policy - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_online_return_policy] - - # 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 update_online_return_policy(self, - request: Optional[Union[gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, dict]] = None, - *, - online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_online_return_policy.OnlineReturnPolicy: - r"""Updates an existing return policy for a given - merchant. - - .. 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_accounts_v1beta - - def sample_update_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( - online_return_policy=online_return_policy, - ) - - # Make the request - response = client.update_online_return_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest, dict]): - The request object. Request message for the ``UpdateOnlineReturnPolicy`` - method. The method supports field masks and when the - mask is provided, only the fields specified in the mask - are updated. - online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): - Required. The online return policy to update. The online - return policy's ``name`` field is used to identify the - online return policy to be updated. - - This corresponds to the ``online_return_policy`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. List of fields being updated. - - The following fields are supported (in both - ``snake_case`` and ``lowerCamelCase``): - - - ``accept_defective_only`` - - ``accept_exchange`` - - ``item_conditions`` - - ``policy`` - - ``process_refund_days`` - - ``restocking_fee`` - - ``return_methods`` - - ``return_policy_uri`` - - ``return_shipping_fee`` - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.OnlineReturnPolicy: - [Online return policy](\ https://support.google.com/merchants/answer/10220642) - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - # 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 = [online_return_policy, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): - request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if online_return_policy is not None: - request.online_return_policy = online_return_policy - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_online_return_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("online_return_policy.name", request.online_return_policy.name), - )), - ) - - # 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_online_return_policy(self, - request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, - *, - name: 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 an existing return policy. - - .. 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_accounts_v1beta - - def sample_delete_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - client.delete_online_return_policy(request=request) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest, dict]): - The request object. Request message for the ``DeleteOnlineReturnPolicy`` - method. - name (str): - Required. The name of the return policy to delete. - Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - - 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, online_return_policy.DeleteOnlineReturnPolicyRequest): - request = online_return_policy.DeleteOnlineReturnPolicyRequest(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_online_return_policy] - - # 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) -> "OnlineReturnPolicyServiceClient": - 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__ = ( - "OnlineReturnPolicyServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/pagers.py deleted file mode 100644 index 2d550a648397..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_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_accounts_v1beta.types import online_return_policy - - -class ListOnlineReturnPoliciesPager: - """A pager for iterating through ``list_online_return_policies`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``online_return_policies`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListOnlineReturnPolicies`` requests and continue to iterate - through the ``online_return_policies`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` - 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[..., online_return_policy.ListOnlineReturnPoliciesResponse], - request: online_return_policy.ListOnlineReturnPoliciesRequest, - response: online_return_policy.ListOnlineReturnPoliciesResponse, - *, - 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_accounts_v1beta.types.ListOnlineReturnPoliciesRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse): - 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 = online_return_policy.ListOnlineReturnPoliciesRequest(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[online_return_policy.ListOnlineReturnPoliciesResponse]: - 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[online_return_policy.OnlineReturnPolicy]: - for page in self.pages: - yield from page.online_return_policies - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListOnlineReturnPoliciesAsyncPager: - """A pager for iterating through ``list_online_return_policies`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``online_return_policies`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListOnlineReturnPolicies`` requests and continue to iterate - through the ``online_return_policies`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse` - 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[online_return_policy.ListOnlineReturnPoliciesResponse]], - request: online_return_policy.ListOnlineReturnPoliciesRequest, - response: online_return_policy.ListOnlineReturnPoliciesResponse, - *, - 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_accounts_v1beta.types.ListOnlineReturnPoliciesRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesResponse): - 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 = online_return_policy.ListOnlineReturnPoliciesRequest(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[online_return_policy.ListOnlineReturnPoliciesResponse]: - 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[online_return_policy.OnlineReturnPolicy]: - async def async_generator(): - async for page in self.pages: - for response in page.online_return_policies: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst deleted file mode 100644 index a6e34721a621..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`OnlineReturnPolicyServiceTransport` is the ABC for all transports. -- public child `OnlineReturnPolicyServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `OnlineReturnPolicyServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseOnlineReturnPolicyServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `OnlineReturnPolicyServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/__init__.py deleted file mode 100644 index 406ed1cc95a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_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 OnlineReturnPolicyServiceTransport -from .grpc import OnlineReturnPolicyServiceGrpcTransport -from .grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport -from .rest import OnlineReturnPolicyServiceRestTransport -from .rest import OnlineReturnPolicyServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] -_transport_registry['grpc'] = OnlineReturnPolicyServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OnlineReturnPolicyServiceGrpcAsyncIOTransport -_transport_registry['rest'] = OnlineReturnPolicyServiceRestTransport - -__all__ = ( - 'OnlineReturnPolicyServiceTransport', - 'OnlineReturnPolicyServiceGrpcTransport', - 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', - 'OnlineReturnPolicyServiceRestTransport', - 'OnlineReturnPolicyServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py deleted file mode 100644 index 8e455d20465e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/base.py +++ /dev/null @@ -1,217 +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_accounts_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_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy - -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 OnlineReturnPolicyServiceTransport(abc.ABC): - """Abstract transport class for OnlineReturnPolicyService.""" - - 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.get_online_return_policy: gapic_v1.method.wrap_method( - self.get_online_return_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_online_return_policies: gapic_v1.method.wrap_method( - self.list_online_return_policies, - default_timeout=None, - client_info=client_info, - ), - self.create_online_return_policy: gapic_v1.method.wrap_method( - self.create_online_return_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_online_return_policy: gapic_v1.method.wrap_method( - self.update_online_return_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_online_return_policy: gapic_v1.method.wrap_method( - self.delete_online_return_policy, - 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 get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - Union[ - online_return_policy.OnlineReturnPolicy, - Awaitable[online_return_policy.OnlineReturnPolicy] - ]]: - raise NotImplementedError() - - @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - Union[ - online_return_policy.ListOnlineReturnPoliciesResponse, - Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - Union[ - gsma_online_return_policy.OnlineReturnPolicy, - Awaitable[gsma_online_return_policy.OnlineReturnPolicy] - ]]: - raise NotImplementedError() - - @property - def update_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], - Union[ - gsma_online_return_policy.OnlineReturnPolicy, - Awaitable[gsma_online_return_policy.OnlineReturnPolicy] - ]]: - raise NotImplementedError() - - @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'OnlineReturnPolicyServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py deleted file mode 100644 index dbfb87c664c8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc.py +++ /dev/null @@ -1,461 +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_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy -from .base import OnlineReturnPolicyServiceTransport, 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.accounts.v1beta.OnlineReturnPolicyService", - "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.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class OnlineReturnPolicyServiceGrpcTransport(OnlineReturnPolicyServiceTransport): - """gRPC backend transport for OnlineReturnPolicyService. - - The service facilitates the management of a merchant's remorse - return policy configuration, encompassing return policies for both - ads and free listings - - programs. This API defines the following resource model: - -------------------------------------------------------- - - `OnlineReturnPolicy `__ - - 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 get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - online_return_policy.OnlineReturnPolicy]: - r"""Return a callable for the get online return policy method over gRPC. - - Gets an existing return policy for a given merchant. - - Returns: - Callable[[~.GetOnlineReturnPolicyRequest], - ~.OnlineReturnPolicy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_online_return_policy' not in self._stubs: - self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/GetOnlineReturnPolicy', - request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, - response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, - ) - return self._stubs['get_online_return_policy'] - - @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - online_return_policy.ListOnlineReturnPoliciesResponse]: - r"""Return a callable for the list online return policies method over gRPC. - - Lists all existing return policies for a given - merchant. - - Returns: - Callable[[~.ListOnlineReturnPoliciesRequest], - ~.ListOnlineReturnPoliciesResponse]: - 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_online_return_policies' not in self._stubs: - self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/ListOnlineReturnPolicies', - request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, - response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, - ) - return self._stubs['list_online_return_policies'] - - @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - gsma_online_return_policy.OnlineReturnPolicy]: - r"""Return a callable for the create online return policy method over gRPC. - - Creates a new return policy for a given merchant. - - Returns: - Callable[[~.CreateOnlineReturnPolicyRequest], - ~.OnlineReturnPolicy]: - 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 'create_online_return_policy' not in self._stubs: - self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/CreateOnlineReturnPolicy', - request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, - response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, - ) - return self._stubs['create_online_return_policy'] - - @property - def update_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], - gsma_online_return_policy.OnlineReturnPolicy]: - r"""Return a callable for the update online return policy method over gRPC. - - Updates an existing return policy for a given - merchant. - - Returns: - Callable[[~.UpdateOnlineReturnPolicyRequest], - ~.OnlineReturnPolicy]: - 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 'update_online_return_policy' not in self._stubs: - self._stubs['update_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/UpdateOnlineReturnPolicy', - request_serializer=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.serialize, - response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, - ) - return self._stubs['update_online_return_policy'] - - @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete online return policy method over gRPC. - - Deletes an existing return policy. - - Returns: - Callable[[~.DeleteOnlineReturnPolicyRequest], - ~.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_online_return_policy' not in self._stubs: - self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', - request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_online_return_policy'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'OnlineReturnPolicyServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py deleted file mode 100644 index f22ed6845d38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,502 +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_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy -from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import OnlineReturnPolicyServiceGrpcTransport - -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.accounts.v1beta.OnlineReturnPolicyService", - "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.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class OnlineReturnPolicyServiceGrpcAsyncIOTransport(OnlineReturnPolicyServiceTransport): - """gRPC AsyncIO backend transport for OnlineReturnPolicyService. - - The service facilitates the management of a merchant's remorse - return policy configuration, encompassing return policies for both - ads and free listings - - programs. This API defines the following resource model: - -------------------------------------------------------- - - `OnlineReturnPolicy `__ - - 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 get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - Awaitable[online_return_policy.OnlineReturnPolicy]]: - r"""Return a callable for the get online return policy method over gRPC. - - Gets an existing return policy for a given merchant. - - Returns: - Callable[[~.GetOnlineReturnPolicyRequest], - Awaitable[~.OnlineReturnPolicy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_online_return_policy' not in self._stubs: - self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/GetOnlineReturnPolicy', - request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, - response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, - ) - return self._stubs['get_online_return_policy'] - - @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse]]: - r"""Return a callable for the list online return policies method over gRPC. - - Lists all existing return policies for a given - merchant. - - Returns: - Callable[[~.ListOnlineReturnPoliciesRequest], - Awaitable[~.ListOnlineReturnPoliciesResponse]]: - 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_online_return_policies' not in self._stubs: - self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/ListOnlineReturnPolicies', - request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, - response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, - ) - return self._stubs['list_online_return_policies'] - - @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - Awaitable[gsma_online_return_policy.OnlineReturnPolicy]]: - r"""Return a callable for the create online return policy method over gRPC. - - Creates a new return policy for a given merchant. - - Returns: - Callable[[~.CreateOnlineReturnPolicyRequest], - Awaitable[~.OnlineReturnPolicy]]: - 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 'create_online_return_policy' not in self._stubs: - self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/CreateOnlineReturnPolicy', - request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, - response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, - ) - return self._stubs['create_online_return_policy'] - - @property - def update_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], - Awaitable[gsma_online_return_policy.OnlineReturnPolicy]]: - r"""Return a callable for the update online return policy method over gRPC. - - Updates an existing return policy for a given - merchant. - - Returns: - Callable[[~.UpdateOnlineReturnPolicyRequest], - Awaitable[~.OnlineReturnPolicy]]: - 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 'update_online_return_policy' not in self._stubs: - self._stubs['update_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/UpdateOnlineReturnPolicy', - request_serializer=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.serialize, - response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, - ) - return self._stubs['update_online_return_policy'] - - @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete online return policy method over gRPC. - - Deletes an existing return policy. - - Returns: - Callable[[~.DeleteOnlineReturnPolicyRequest], - 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_online_return_policy' not in self._stubs: - self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', - request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_online_return_policy'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_online_return_policy: self._wrap_method( - self.get_online_return_policy, - default_timeout=None, - client_info=client_info, - ), - self.list_online_return_policies: self._wrap_method( - self.list_online_return_policies, - default_timeout=None, - client_info=client_info, - ), - self.create_online_return_policy: self._wrap_method( - self.create_online_return_policy, - default_timeout=None, - client_info=client_info, - ), - self.update_online_return_policy: self._wrap_method( - self.update_online_return_policy, - default_timeout=None, - client_info=client_info, - ), - self.delete_online_return_policy: self._wrap_method( - self.delete_online_return_policy, - 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__ = ( - 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py deleted file mode 100644 index e8dd549853b8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest.py +++ /dev/null @@ -1,1009 +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_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy - - -from .rest_base import _BaseOnlineReturnPolicyServiceRestTransport -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 OnlineReturnPolicyServiceRestInterceptor: - """Interceptor for OnlineReturnPolicyService. - - 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 OnlineReturnPolicyServiceRestTransport. - - .. code-block:: python - class MyCustomOnlineReturnPolicyServiceInterceptor(OnlineReturnPolicyServiceRestInterceptor): - def pre_create_online_return_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_online_return_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_online_return_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_online_return_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_online_return_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_online_return_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_online_return_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_online_return_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_online_return_policy(self, response): - logging.log(f"Received response: {response}") - return response - - transport = OnlineReturnPolicyServiceRestTransport(interceptor=MyCustomOnlineReturnPolicyServiceInterceptor()) - client = OnlineReturnPolicyServiceClient(transport=transport) - - - """ - def pre_create_online_return_policy(self, request: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_online_return_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the OnlineReturnPolicyService server. - """ - return request, metadata - - def post_create_online_return_policy(self, response: gsma_online_return_policy.OnlineReturnPolicy) -> gsma_online_return_policy.OnlineReturnPolicy: - """Post-rpc interceptor for create_online_return_policy - - DEPRECATED. Please use the `post_create_online_return_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OnlineReturnPolicyService server but before - it is returned to user code. This `post_create_online_return_policy` interceptor runs - before the `post_create_online_return_policy_with_metadata` interceptor. - """ - return response - - def post_create_online_return_policy_with_metadata(self, response: gsma_online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_online_return_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OnlineReturnPolicyService server but before it is returned to user code. - - We recommend only using this `post_create_online_return_policy_with_metadata` - interceptor in new development instead of the `post_create_online_return_policy` interceptor. - When both interceptors are used, this `post_create_online_return_policy_with_metadata` interceptor runs after the - `post_create_online_return_policy` interceptor. The (possibly modified) response returned by - `post_create_online_return_policy` will be passed to - `post_create_online_return_policy_with_metadata`. - """ - return response, metadata - - def pre_delete_online_return_policy(self, request: online_return_policy.DeleteOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.DeleteOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_online_return_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the OnlineReturnPolicyService server. - """ - return request, metadata - - def pre_get_online_return_policy(self, request: online_return_policy.GetOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_online_return_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the OnlineReturnPolicyService server. - """ - return request, metadata - - def post_get_online_return_policy(self, response: online_return_policy.OnlineReturnPolicy) -> online_return_policy.OnlineReturnPolicy: - """Post-rpc interceptor for get_online_return_policy - - DEPRECATED. Please use the `post_get_online_return_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OnlineReturnPolicyService server but before - it is returned to user code. This `post_get_online_return_policy` interceptor runs - before the `post_get_online_return_policy_with_metadata` interceptor. - """ - return response - - def post_get_online_return_policy_with_metadata(self, response: online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_online_return_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OnlineReturnPolicyService server but before it is returned to user code. - - We recommend only using this `post_get_online_return_policy_with_metadata` - interceptor in new development instead of the `post_get_online_return_policy` interceptor. - When both interceptors are used, this `post_get_online_return_policy_with_metadata` interceptor runs after the - `post_get_online_return_policy` interceptor. The (possibly modified) response returned by - `post_get_online_return_policy` will be passed to - `post_get_online_return_policy_with_metadata`. - """ - return response, metadata - - def pre_list_online_return_policies(self, request: online_return_policy.ListOnlineReturnPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_online_return_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the OnlineReturnPolicyService server. - """ - return request, metadata - - def post_list_online_return_policies(self, response: online_return_policy.ListOnlineReturnPoliciesResponse) -> online_return_policy.ListOnlineReturnPoliciesResponse: - """Post-rpc interceptor for list_online_return_policies - - DEPRECATED. Please use the `post_list_online_return_policies_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OnlineReturnPolicyService server but before - it is returned to user code. This `post_list_online_return_policies` interceptor runs - before the `post_list_online_return_policies_with_metadata` interceptor. - """ - return response - - def post_list_online_return_policies_with_metadata(self, response: online_return_policy.ListOnlineReturnPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_online_return_policies - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OnlineReturnPolicyService server but before it is returned to user code. - - We recommend only using this `post_list_online_return_policies_with_metadata` - interceptor in new development instead of the `post_list_online_return_policies` interceptor. - When both interceptors are used, this `post_list_online_return_policies_with_metadata` interceptor runs after the - `post_list_online_return_policies` interceptor. The (possibly modified) response returned by - `post_list_online_return_policies` will be passed to - `post_list_online_return_policies_with_metadata`. - """ - return response, metadata - - def pre_update_online_return_policy(self, request: gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_online_return_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the OnlineReturnPolicyService server. - """ - return request, metadata - - def post_update_online_return_policy(self, response: gsma_online_return_policy.OnlineReturnPolicy) -> gsma_online_return_policy.OnlineReturnPolicy: - """Post-rpc interceptor for update_online_return_policy - - DEPRECATED. Please use the `post_update_online_return_policy_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the OnlineReturnPolicyService server but before - it is returned to user code. This `post_update_online_return_policy` interceptor runs - before the `post_update_online_return_policy_with_metadata` interceptor. - """ - return response - - def post_update_online_return_policy_with_metadata(self, response: gsma_online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_online_return_policy - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the OnlineReturnPolicyService server but before it is returned to user code. - - We recommend only using this `post_update_online_return_policy_with_metadata` - interceptor in new development instead of the `post_update_online_return_policy` interceptor. - When both interceptors are used, this `post_update_online_return_policy_with_metadata` interceptor runs after the - `post_update_online_return_policy` interceptor. The (possibly modified) response returned by - `post_update_online_return_policy` will be passed to - `post_update_online_return_policy_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class OnlineReturnPolicyServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: OnlineReturnPolicyServiceRestInterceptor - - -class OnlineReturnPolicyServiceRestTransport(_BaseOnlineReturnPolicyServiceRestTransport): - """REST backend synchronous transport for OnlineReturnPolicyService. - - The service facilitates the management of a merchant's remorse - return policy configuration, encompassing return policies for both - ads and free listings - - programs. This API defines the following resource model: - -------------------------------------------------------- - - `OnlineReturnPolicy `__ - - 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[OnlineReturnPolicyServiceRestInterceptor] = 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 OnlineReturnPolicyServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): - def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.CreateOnlineReturnPolicy") - - @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: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_online_return_policy.OnlineReturnPolicy: - r"""Call the create online return - policy method over HTTP. - - Args: - request (~.gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - The request object. Request message for the ``CreateOnlineReturnPolicy`` - 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: - ~.gsma_online_return_policy.OnlineReturnPolicy: - `Online return - policy `__ - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_http_options() - - request, metadata = self._interceptor.pre_create_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_transcoded_request(http_options, request) - - body = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.CreateOnlineReturnPolicy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "CreateOnlineReturnPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OnlineReturnPolicyServiceRestTransport._CreateOnlineReturnPolicy._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 = gsma_online_return_policy.OnlineReturnPolicy() - pb_resp = gsma_online_return_policy.OnlineReturnPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_online_return_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_online_return_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gsma_online_return_policy.OnlineReturnPolicy.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.accounts_v1beta.OnlineReturnPolicyServiceClient.create_online_return_policy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "CreateOnlineReturnPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): - def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.DeleteOnlineReturnPolicy") - - @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: online_return_policy.DeleteOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete online return - policy method over HTTP. - - Args: - request (~.online_return_policy.DeleteOnlineReturnPolicyRequest): - The request object. Request message for the ``DeleteOnlineReturnPolicy`` - 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_http_options() - - request, metadata = self._interceptor.pre_delete_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.DeleteOnlineReturnPolicy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "DeleteOnlineReturnPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OnlineReturnPolicyServiceRestTransport._DeleteOnlineReturnPolicy._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 _GetOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): - def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.GetOnlineReturnPolicy") - - @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: online_return_policy.GetOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> online_return_policy.OnlineReturnPolicy: - r"""Call the get online return policy method over HTTP. - - Args: - request (~.online_return_policy.GetOnlineReturnPolicyRequest): - The request object. Request message for the ``GetOnlineReturnPolicy`` - 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: - ~.online_return_policy.OnlineReturnPolicy: - `Online return - policy `__ - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.GetOnlineReturnPolicy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "GetOnlineReturnPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OnlineReturnPolicyServiceRestTransport._GetOnlineReturnPolicy._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 = online_return_policy.OnlineReturnPolicy() - pb_resp = online_return_policy.OnlineReturnPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_online_return_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_online_return_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = online_return_policy.OnlineReturnPolicy.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.accounts_v1beta.OnlineReturnPolicyServiceClient.get_online_return_policy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "GetOnlineReturnPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListOnlineReturnPolicies(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies, OnlineReturnPolicyServiceRestStub): - def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.ListOnlineReturnPolicies") - - @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: online_return_policy.ListOnlineReturnPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> online_return_policy.ListOnlineReturnPoliciesResponse: - r"""Call the list online return - policies method over HTTP. - - Args: - request (~.online_return_policy.ListOnlineReturnPoliciesRequest): - The request object. Request message for the ``ListOnlineReturnPolicies`` - 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: - ~.online_return_policy.ListOnlineReturnPoliciesResponse: - Response message for the ``ListOnlineReturnPolicies`` - method. - - """ - - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_http_options() - - request, metadata = self._interceptor.pre_list_online_return_policies(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.ListOnlineReturnPolicies", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "ListOnlineReturnPolicies", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OnlineReturnPolicyServiceRestTransport._ListOnlineReturnPolicies._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 = online_return_policy.ListOnlineReturnPoliciesResponse() - pb_resp = online_return_policy.ListOnlineReturnPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_online_return_policies(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_online_return_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = online_return_policy.ListOnlineReturnPoliciesResponse.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.accounts_v1beta.OnlineReturnPolicyServiceClient.list_online_return_policies", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "ListOnlineReturnPolicies", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): - def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.UpdateOnlineReturnPolicy") - - @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: gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_online_return_policy.OnlineReturnPolicy: - r"""Call the update online return - policy method over HTTP. - - Args: - request (~.gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): - The request object. Request message for the ``UpdateOnlineReturnPolicy`` - method. The method supports field masks and when the - mask is provided, only the fields specified in the mask - are updated. - 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: - ~.gsma_online_return_policy.OnlineReturnPolicy: - `Online return - policy `__ - object. This is currently used to represent return - policies for ads and free listings programs. - - """ - - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_http_options() - - request, metadata = self._interceptor.pre_update_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_transcoded_request(http_options, request) - - body = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.OnlineReturnPolicyServiceClient.UpdateOnlineReturnPolicy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "UpdateOnlineReturnPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = OnlineReturnPolicyServiceRestTransport._UpdateOnlineReturnPolicy._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 = gsma_online_return_policy.OnlineReturnPolicy() - pb_resp = gsma_online_return_policy.OnlineReturnPolicy.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_online_return_policy(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_online_return_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gsma_online_return_policy.OnlineReturnPolicy.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.accounts_v1beta.OnlineReturnPolicyServiceClient.update_online_return_policy", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "rpcName": "UpdateOnlineReturnPolicy", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - gsma_online_return_policy.OnlineReturnPolicy]: - # 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._CreateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - 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._DeleteOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - online_return_policy.OnlineReturnPolicy]: - # 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._GetOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - online_return_policy.ListOnlineReturnPoliciesResponse]: - # 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._ListOnlineReturnPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.UpdateOnlineReturnPolicyRequest], - gsma_online_return_policy.OnlineReturnPolicy]: - # 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._UpdateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'OnlineReturnPolicyServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py deleted file mode 100644 index 58371e3cbd32..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/online_return_policy_service/transports/rest_base.py +++ /dev/null @@ -1,298 +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 OnlineReturnPolicyServiceTransport, 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_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy - - -class _BaseOnlineReturnPolicyServiceRestTransport(OnlineReturnPolicyServiceTransport): - """Base REST backend transport for OnlineReturnPolicyService. - - 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 _BaseCreateOnlineReturnPolicy: - 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': '/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies', - 'body': 'online_return_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteOnlineReturnPolicy: - 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': '/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = online_return_policy.DeleteOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetOnlineReturnPolicy: - 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': '/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = online_return_policy.GetOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListOnlineReturnPolicies: - 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': '/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = online_return_policy.ListOnlineReturnPoliciesRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateOnlineReturnPolicy: - 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': 'patch', - 'uri': '/accounts/v1beta/{online_return_policy.name=accounts/*/onlineReturnPolicies/*}', - 'body': 'online_return_policy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseUpdateOnlineReturnPolicy._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseOnlineReturnPolicyServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py deleted file mode 100644 index 3be254a282c6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/async_client.py +++ /dev/null @@ -1,740 +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_accounts_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_accounts_v1beta.services.programs_service import pagers -from google.shopping.merchant_accounts_v1beta.types import programs -from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport -from .client import ProgramsServiceClient - -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 ProgramsServiceAsyncClient: - """Service for program management. - - Programs provide a mechanism for adding functionality to merchant - accounts. A typical example of this is the `Free product - listings `__ - program, which enables products from a merchant's store to be shown - across Google for free. - - This service exposes methods to retrieve a merchant's participation - in all available programs, in addition to methods for explicitly - enabling or disabling participation in each program. - """ - - _client: ProgramsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ProgramsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ProgramsServiceClient._DEFAULT_UNIVERSE - - program_path = staticmethod(ProgramsServiceClient.program_path) - parse_program_path = staticmethod(ProgramsServiceClient.parse_program_path) - common_billing_account_path = staticmethod(ProgramsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProgramsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProgramsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProgramsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProgramsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProgramsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ProgramsServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProgramsServiceClient.parse_common_project_path) - common_location_path = staticmethod(ProgramsServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProgramsServiceClient.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: - ProgramsServiceAsyncClient: The constructed client. - """ - return ProgramsServiceClient.from_service_account_info.__func__(ProgramsServiceAsyncClient, 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: - ProgramsServiceAsyncClient: The constructed client. - """ - return ProgramsServiceClient.from_service_account_file.__func__(ProgramsServiceAsyncClient, 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 ProgramsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProgramsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProgramsServiceTransport: 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 = ProgramsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the programs 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,ProgramsServiceTransport,Callable[..., ProgramsServiceTransport]]]): - 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 ProgramsServiceTransport 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 = ProgramsServiceClient( - 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.accounts_v1beta.ProgramsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "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.accounts.v1beta.ProgramsService", - "credentialsType": None, - } - ) - - async def get_program(self, - request: Optional[Union[programs.GetProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: - r"""Retrieves the specified program for the 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_accounts_v1beta - - async def sample_get_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetProgramRequest( - name="name_value", - ) - - # Make the request - response = await client.get_program(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetProgramRequest, dict]]): - The request object. Request message for the GetProgram - method. - name (:class:`str`): - Required. The name of the program to retrieve. Format: - ``accounts/{account}/programs/{program}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality - to merchant accounts. A typical example of this is - the [Free product - listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) - program, which enables products from a merchant's - store to be shown across Google for free. - - """ - # 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, programs.GetProgramRequest): - request = programs.GetProgramRequest(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.get_program] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_programs(self, - request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsAsyncPager: - r"""Retrieves all programs for the 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_accounts_v1beta - - async def sample_list_programs(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListProgramsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_programs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest, dict]]): - The request object. Request message for the ListPrograms - method. - parent (:class:`str`): - Required. The name of the account for which to retrieve - all programs. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.programs_service.pagers.ListProgramsAsyncPager: - Response message for the ListPrograms - 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, programs.ListProgramsRequest): - request = programs.ListProgramsRequest(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_programs] - - # 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.ListProgramsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def enable_program(self, - request: Optional[Union[programs.EnableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: - r"""Enable participation in the specified program for the - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_enable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.EnableProgramRequest( - name="name_value", - ) - - # Make the request - response = await client.enable_program(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest, dict]]): - The request object. Request message for the EnableProgram - method. - name (:class:`str`): - Required. The name of the program for which to enable - participation for the given account. Format: - ``accounts/{account}/programs/{program}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality - to merchant accounts. A typical example of this is - the [Free product - listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) - program, which enables products from a merchant's - store to be shown across Google for free. - - """ - # 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, programs.EnableProgramRequest): - request = programs.EnableProgramRequest(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.enable_program] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def disable_program(self, - request: Optional[Union[programs.DisableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: - r"""Disable participation in the specified program for - the account. Executing this method requires admin - access. - - .. 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_accounts_v1beta - - async def sample_disable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DisableProgramRequest( - name="name_value", - ) - - # Make the request - response = await client.disable_program(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest, dict]]): - The request object. Request message for the - DisableProgram method. - name (:class:`str`): - Required. The name of the program for which to disable - participation for the given account. Format: - ``accounts/{account}/programs/{program}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality - to merchant accounts. A typical example of this is - the [Free product - listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) - program, which enables products from a merchant's - store to be shown across Google for free. - - """ - # 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, programs.DisableProgramRequest): - request = programs.DisableProgramRequest(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.disable_program] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ProgramsServiceAsyncClient": - 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__ = ( - "ProgramsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py deleted file mode 100644 index 8a5514d19412..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/client.py +++ /dev/null @@ -1,1097 +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_accounts_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_accounts_v1beta.services.programs_service import pagers -from google.shopping.merchant_accounts_v1beta.types import programs -from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProgramsServiceGrpcTransport -from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport -from .transports.rest import ProgramsServiceRestTransport - - -class ProgramsServiceClientMeta(type): - """Metaclass for the ProgramsService 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[ProgramsServiceTransport]] - _transport_registry["grpc"] = ProgramsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ProgramsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ProgramsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ProgramsServiceTransport]: - """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 ProgramsServiceClient(metaclass=ProgramsServiceClientMeta): - """Service for program management. - - Programs provide a mechanism for adding functionality to merchant - accounts. A typical example of this is the `Free product - listings `__ - program, which enables products from a merchant's store to be shown - across Google for free. - - This service exposes methods to retrieve a merchant's participation - in all available programs, in addition to methods for explicitly - enabling or disabling participation in each program. - """ - - @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: - ProgramsServiceClient: 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: - ProgramsServiceClient: 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) -> ProgramsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ProgramsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def program_path(account: str,program: str,) -> str: - """Returns a fully-qualified program string.""" - return "accounts/{account}/programs/{program}".format(account=account, program=program, ) - - @staticmethod - def parse_program_path(path: str) -> Dict[str,str]: - """Parses a program path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/programs/(?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 = ProgramsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ProgramsServiceClient._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 = ProgramsServiceClient._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, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the programs 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,ProgramsServiceTransport,Callable[..., ProgramsServiceTransport]]]): - 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 ProgramsServiceTransport 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 = ProgramsServiceClient._read_environment_variables() - self._client_cert_source = ProgramsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ProgramsServiceClient._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, ProgramsServiceTransport) - if transport_provided: - # transport is a ProgramsServiceTransport 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(ProgramsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ProgramsServiceClient._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[ProgramsServiceTransport], Callable[..., ProgramsServiceTransport]] = ( - ProgramsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ProgramsServiceTransport], 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.accounts_v1beta.ProgramsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "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.accounts.v1beta.ProgramsService", - "credentialsType": None, - } - ) - - def get_program(self, - request: Optional[Union[programs.GetProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: - r"""Retrieves the specified program for the 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_accounts_v1beta - - def sample_get_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetProgramRequest( - name="name_value", - ) - - # Make the request - response = client.get_program(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetProgramRequest, dict]): - The request object. Request message for the GetProgram - method. - name (str): - Required. The name of the program to retrieve. Format: - ``accounts/{account}/programs/{program}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality - to merchant accounts. A typical example of this is - the [Free product - listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) - program, which enables products from a merchant's - store to be shown across Google for free. - - """ - # 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, programs.GetProgramRequest): - request = programs.GetProgramRequest(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.get_program] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_programs(self, - request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsPager: - r"""Retrieves all programs for the 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_accounts_v1beta - - def sample_list_programs(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListProgramsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_programs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest, dict]): - The request object. Request message for the ListPrograms - method. - parent (str): - Required. The name of the account for which to retrieve - all programs. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.programs_service.pagers.ListProgramsPager: - Response message for the ListPrograms - 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, programs.ListProgramsRequest): - request = programs.ListProgramsRequest(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_programs] - - # 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.ListProgramsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def enable_program(self, - request: Optional[Union[programs.EnableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: - r"""Enable participation in the specified program for the - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - def sample_enable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.EnableProgramRequest( - name="name_value", - ) - - # Make the request - response = client.enable_program(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest, dict]): - The request object. Request message for the EnableProgram - method. - name (str): - Required. The name of the program for which to enable - participation for the given account. Format: - ``accounts/{account}/programs/{program}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality - to merchant accounts. A typical example of this is - the [Free product - listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) - program, which enables products from a merchant's - store to be shown across Google for free. - - """ - # 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, programs.EnableProgramRequest): - request = programs.EnableProgramRequest(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.enable_program] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def disable_program(self, - request: Optional[Union[programs.DisableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: - r"""Disable participation in the specified program for - the account. Executing this method requires admin - access. - - .. 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_accounts_v1beta - - def sample_disable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DisableProgramRequest( - name="name_value", - ) - - # Make the request - response = client.disable_program(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest, dict]): - The request object. Request message for the - DisableProgram method. - name (str): - Required. The name of the program for which to disable - participation for the given account. Format: - ``accounts/{account}/programs/{program}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality - to merchant accounts. A typical example of this is - the [Free product - listings](\ https://support.google.com/merchants/topic/9240261?ref_topic=7257954,7259405,&sjid=796648681813264022-EU) - program, which enables products from a merchant's - store to be shown across Google for free. - - """ - # 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, programs.DisableProgramRequest): - request = programs.DisableProgramRequest(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.disable_program] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ProgramsServiceClient": - 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__ = ( - "ProgramsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/pagers.py deleted file mode 100644 index 640983cf175e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_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_accounts_v1beta.types import programs - - -class ListProgramsPager: - """A pager for iterating through ``list_programs`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``programs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPrograms`` requests and continue to iterate - through the ``programs`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` - 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[..., programs.ListProgramsResponse], - request: programs.ListProgramsRequest, - response: programs.ListProgramsResponse, - *, - 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_accounts_v1beta.types.ListProgramsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse): - 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 = programs.ListProgramsRequest(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[programs.ListProgramsResponse]: - 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[programs.Program]: - for page in self.pages: - yield from page.programs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListProgramsAsyncPager: - """A pager for iterating through ``list_programs`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``programs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPrograms`` requests and continue to iterate - through the ``programs`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse` - 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[programs.ListProgramsResponse]], - request: programs.ListProgramsRequest, - response: programs.ListProgramsResponse, - *, - 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_accounts_v1beta.types.ListProgramsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListProgramsResponse): - 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 = programs.ListProgramsRequest(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[programs.ListProgramsResponse]: - 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[programs.Program]: - async def async_generator(): - async for page in self.pages: - for response in page.programs: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst deleted file mode 100644 index b36d6af5aeda..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ProgramsServiceTransport` is the ABC for all transports. -- public child `ProgramsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ProgramsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseProgramsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ProgramsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py deleted file mode 100644 index d32f143bd271..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/base.py +++ /dev/null @@ -1,201 +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_accounts_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.shopping.merchant_accounts_v1beta.types import programs - -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 ProgramsServiceTransport(abc.ABC): - """Abstract transport class for ProgramsService.""" - - 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.get_program: gapic_v1.method.wrap_method( - self.get_program, - default_timeout=None, - client_info=client_info, - ), - self.list_programs: gapic_v1.method.wrap_method( - self.list_programs, - default_timeout=None, - client_info=client_info, - ), - self.enable_program: gapic_v1.method.wrap_method( - self.enable_program, - default_timeout=None, - client_info=client_info, - ), - self.disable_program: gapic_v1.method.wrap_method( - self.disable_program, - 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 get_program(self) -> Callable[ - [programs.GetProgramRequest], - Union[ - programs.Program, - Awaitable[programs.Program] - ]]: - raise NotImplementedError() - - @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - Union[ - programs.ListProgramsResponse, - Awaitable[programs.ListProgramsResponse] - ]]: - raise NotImplementedError() - - @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - Union[ - programs.Program, - Awaitable[programs.Program] - ]]: - raise NotImplementedError() - - @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - Union[ - programs.Program, - Awaitable[programs.Program] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ProgramsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py deleted file mode 100644 index d6654539650f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc.py +++ /dev/null @@ -1,437 +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.shopping.merchant_accounts_v1beta.types import programs -from .base import ProgramsServiceTransport, 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.accounts.v1beta.ProgramsService", - "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.accounts.v1beta.ProgramsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ProgramsServiceGrpcTransport(ProgramsServiceTransport): - """gRPC backend transport for ProgramsService. - - Service for program management. - - Programs provide a mechanism for adding functionality to merchant - accounts. A typical example of this is the `Free product - listings `__ - program, which enables products from a merchant's store to be shown - across Google for free. - - This service exposes methods to retrieve a merchant's participation - in all available programs, in addition to methods for explicitly - enabling or disabling participation in each program. - - 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 get_program(self) -> Callable[ - [programs.GetProgramRequest], - programs.Program]: - r"""Return a callable for the get program method over gRPC. - - Retrieves the specified program for the account. - - Returns: - Callable[[~.GetProgramRequest], - ~.Program]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_program' not in self._stubs: - self._stubs['get_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/GetProgram', - request_serializer=programs.GetProgramRequest.serialize, - response_deserializer=programs.Program.deserialize, - ) - return self._stubs['get_program'] - - @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - programs.ListProgramsResponse]: - r"""Return a callable for the list programs method over gRPC. - - Retrieves all programs for the account. - - Returns: - Callable[[~.ListProgramsRequest], - ~.ListProgramsResponse]: - 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_programs' not in self._stubs: - self._stubs['list_programs'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/ListPrograms', - request_serializer=programs.ListProgramsRequest.serialize, - response_deserializer=programs.ListProgramsResponse.deserialize, - ) - return self._stubs['list_programs'] - - @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - programs.Program]: - r"""Return a callable for the enable program method over gRPC. - - Enable participation in the specified program for the - account. Executing this method requires admin access. - - Returns: - Callable[[~.EnableProgramRequest], - ~.Program]: - 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 'enable_program' not in self._stubs: - self._stubs['enable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/EnableProgram', - request_serializer=programs.EnableProgramRequest.serialize, - response_deserializer=programs.Program.deserialize, - ) - return self._stubs['enable_program'] - - @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - programs.Program]: - r"""Return a callable for the disable program method over gRPC. - - Disable participation in the specified program for - the account. Executing this method requires admin - access. - - Returns: - Callable[[~.DisableProgramRequest], - ~.Program]: - 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 'disable_program' not in self._stubs: - self._stubs['disable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/DisableProgram', - request_serializer=programs.DisableProgramRequest.serialize, - response_deserializer=programs.Program.deserialize, - ) - return self._stubs['disable_program'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProgramsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py deleted file mode 100644 index 83fe0e73dc07..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,473 +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.shopping.merchant_accounts_v1beta.types import programs -from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ProgramsServiceGrpcTransport - -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.accounts.v1beta.ProgramsService", - "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.accounts.v1beta.ProgramsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ProgramsServiceGrpcAsyncIOTransport(ProgramsServiceTransport): - """gRPC AsyncIO backend transport for ProgramsService. - - Service for program management. - - Programs provide a mechanism for adding functionality to merchant - accounts. A typical example of this is the `Free product - listings `__ - program, which enables products from a merchant's store to be shown - across Google for free. - - This service exposes methods to retrieve a merchant's participation - in all available programs, in addition to methods for explicitly - enabling or disabling participation in each program. - - 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 get_program(self) -> Callable[ - [programs.GetProgramRequest], - Awaitable[programs.Program]]: - r"""Return a callable for the get program method over gRPC. - - Retrieves the specified program for the account. - - Returns: - Callable[[~.GetProgramRequest], - Awaitable[~.Program]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_program' not in self._stubs: - self._stubs['get_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/GetProgram', - request_serializer=programs.GetProgramRequest.serialize, - response_deserializer=programs.Program.deserialize, - ) - return self._stubs['get_program'] - - @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - Awaitable[programs.ListProgramsResponse]]: - r"""Return a callable for the list programs method over gRPC. - - Retrieves all programs for the account. - - Returns: - Callable[[~.ListProgramsRequest], - Awaitable[~.ListProgramsResponse]]: - 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_programs' not in self._stubs: - self._stubs['list_programs'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/ListPrograms', - request_serializer=programs.ListProgramsRequest.serialize, - response_deserializer=programs.ListProgramsResponse.deserialize, - ) - return self._stubs['list_programs'] - - @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - Awaitable[programs.Program]]: - r"""Return a callable for the enable program method over gRPC. - - Enable participation in the specified program for the - account. Executing this method requires admin access. - - Returns: - Callable[[~.EnableProgramRequest], - Awaitable[~.Program]]: - 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 'enable_program' not in self._stubs: - self._stubs['enable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/EnableProgram', - request_serializer=programs.EnableProgramRequest.serialize, - response_deserializer=programs.Program.deserialize, - ) - return self._stubs['enable_program'] - - @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - Awaitable[programs.Program]]: - r"""Return a callable for the disable program method over gRPC. - - Disable participation in the specified program for - the account. Executing this method requires admin - access. - - Returns: - Callable[[~.DisableProgramRequest], - Awaitable[~.Program]]: - 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 'disable_program' not in self._stubs: - self._stubs['disable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ProgramsService/DisableProgram', - request_serializer=programs.DisableProgramRequest.serialize, - response_deserializer=programs.Program.deserialize, - ) - return self._stubs['disable_program'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_program: self._wrap_method( - self.get_program, - default_timeout=None, - client_info=client_info, - ), - self.list_programs: self._wrap_method( - self.list_programs, - default_timeout=None, - client_info=client_info, - ), - self.enable_program: self._wrap_method( - self.enable_program, - default_timeout=None, - client_info=client_info, - ), - self.disable_program: self._wrap_method( - self.disable_program, - 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__ = ( - 'ProgramsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py deleted file mode 100644 index 6ed479278432..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest.py +++ /dev/null @@ -1,913 +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.shopping.merchant_accounts_v1beta.types import programs - - -from .rest_base import _BaseProgramsServiceRestTransport -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 ProgramsServiceRestInterceptor: - """Interceptor for ProgramsService. - - 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 ProgramsServiceRestTransport. - - .. code-block:: python - class MyCustomProgramsServiceInterceptor(ProgramsServiceRestInterceptor): - def pre_disable_program(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_disable_program(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_enable_program(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_enable_program(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_program(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_program(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_programs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_programs(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ProgramsServiceRestTransport(interceptor=MyCustomProgramsServiceInterceptor()) - client = ProgramsServiceClient(transport=transport) - - - """ - def pre_disable_program(self, request: programs.DisableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for disable_program - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProgramsService server. - """ - return request, metadata - - def post_disable_program(self, response: programs.Program) -> programs.Program: - """Post-rpc interceptor for disable_program - - DEPRECATED. Please use the `post_disable_program_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. This `post_disable_program` interceptor runs - before the `post_disable_program_with_metadata` interceptor. - """ - return response - - def post_disable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for disable_program - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ProgramsService server but before it is returned to user code. - - We recommend only using this `post_disable_program_with_metadata` - interceptor in new development instead of the `post_disable_program` interceptor. - When both interceptors are used, this `post_disable_program_with_metadata` interceptor runs after the - `post_disable_program` interceptor. The (possibly modified) response returned by - `post_disable_program` will be passed to - `post_disable_program_with_metadata`. - """ - return response, metadata - - def pre_enable_program(self, request: programs.EnableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for enable_program - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProgramsService server. - """ - return request, metadata - - def post_enable_program(self, response: programs.Program) -> programs.Program: - """Post-rpc interceptor for enable_program - - DEPRECATED. Please use the `post_enable_program_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. This `post_enable_program` interceptor runs - before the `post_enable_program_with_metadata` interceptor. - """ - return response - - def post_enable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for enable_program - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ProgramsService server but before it is returned to user code. - - We recommend only using this `post_enable_program_with_metadata` - interceptor in new development instead of the `post_enable_program` interceptor. - When both interceptors are used, this `post_enable_program_with_metadata` interceptor runs after the - `post_enable_program` interceptor. The (possibly modified) response returned by - `post_enable_program` will be passed to - `post_enable_program_with_metadata`. - """ - return response, metadata - - def pre_get_program(self, request: programs.GetProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_program - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProgramsService server. - """ - return request, metadata - - def post_get_program(self, response: programs.Program) -> programs.Program: - """Post-rpc interceptor for get_program - - DEPRECATED. Please use the `post_get_program_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. This `post_get_program` interceptor runs - before the `post_get_program_with_metadata` interceptor. - """ - return response - - def post_get_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_program - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ProgramsService server but before it is returned to user code. - - We recommend only using this `post_get_program_with_metadata` - interceptor in new development instead of the `post_get_program` interceptor. - When both interceptors are used, this `post_get_program_with_metadata` interceptor runs after the - `post_get_program` interceptor. The (possibly modified) response returned by - `post_get_program` will be passed to - `post_get_program_with_metadata`. - """ - return response, metadata - - def pre_list_programs(self, request: programs.ListProgramsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_programs - - Override in a subclass to manipulate the request or metadata - before they are sent to the ProgramsService server. - """ - return request, metadata - - def post_list_programs(self, response: programs.ListProgramsResponse) -> programs.ListProgramsResponse: - """Post-rpc interceptor for list_programs - - DEPRECATED. Please use the `post_list_programs_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ProgramsService server but before - it is returned to user code. This `post_list_programs` interceptor runs - before the `post_list_programs_with_metadata` interceptor. - """ - return response - - def post_list_programs_with_metadata(self, response: programs.ListProgramsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_programs - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ProgramsService server but before it is returned to user code. - - We recommend only using this `post_list_programs_with_metadata` - interceptor in new development instead of the `post_list_programs` interceptor. - When both interceptors are used, this `post_list_programs_with_metadata` interceptor runs after the - `post_list_programs` interceptor. The (possibly modified) response returned by - `post_list_programs` will be passed to - `post_list_programs_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class ProgramsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ProgramsServiceRestInterceptor - - -class ProgramsServiceRestTransport(_BaseProgramsServiceRestTransport): - """REST backend synchronous transport for ProgramsService. - - Service for program management. - - Programs provide a mechanism for adding functionality to merchant - accounts. A typical example of this is the `Free product - listings `__ - program, which enables products from a merchant's store to be shown - across Google for free. - - This service exposes methods to retrieve a merchant's participation - in all available programs, in addition to methods for explicitly - enabling or disabling participation in each program. - - 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[ProgramsServiceRestInterceptor] = 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 ProgramsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _DisableProgram(_BaseProgramsServiceRestTransport._BaseDisableProgram, ProgramsServiceRestStub): - def __hash__(self): - return hash("ProgramsServiceRestTransport.DisableProgram") - - @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: programs.DisableProgramRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.Program: - r"""Call the disable program method over HTTP. - - Args: - request (~.programs.DisableProgramRequest): - The request object. Request message for the - DisableProgram 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: - ~.programs.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality to - merchant accounts. A typical example of this is the - `Free product - listings `__ - program, which enables products from a merchant's store - to be shown across Google for free. - - """ - - http_options = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_http_options() - - request, metadata = self._interceptor.pre_disable_program(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_transcoded_request(http_options, request) - - body = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.DisableProgram", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "DisableProgram", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ProgramsServiceRestTransport._DisableProgram._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 = programs.Program() - pb_resp = programs.Program.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_disable_program(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_disable_program_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = programs.Program.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.accounts_v1beta.ProgramsServiceClient.disable_program", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "DisableProgram", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _EnableProgram(_BaseProgramsServiceRestTransport._BaseEnableProgram, ProgramsServiceRestStub): - def __hash__(self): - return hash("ProgramsServiceRestTransport.EnableProgram") - - @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: programs.EnableProgramRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.Program: - r"""Call the enable program method over HTTP. - - Args: - request (~.programs.EnableProgramRequest): - The request object. Request message for the EnableProgram - 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: - ~.programs.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality to - merchant accounts. A typical example of this is the - `Free product - listings `__ - program, which enables products from a merchant's store - to be shown across Google for free. - - """ - - http_options = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_http_options() - - request, metadata = self._interceptor.pre_enable_program(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_transcoded_request(http_options, request) - - body = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.EnableProgram", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "EnableProgram", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ProgramsServiceRestTransport._EnableProgram._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 = programs.Program() - pb_resp = programs.Program.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_enable_program(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_enable_program_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = programs.Program.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.accounts_v1beta.ProgramsServiceClient.enable_program", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "EnableProgram", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetProgram(_BaseProgramsServiceRestTransport._BaseGetProgram, ProgramsServiceRestStub): - def __hash__(self): - return hash("ProgramsServiceRestTransport.GetProgram") - - @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: programs.GetProgramRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.Program: - r"""Call the get program method over HTTP. - - Args: - request (~.programs.GetProgramRequest): - The request object. Request message for the GetProgram - 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: - ~.programs.Program: - Defines participation in a given program for the - specified account. - - Programs provide a mechanism for adding functionality to - merchant accounts. A typical example of this is the - `Free product - listings `__ - program, which enables products from a merchant's store - to be shown across Google for free. - - """ - - http_options = _BaseProgramsServiceRestTransport._BaseGetProgram._get_http_options() - - request, metadata = self._interceptor.pre_get_program(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseGetProgram._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseGetProgram._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.GetProgram", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "GetProgram", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ProgramsServiceRestTransport._GetProgram._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 = programs.Program() - pb_resp = programs.Program.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_program(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_program_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = programs.Program.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.accounts_v1beta.ProgramsServiceClient.get_program", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "GetProgram", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListPrograms(_BaseProgramsServiceRestTransport._BaseListPrograms, ProgramsServiceRestStub): - def __hash__(self): - return hash("ProgramsServiceRestTransport.ListPrograms") - - @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: programs.ListProgramsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.ListProgramsResponse: - r"""Call the list programs method over HTTP. - - Args: - request (~.programs.ListProgramsRequest): - The request object. Request message for the ListPrograms - 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: - ~.programs.ListProgramsResponse: - Response message for the ListPrograms - method. - - """ - - http_options = _BaseProgramsServiceRestTransport._BaseListPrograms._get_http_options() - - request, metadata = self._interceptor.pre_list_programs(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseListPrograms._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseListPrograms._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ProgramsServiceClient.ListPrograms", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "ListPrograms", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ProgramsServiceRestTransport._ListPrograms._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 = programs.ListProgramsResponse() - pb_resp = programs.ListProgramsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_programs(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_programs_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = programs.ListProgramsResponse.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.accounts_v1beta.ProgramsServiceClient.list_programs", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "rpcName": "ListPrograms", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - programs.Program]: - # 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._DisableProgram(self._session, self._host, self._interceptor) # type: ignore - - @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - programs.Program]: - # 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._EnableProgram(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_program(self) -> Callable[ - [programs.GetProgramRequest], - programs.Program]: - # 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._GetProgram(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - programs.ListProgramsResponse]: - # 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._ListPrograms(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ProgramsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py deleted file mode 100644 index 5365133a004b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/rest_base.py +++ /dev/null @@ -1,259 +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 ProgramsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import programs - - -class _BaseProgramsServiceRestTransport(ProgramsServiceTransport): - """Base REST backend transport for ProgramsService. - - 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 _BaseDisableProgram: - 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': '/accounts/v1beta/{name=accounts/*/programs/*}:disable', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = programs.DisableProgramRequest.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(_BaseProgramsServiceRestTransport._BaseDisableProgram._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseEnableProgram: - 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': '/accounts/v1beta/{name=accounts/*/programs/*}:enable', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = programs.EnableProgramRequest.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(_BaseProgramsServiceRestTransport._BaseEnableProgram._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetProgram: - 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': '/accounts/v1beta/{name=accounts/*/programs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = programs.GetProgramRequest.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(_BaseProgramsServiceRestTransport._BaseGetProgram._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListPrograms: - 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': '/accounts/v1beta/{parent=accounts/*}/programs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = programs.ListProgramsRequest.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(_BaseProgramsServiceRestTransport._BaseListPrograms._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseProgramsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/__init__.py deleted file mode 100644 index 4809e9fed9f9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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 RegionsServiceClient -from .async_client import RegionsServiceAsyncClient - -__all__ = ( - 'RegionsServiceClient', - 'RegionsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py deleted file mode 100644 index 15b74ad96d1b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/async_client.py +++ /dev/null @@ -1,847 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.regions_service import pagers -from google.shopping.merchant_accounts_v1beta.types import regions -from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport -from .client import RegionsServiceClient - -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 RegionsServiceAsyncClient: - """Manages regions configuration. - - This API defines the following resource model: - - - [Region][google.shopping.merchant.accounts.v1main.Region] - """ - - _client: RegionsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = RegionsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = RegionsServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(RegionsServiceClient.account_path) - parse_account_path = staticmethod(RegionsServiceClient.parse_account_path) - region_path = staticmethod(RegionsServiceClient.region_path) - parse_region_path = staticmethod(RegionsServiceClient.parse_region_path) - common_billing_account_path = staticmethod(RegionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegionsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RegionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegionsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RegionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegionsServiceClient.parse_common_project_path) - common_location_path = staticmethod(RegionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegionsServiceClient.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: - RegionsServiceAsyncClient: The constructed client. - """ - return RegionsServiceClient.from_service_account_info.__func__(RegionsServiceAsyncClient, 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: - RegionsServiceAsyncClient: The constructed client. - """ - return RegionsServiceClient.from_service_account_file.__func__(RegionsServiceAsyncClient, 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 RegionsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RegionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegionsServiceTransport: 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 = RegionsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the regions 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,RegionsServiceTransport,Callable[..., RegionsServiceTransport]]]): - 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 RegionsServiceTransport 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 = RegionsServiceClient( - 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.accounts_v1beta.RegionsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "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.accounts.v1beta.RegionsService", - "credentialsType": None, - } - ) - - async def get_region(self, - request: Optional[Union[regions.GetRegionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: - r"""Retrieves a region defined in your Merchant Center - 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_accounts_v1beta - - async def sample_get_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetRegionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_region(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetRegionRequest, dict]]): - The request object. Request message for the ``GetRegion`` method. - name (:class:`str`): - Required. The name of the region to retrieve. Format: - ``accounts/{account}/regions/{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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Region: - Represents a geographic region that you can use as a target with both the - RegionalInventory and ShippingSettings services. You - can define regions as collections of either postal - codes or, in some countries, using predefined - geotargets. For more information, see [Set up regions - ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) - for more information. - - """ - # 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, regions.GetRegionRequest): - request = regions.GetRegionRequest(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.get_region] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_region(self, - request: Optional[Union[regions.CreateRegionRequest, dict]] = None, - *, - parent: Optional[str] = None, - region: Optional[regions.Region] = None, - region_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: - r"""Creates a region definition in your Merchant Center - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_create_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateRegionRequest( - parent="parent_value", - region_id="region_id_value", - ) - - # Make the request - response = await client.create_region(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest, dict]]): - The request object. Request message for the ``CreateRegion`` method. - parent (:class:`str`): - Required. The account to create a region for. Format: - ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - region (:class:`google.shopping.merchant_accounts_v1beta.types.Region`): - Required. The region to create. - This corresponds to the ``region`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - region_id (:class:`str`): - Required. The identifier for the - region, unique over all regions of the - same account. - - This corresponds to the ``region_id`` 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_accounts_v1beta.types.Region: - Represents a geographic region that you can use as a target with both the - RegionalInventory and ShippingSettings services. You - can define regions as collections of either postal - codes or, in some countries, using predefined - geotargets. For more information, see [Set up regions - ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) - for more information. - - """ - # 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, region, region_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, regions.CreateRegionRequest): - request = regions.CreateRegionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if region is not None: - request.region = region - if region_id is not None: - request.region_id = region_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_region] - - # 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 update_region(self, - request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, - *, - region: Optional[regions.Region] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: - r"""Updates a region definition in your Merchant Center - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_update_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateRegionRequest( - ) - - # Make the request - response = await client.update_region(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest, dict]]): - The request object. Request message for the ``UpdateRegion`` method. - region (:class:`google.shopping.merchant_accounts_v1beta.types.Region`): - Required. The updated region. - This corresponds to the ``region`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Optional. The comma-separated field mask indicating the - fields to update. Example: - ``"displayName,postalCodeArea.regionCode"``. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Region: - Represents a geographic region that you can use as a target with both the - RegionalInventory and ShippingSettings services. You - can define regions as collections of either postal - codes or, in some countries, using predefined - geotargets. For more information, see [Set up regions - ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) - for more information. - - """ - # 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 = [region, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, regions.UpdateRegionRequest): - request = regions.UpdateRegionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if region is not None: - request.region = region - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_region] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("region.name", request.region.name), - )), - ) - - # 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_region(self, - request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, - *, - name: 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 a region definition from your Merchant Center - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_delete_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteRegionRequest( - name="name_value", - ) - - # Make the request - await client.delete_region(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest, dict]]): - The request object. Request message for the ``DeleteRegion`` method. - name (:class:`str`): - Required. The name of the region to delete. Format: - ``accounts/{account}/regions/{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, regions.DeleteRegionRequest): - request = regions.DeleteRegionRequest(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_region] - - # 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 list_regions(self, - request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsAsyncPager: - r"""Lists the regions in your Merchant Center 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_accounts_v1beta - - async def sample_list_regions(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListRegionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest, dict]]): - The request object. Request message for the ``ListRegions`` method. - parent (:class:`str`): - Required. The account to list regions for. Format: - ``accounts/{account}`` - - 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_accounts_v1beta.services.regions_service.pagers.ListRegionsAsyncPager: - Response message for the ListRegions 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, regions.ListRegionsRequest): - request = regions.ListRegionsRequest(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_regions] - - # 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.ListRegionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "RegionsServiceAsyncClient": - 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__ = ( - "RegionsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py deleted file mode 100644 index a3ef9c4bec4f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/client.py +++ /dev/null @@ -1,1212 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.regions_service import pagers -from google.shopping.merchant_accounts_v1beta.types import regions -from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RegionsServiceGrpcTransport -from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport -from .transports.rest import RegionsServiceRestTransport - - -class RegionsServiceClientMeta(type): - """Metaclass for the RegionsService 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[RegionsServiceTransport]] - _transport_registry["grpc"] = RegionsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RegionsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = RegionsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RegionsServiceTransport]: - """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 RegionsServiceClient(metaclass=RegionsServiceClientMeta): - """Manages regions configuration. - - This API defines the following resource model: - - - [Region][google.shopping.merchant.accounts.v1main.Region] - """ - - @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: - RegionsServiceClient: 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: - RegionsServiceClient: 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) -> RegionsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RegionsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def region_path(account: str,region: str,) -> str: - """Returns a fully-qualified region string.""" - return "accounts/{account}/regions/{region}".format(account=account, region=region, ) - - @staticmethod - def parse_region_path(path: str) -> Dict[str,str]: - """Parses a region path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/regions/(?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 = RegionsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = RegionsServiceClient._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 = RegionsServiceClient._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, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the regions 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,RegionsServiceTransport,Callable[..., RegionsServiceTransport]]]): - 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 RegionsServiceTransport 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 = RegionsServiceClient._read_environment_variables() - self._client_cert_source = RegionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RegionsServiceClient._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, RegionsServiceTransport) - if transport_provided: - # transport is a RegionsServiceTransport 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(RegionsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - RegionsServiceClient._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[RegionsServiceTransport], Callable[..., RegionsServiceTransport]] = ( - RegionsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., RegionsServiceTransport], 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.accounts_v1beta.RegionsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "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.accounts.v1beta.RegionsService", - "credentialsType": None, - } - ) - - def get_region(self, - request: Optional[Union[regions.GetRegionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: - r"""Retrieves a region defined in your Merchant Center - 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_accounts_v1beta - - def sample_get_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetRegionRequest( - name="name_value", - ) - - # Make the request - response = client.get_region(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetRegionRequest, dict]): - The request object. Request message for the ``GetRegion`` method. - name (str): - Required. The name of the region to retrieve. Format: - ``accounts/{account}/regions/{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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.Region: - Represents a geographic region that you can use as a target with both the - RegionalInventory and ShippingSettings services. You - can define regions as collections of either postal - codes or, in some countries, using predefined - geotargets. For more information, see [Set up regions - ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) - for more information. - - """ - # 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, regions.GetRegionRequest): - request = regions.GetRegionRequest(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.get_region] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_region(self, - request: Optional[Union[regions.CreateRegionRequest, dict]] = None, - *, - parent: Optional[str] = None, - region: Optional[regions.Region] = None, - region_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: - r"""Creates a region definition in your Merchant Center - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - def sample_create_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateRegionRequest( - parent="parent_value", - region_id="region_id_value", - ) - - # Make the request - response = client.create_region(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest, dict]): - The request object. Request message for the ``CreateRegion`` method. - parent (str): - Required. The account to create a region for. Format: - ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - region (google.shopping.merchant_accounts_v1beta.types.Region): - Required. The region to create. - This corresponds to the ``region`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - region_id (str): - Required. The identifier for the - region, unique over all regions of the - same account. - - This corresponds to the ``region_id`` 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_accounts_v1beta.types.Region: - Represents a geographic region that you can use as a target with both the - RegionalInventory and ShippingSettings services. You - can define regions as collections of either postal - codes or, in some countries, using predefined - geotargets. For more information, see [Set up regions - ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) - for more information. - - """ - # 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, region, region_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, regions.CreateRegionRequest): - request = regions.CreateRegionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if region is not None: - request.region = region - if region_id is not None: - request.region_id = region_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_region] - - # 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 update_region(self, - request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, - *, - region: Optional[regions.Region] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: - r"""Updates a region definition in your Merchant Center - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - def sample_update_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateRegionRequest( - ) - - # Make the request - response = client.update_region(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest, dict]): - The request object. Request message for the ``UpdateRegion`` method. - region (google.shopping.merchant_accounts_v1beta.types.Region): - Required. The updated region. - This corresponds to the ``region`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The comma-separated field mask indicating the - fields to update. Example: - ``"displayName,postalCodeArea.regionCode"``. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.Region: - Represents a geographic region that you can use as a target with both the - RegionalInventory and ShippingSettings services. You - can define regions as collections of either postal - codes or, in some countries, using predefined - geotargets. For more information, see [Set up regions - ](\ https://support.google.com/merchants/answer/7410946#zippy=%2Ccreate-a-new-region) - for more information. - - """ - # 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 = [region, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, regions.UpdateRegionRequest): - request = regions.UpdateRegionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if region is not None: - request.region = region - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_region] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("region.name", request.region.name), - )), - ) - - # 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_region(self, - request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, - *, - name: 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 a region definition from your Merchant Center - account. Executing this method requires admin access. - - .. 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_accounts_v1beta - - def sample_delete_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteRegionRequest( - name="name_value", - ) - - # Make the request - client.delete_region(request=request) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest, dict]): - The request object. Request message for the ``DeleteRegion`` method. - name (str): - Required. The name of the region to delete. Format: - ``accounts/{account}/regions/{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, regions.DeleteRegionRequest): - request = regions.DeleteRegionRequest(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_region] - - # 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 list_regions(self, - request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsPager: - r"""Lists the regions in your Merchant Center 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_accounts_v1beta - - def sample_list_regions(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListRegionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest, dict]): - The request object. Request message for the ``ListRegions`` method. - parent (str): - Required. The account to list regions for. Format: - ``accounts/{account}`` - - 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_accounts_v1beta.services.regions_service.pagers.ListRegionsPager: - Response message for the ListRegions 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, regions.ListRegionsRequest): - request = regions.ListRegionsRequest(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_regions] - - # 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.ListRegionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RegionsServiceClient": - 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__ = ( - "RegionsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/pagers.py deleted file mode 100644 index 0edde3c4b20c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_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_accounts_v1beta.types import regions - - -class ListRegionsPager: - """A pager for iterating through ``list_regions`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``regions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListRegions`` requests and continue to iterate - through the ``regions`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` - 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[..., regions.ListRegionsResponse], - request: regions.ListRegionsRequest, - response: regions.ListRegionsResponse, - *, - 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_accounts_v1beta.types.ListRegionsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse): - 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 = regions.ListRegionsRequest(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[regions.ListRegionsResponse]: - 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[regions.Region]: - for page in self.pages: - yield from page.regions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRegionsAsyncPager: - """A pager for iterating through ``list_regions`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``regions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListRegions`` requests and continue to iterate - through the ``regions`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse` - 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[regions.ListRegionsResponse]], - request: regions.ListRegionsRequest, - response: regions.ListRegionsResponse, - *, - 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_accounts_v1beta.types.ListRegionsRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListRegionsResponse): - 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 = regions.ListRegionsRequest(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[regions.ListRegionsResponse]: - 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[regions.Region]: - async def async_generator(): - async for page in self.pages: - for response in page.regions: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst deleted file mode 100644 index 58b1a6574ad7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`RegionsServiceTransport` is the ABC for all transports. -- public child `RegionsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `RegionsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseRegionsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `RegionsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py deleted file mode 100644 index f88c19fb292f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/base.py +++ /dev/null @@ -1,216 +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_accounts_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_accounts_v1beta.types import regions - -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 RegionsServiceTransport(abc.ABC): - """Abstract transport class for RegionsService.""" - - 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.get_region: gapic_v1.method.wrap_method( - self.get_region, - default_timeout=None, - client_info=client_info, - ), - self.create_region: gapic_v1.method.wrap_method( - self.create_region, - default_timeout=None, - client_info=client_info, - ), - self.update_region: gapic_v1.method.wrap_method( - self.update_region, - default_timeout=None, - client_info=client_info, - ), - self.delete_region: gapic_v1.method.wrap_method( - self.delete_region, - default_timeout=None, - client_info=client_info, - ), - self.list_regions: gapic_v1.method.wrap_method( - self.list_regions, - 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 get_region(self) -> Callable[ - [regions.GetRegionRequest], - Union[ - regions.Region, - Awaitable[regions.Region] - ]]: - raise NotImplementedError() - - @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - Union[ - regions.Region, - Awaitable[regions.Region] - ]]: - raise NotImplementedError() - - @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - Union[ - regions.Region, - Awaitable[regions.Region] - ]]: - raise NotImplementedError() - - @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - Union[ - regions.ListRegionsResponse, - Awaitable[regions.ListRegionsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RegionsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py deleted file mode 100644 index b5a01c06cea2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc.py +++ /dev/null @@ -1,459 +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_accounts_v1beta.types import regions -from .base import RegionsServiceTransport, 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.accounts.v1beta.RegionsService", - "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.accounts.v1beta.RegionsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RegionsServiceGrpcTransport(RegionsServiceTransport): - """gRPC backend transport for RegionsService. - - Manages regions configuration. - - This API defines the following resource model: - - - [Region][google.shopping.merchant.accounts.v1main.Region] - - 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 get_region(self) -> Callable[ - [regions.GetRegionRequest], - regions.Region]: - r"""Return a callable for the get region method over gRPC. - - Retrieves a region defined in your Merchant Center - account. - - Returns: - Callable[[~.GetRegionRequest], - ~.Region]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_region' not in self._stubs: - self._stubs['get_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/GetRegion', - request_serializer=regions.GetRegionRequest.serialize, - response_deserializer=regions.Region.deserialize, - ) - return self._stubs['get_region'] - - @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - regions.Region]: - r"""Return a callable for the create region method over gRPC. - - Creates a region definition in your Merchant Center - account. Executing this method requires admin access. - - Returns: - Callable[[~.CreateRegionRequest], - ~.Region]: - 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 'create_region' not in self._stubs: - self._stubs['create_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/CreateRegion', - request_serializer=regions.CreateRegionRequest.serialize, - response_deserializer=regions.Region.deserialize, - ) - return self._stubs['create_region'] - - @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - regions.Region]: - r"""Return a callable for the update region method over gRPC. - - Updates a region definition in your Merchant Center - account. Executing this method requires admin access. - - Returns: - Callable[[~.UpdateRegionRequest], - ~.Region]: - 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 'update_region' not in self._stubs: - self._stubs['update_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/UpdateRegion', - request_serializer=regions.UpdateRegionRequest.serialize, - response_deserializer=regions.Region.deserialize, - ) - return self._stubs['update_region'] - - @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete region method over gRPC. - - Deletes a region definition from your Merchant Center - account. Executing this method requires admin access. - - Returns: - Callable[[~.DeleteRegionRequest], - ~.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_region' not in self._stubs: - self._stubs['delete_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/DeleteRegion', - request_serializer=regions.DeleteRegionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_region'] - - @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - regions.ListRegionsResponse]: - r"""Return a callable for the list regions method over gRPC. - - Lists the regions in your Merchant Center account. - - Returns: - Callable[[~.ListRegionsRequest], - ~.ListRegionsResponse]: - 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_regions' not in self._stubs: - self._stubs['list_regions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/ListRegions', - request_serializer=regions.ListRegionsRequest.serialize, - response_deserializer=regions.ListRegionsResponse.deserialize, - ) - return self._stubs['list_regions'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RegionsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py deleted file mode 100644 index 6c72dc1d4595..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,500 +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_accounts_v1beta.types import regions -from .base import RegionsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RegionsServiceGrpcTransport - -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.accounts.v1beta.RegionsService", - "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.accounts.v1beta.RegionsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class RegionsServiceGrpcAsyncIOTransport(RegionsServiceTransport): - """gRPC AsyncIO backend transport for RegionsService. - - Manages regions configuration. - - This API defines the following resource model: - - - [Region][google.shopping.merchant.accounts.v1main.Region] - - 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 get_region(self) -> Callable[ - [regions.GetRegionRequest], - Awaitable[regions.Region]]: - r"""Return a callable for the get region method over gRPC. - - Retrieves a region defined in your Merchant Center - account. - - Returns: - Callable[[~.GetRegionRequest], - Awaitable[~.Region]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_region' not in self._stubs: - self._stubs['get_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/GetRegion', - request_serializer=regions.GetRegionRequest.serialize, - response_deserializer=regions.Region.deserialize, - ) - return self._stubs['get_region'] - - @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - Awaitable[regions.Region]]: - r"""Return a callable for the create region method over gRPC. - - Creates a region definition in your Merchant Center - account. Executing this method requires admin access. - - Returns: - Callable[[~.CreateRegionRequest], - Awaitable[~.Region]]: - 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 'create_region' not in self._stubs: - self._stubs['create_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/CreateRegion', - request_serializer=regions.CreateRegionRequest.serialize, - response_deserializer=regions.Region.deserialize, - ) - return self._stubs['create_region'] - - @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - Awaitable[regions.Region]]: - r"""Return a callable for the update region method over gRPC. - - Updates a region definition in your Merchant Center - account. Executing this method requires admin access. - - Returns: - Callable[[~.UpdateRegionRequest], - Awaitable[~.Region]]: - 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 'update_region' not in self._stubs: - self._stubs['update_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/UpdateRegion', - request_serializer=regions.UpdateRegionRequest.serialize, - response_deserializer=regions.Region.deserialize, - ) - return self._stubs['update_region'] - - @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete region method over gRPC. - - Deletes a region definition from your Merchant Center - account. Executing this method requires admin access. - - Returns: - Callable[[~.DeleteRegionRequest], - 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_region' not in self._stubs: - self._stubs['delete_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/DeleteRegion', - request_serializer=regions.DeleteRegionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_region'] - - @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - Awaitable[regions.ListRegionsResponse]]: - r"""Return a callable for the list regions method over gRPC. - - Lists the regions in your Merchant Center account. - - Returns: - Callable[[~.ListRegionsRequest], - Awaitable[~.ListRegionsResponse]]: - 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_regions' not in self._stubs: - self._stubs['list_regions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.RegionsService/ListRegions', - request_serializer=regions.ListRegionsRequest.serialize, - response_deserializer=regions.ListRegionsResponse.deserialize, - ) - return self._stubs['list_regions'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_region: self._wrap_method( - self.get_region, - default_timeout=None, - client_info=client_info, - ), - self.create_region: self._wrap_method( - self.create_region, - default_timeout=None, - client_info=client_info, - ), - self.update_region: self._wrap_method( - self.update_region, - default_timeout=None, - client_info=client_info, - ), - self.delete_region: self._wrap_method( - self.delete_region, - default_timeout=None, - client_info=client_info, - ), - self.list_regions: self._wrap_method( - self.list_regions, - 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__ = ( - 'RegionsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py deleted file mode 100644 index 9160e7a04b93..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest.py +++ /dev/null @@ -1,1004 +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_accounts_v1beta.types import regions - - -from .rest_base import _BaseRegionsServiceRestTransport -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 RegionsServiceRestInterceptor: - """Interceptor for RegionsService. - - 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 RegionsServiceRestTransport. - - .. code-block:: python - class MyCustomRegionsServiceInterceptor(RegionsServiceRestInterceptor): - def pre_create_region(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_region(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_region(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_region(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_region(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_regions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_regions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_region(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_region(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RegionsServiceRestTransport(interceptor=MyCustomRegionsServiceInterceptor()) - client = RegionsServiceClient(transport=transport) - - - """ - def pre_create_region(self, request: regions.CreateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_region - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionsService server. - """ - return request, metadata - - def post_create_region(self, response: regions.Region) -> regions.Region: - """Post-rpc interceptor for create_region - - DEPRECATED. Please use the `post_create_region_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. This `post_create_region` interceptor runs - before the `post_create_region_with_metadata` interceptor. - """ - return response - - def post_create_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_region - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the RegionsService server but before it is returned to user code. - - We recommend only using this `post_create_region_with_metadata` - interceptor in new development instead of the `post_create_region` interceptor. - When both interceptors are used, this `post_create_region_with_metadata` interceptor runs after the - `post_create_region` interceptor. The (possibly modified) response returned by - `post_create_region` will be passed to - `post_create_region_with_metadata`. - """ - return response, metadata - - def pre_delete_region(self, request: regions.DeleteRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_region - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionsService server. - """ - return request, metadata - - def pre_get_region(self, request: regions.GetRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_region - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionsService server. - """ - return request, metadata - - def post_get_region(self, response: regions.Region) -> regions.Region: - """Post-rpc interceptor for get_region - - DEPRECATED. Please use the `post_get_region_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. This `post_get_region` interceptor runs - before the `post_get_region_with_metadata` interceptor. - """ - return response - - def post_get_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_region - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the RegionsService server but before it is returned to user code. - - We recommend only using this `post_get_region_with_metadata` - interceptor in new development instead of the `post_get_region` interceptor. - When both interceptors are used, this `post_get_region_with_metadata` interceptor runs after the - `post_get_region` interceptor. The (possibly modified) response returned by - `post_get_region` will be passed to - `post_get_region_with_metadata`. - """ - return response, metadata - - def pre_list_regions(self, request: regions.ListRegionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_regions - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionsService server. - """ - return request, metadata - - def post_list_regions(self, response: regions.ListRegionsResponse) -> regions.ListRegionsResponse: - """Post-rpc interceptor for list_regions - - DEPRECATED. Please use the `post_list_regions_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. This `post_list_regions` interceptor runs - before the `post_list_regions_with_metadata` interceptor. - """ - return response - - def post_list_regions_with_metadata(self, response: regions.ListRegionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_regions - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the RegionsService server but before it is returned to user code. - - We recommend only using this `post_list_regions_with_metadata` - interceptor in new development instead of the `post_list_regions` interceptor. - When both interceptors are used, this `post_list_regions_with_metadata` interceptor runs after the - `post_list_regions` interceptor. The (possibly modified) response returned by - `post_list_regions` will be passed to - `post_list_regions_with_metadata`. - """ - return response, metadata - - def pre_update_region(self, request: regions.UpdateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_region - - Override in a subclass to manipulate the request or metadata - before they are sent to the RegionsService server. - """ - return request, metadata - - def post_update_region(self, response: regions.Region) -> regions.Region: - """Post-rpc interceptor for update_region - - DEPRECATED. Please use the `post_update_region_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the RegionsService server but before - it is returned to user code. This `post_update_region` interceptor runs - before the `post_update_region_with_metadata` interceptor. - """ - return response - - def post_update_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_region - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the RegionsService server but before it is returned to user code. - - We recommend only using this `post_update_region_with_metadata` - interceptor in new development instead of the `post_update_region` interceptor. - When both interceptors are used, this `post_update_region_with_metadata` interceptor runs after the - `post_update_region` interceptor. The (possibly modified) response returned by - `post_update_region` will be passed to - `post_update_region_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class RegionsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RegionsServiceRestInterceptor - - -class RegionsServiceRestTransport(_BaseRegionsServiceRestTransport): - """REST backend synchronous transport for RegionsService. - - Manages regions configuration. - - This API defines the following resource model: - - - [Region][google.shopping.merchant.accounts.v1main.Region] - - 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[RegionsServiceRestInterceptor] = 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 RegionsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateRegion(_BaseRegionsServiceRestTransport._BaseCreateRegion, RegionsServiceRestStub): - def __hash__(self): - return hash("RegionsServiceRestTransport.CreateRegion") - - @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: regions.CreateRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.Region: - r"""Call the create region method over HTTP. - - Args: - request (~.regions.CreateRegionRequest): - The request object. Request message for the ``CreateRegion`` 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: - ~.regions.Region: - Represents a geographic region that you can use as a - target with both the ``RegionalInventory`` and - ``ShippingSettings`` services. You can define regions as - collections of either postal codes or, in some - countries, using predefined geotargets. For more - information, see `Set up - regions `__ - for more information. - - """ - - http_options = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_http_options() - - request, metadata = self._interceptor.pre_create_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_transcoded_request(http_options, request) - - body = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.CreateRegion", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "CreateRegion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionsServiceRestTransport._CreateRegion._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 = regions.Region() - pb_resp = regions.Region.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_region(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_region_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regions.Region.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.accounts_v1beta.RegionsServiceClient.create_region", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "CreateRegion", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteRegion(_BaseRegionsServiceRestTransport._BaseDeleteRegion, RegionsServiceRestStub): - def __hash__(self): - return hash("RegionsServiceRestTransport.DeleteRegion") - - @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: regions.DeleteRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete region method over HTTP. - - Args: - request (~.regions.DeleteRegionRequest): - The request object. Request message for the ``DeleteRegion`` 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 = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_http_options() - - request, metadata = self._interceptor.pre_delete_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.DeleteRegion", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "DeleteRegion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionsServiceRestTransport._DeleteRegion._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 _GetRegion(_BaseRegionsServiceRestTransport._BaseGetRegion, RegionsServiceRestStub): - def __hash__(self): - return hash("RegionsServiceRestTransport.GetRegion") - - @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: regions.GetRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.Region: - r"""Call the get region method over HTTP. - - Args: - request (~.regions.GetRegionRequest): - The request object. Request message for the ``GetRegion`` 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: - ~.regions.Region: - Represents a geographic region that you can use as a - target with both the ``RegionalInventory`` and - ``ShippingSettings`` services. You can define regions as - collections of either postal codes or, in some - countries, using predefined geotargets. For more - information, see `Set up - regions `__ - for more information. - - """ - - http_options = _BaseRegionsServiceRestTransport._BaseGetRegion._get_http_options() - - request, metadata = self._interceptor.pre_get_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseGetRegion._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseGetRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.GetRegion", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "GetRegion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionsServiceRestTransport._GetRegion._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 = regions.Region() - pb_resp = regions.Region.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_region(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_region_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regions.Region.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.accounts_v1beta.RegionsServiceClient.get_region", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "GetRegion", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListRegions(_BaseRegionsServiceRestTransport._BaseListRegions, RegionsServiceRestStub): - def __hash__(self): - return hash("RegionsServiceRestTransport.ListRegions") - - @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: regions.ListRegionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.ListRegionsResponse: - r"""Call the list regions method over HTTP. - - Args: - request (~.regions.ListRegionsRequest): - The request object. Request message for the ``ListRegions`` 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: - ~.regions.ListRegionsResponse: - Response message for the ``ListRegions`` method. - """ - - http_options = _BaseRegionsServiceRestTransport._BaseListRegions._get_http_options() - - request, metadata = self._interceptor.pre_list_regions(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseListRegions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseListRegions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.ListRegions", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "ListRegions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionsServiceRestTransport._ListRegions._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 = regions.ListRegionsResponse() - pb_resp = regions.ListRegionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_regions(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_regions_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regions.ListRegionsResponse.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.accounts_v1beta.RegionsServiceClient.list_regions", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "ListRegions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateRegion(_BaseRegionsServiceRestTransport._BaseUpdateRegion, RegionsServiceRestStub): - def __hash__(self): - return hash("RegionsServiceRestTransport.UpdateRegion") - - @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: regions.UpdateRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.Region: - r"""Call the update region method over HTTP. - - Args: - request (~.regions.UpdateRegionRequest): - The request object. Request message for the ``UpdateRegion`` 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: - ~.regions.Region: - Represents a geographic region that you can use as a - target with both the ``RegionalInventory`` and - ``ShippingSettings`` services. You can define regions as - collections of either postal codes or, in some - countries, using predefined geotargets. For more - information, see `Set up - regions `__ - for more information. - - """ - - http_options = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_http_options() - - request, metadata = self._interceptor.pre_update_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_transcoded_request(http_options, request) - - body = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.RegionsServiceClient.UpdateRegion", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "UpdateRegion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = RegionsServiceRestTransport._UpdateRegion._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 = regions.Region() - pb_resp = regions.Region.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_region(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_region_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = regions.Region.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.accounts_v1beta.RegionsServiceClient.update_region", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "rpcName": "UpdateRegion", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - regions.Region]: - # 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._CreateRegion(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - 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._DeleteRegion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_region(self) -> Callable[ - [regions.GetRegionRequest], - regions.Region]: - # 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._GetRegion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - regions.ListRegionsResponse]: - # 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._ListRegions(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - regions.Region]: - # 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._UpdateRegion(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RegionsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py deleted file mode 100644 index 31c30d3d35e3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/rest_base.py +++ /dev/null @@ -1,297 +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 RegionsServiceTransport, 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_accounts_v1beta.types import regions - - -class _BaseRegionsServiceRestTransport(RegionsServiceTransport): - """Base REST backend transport for RegionsService. - - 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 _BaseCreateRegion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "regionId" : "", } - - @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': '/accounts/v1beta/{parent=accounts/*}/regions', - 'body': 'region', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regions.CreateRegionRequest.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(_BaseRegionsServiceRestTransport._BaseCreateRegion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteRegion: - 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': '/accounts/v1beta/{name=accounts/*/regions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regions.DeleteRegionRequest.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(_BaseRegionsServiceRestTransport._BaseDeleteRegion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetRegion: - 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': '/accounts/v1beta/{name=accounts/*/regions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regions.GetRegionRequest.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(_BaseRegionsServiceRestTransport._BaseGetRegion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListRegions: - 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': '/accounts/v1beta/{parent=accounts/*}/regions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regions.ListRegionsRequest.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(_BaseRegionsServiceRestTransport._BaseListRegions._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateRegion: - 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': 'patch', - 'uri': '/accounts/v1beta/{region.name=accounts/*/regions/*}', - 'body': 'region', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = regions.UpdateRegionRequest.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(_BaseRegionsServiceRestTransport._BaseUpdateRegion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseRegionsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/__init__.py deleted file mode 100644 index 023e41c50a7f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_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 ShippingSettingsServiceClient -from .async_client import ShippingSettingsServiceAsyncClient - -__all__ = ( - 'ShippingSettingsServiceClient', - 'ShippingSettingsServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py deleted file mode 100644 index 220f282c9e2d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/async_client.py +++ /dev/null @@ -1,461 +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_accounts_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_accounts_v1beta.types import shippingsettings -from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport -from .client import ShippingSettingsServiceClient - -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 ShippingSettingsServiceAsyncClient: - """Service to get method call shipping setting information per - Merchant API method. - """ - - _client: ShippingSettingsServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - - shipping_settings_path = staticmethod(ShippingSettingsServiceClient.shipping_settings_path) - parse_shipping_settings_path = staticmethod(ShippingSettingsServiceClient.parse_shipping_settings_path) - common_billing_account_path = staticmethod(ShippingSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ShippingSettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ShippingSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ShippingSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ShippingSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ShippingSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ShippingSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(ShippingSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(ShippingSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(ShippingSettingsServiceClient.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: - ShippingSettingsServiceAsyncClient: The constructed client. - """ - return ShippingSettingsServiceClient.from_service_account_info.__func__(ShippingSettingsServiceAsyncClient, 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: - ShippingSettingsServiceAsyncClient: The constructed client. - """ - return ShippingSettingsServiceClient.from_service_account_file.__func__(ShippingSettingsServiceAsyncClient, 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 ShippingSettingsServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ShippingSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ShippingSettingsServiceTransport: 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 = ShippingSettingsServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the shipping settings 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,ShippingSettingsServiceTransport,Callable[..., ShippingSettingsServiceTransport]]]): - 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 ShippingSettingsServiceTransport 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 = ShippingSettingsServiceClient( - 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.accounts_v1beta.ShippingSettingsServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "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.accounts.v1beta.ShippingSettingsService", - "credentialsType": None, - } - ) - - async def get_shipping_settings(self, - request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: - r"""Retrieve shipping setting information. - - .. 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_accounts_v1beta - - async def sample_get_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetShippingSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_shipping_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest, dict]]): - The request object. Request message for the ``GetShippingSetting`` method. - name (:class:`str`): - Required. The name of the shipping setting to retrieve. - Format: ``accounts/{account}/shippingsetting`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.ShippingSettings: - The merchant account's [shipping - setting](\ https://support.google.com/merchants/answer/6069284). - - """ - # 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, shippingsettings.GetShippingSettingsRequest): - request = shippingsettings.GetShippingSettingsRequest(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.get_shipping_settings] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def insert_shipping_settings(self, - request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: - r"""Replace the shipping setting of a merchant with the - request shipping setting. Executing this method requires - admin access. - - .. 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_accounts_v1beta - - async def sample_insert_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() - - # Initialize request argument(s) - shipping_setting = merchant_accounts_v1beta.ShippingSettings() - shipping_setting.etag = "etag_value" - - request = merchant_accounts_v1beta.InsertShippingSettingsRequest( - parent="parent_value", - shipping_setting=shipping_setting, - ) - - # Make the request - response = await client.insert_shipping_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest, dict]]): - The request object. Request message for the ``InsertShippingSetting`` - 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_accounts_v1beta.types.ShippingSettings: - The merchant account's [shipping - setting](\ https://support.google.com/merchants/answer/6069284). - - """ - # 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, shippingsettings.InsertShippingSettingsRequest): - request = shippingsettings.InsertShippingSettingsRequest(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_shipping_settings] - - # 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 __aenter__(self) -> "ShippingSettingsServiceAsyncClient": - 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__ = ( - "ShippingSettingsServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py deleted file mode 100644 index b51db3bd4107..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/client.py +++ /dev/null @@ -1,821 +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_accounts_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_accounts_v1beta.types import shippingsettings -from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ShippingSettingsServiceGrpcTransport -from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport -from .transports.rest import ShippingSettingsServiceRestTransport - - -class ShippingSettingsServiceClientMeta(type): - """Metaclass for the ShippingSettingsService 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[ShippingSettingsServiceTransport]] - _transport_registry["grpc"] = ShippingSettingsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ShippingSettingsServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ShippingSettingsServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ShippingSettingsServiceTransport]: - """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 ShippingSettingsServiceClient(metaclass=ShippingSettingsServiceClientMeta): - """Service to get method call shipping setting information per - Merchant API method. - """ - - @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: - ShippingSettingsServiceClient: 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: - ShippingSettingsServiceClient: 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) -> ShippingSettingsServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ShippingSettingsServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def shipping_settings_path(account: str,) -> str: - """Returns a fully-qualified shipping_settings string.""" - return "accounts/{account}/shippingSettings".format(account=account, ) - - @staticmethod - def parse_shipping_settings_path(path: str) -> Dict[str,str]: - """Parses a shipping_settings path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/shippingSettings$", 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 = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient._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, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the shipping settings 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,ShippingSettingsServiceTransport,Callable[..., ShippingSettingsServiceTransport]]]): - 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 ShippingSettingsServiceTransport 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 = ShippingSettingsServiceClient._read_environment_variables() - self._client_cert_source = ShippingSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ShippingSettingsServiceClient._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, ShippingSettingsServiceTransport) - if transport_provided: - # transport is a ShippingSettingsServiceTransport 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(ShippingSettingsServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ShippingSettingsServiceClient._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[ShippingSettingsServiceTransport], Callable[..., ShippingSettingsServiceTransport]] = ( - ShippingSettingsServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ShippingSettingsServiceTransport], 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.accounts_v1beta.ShippingSettingsServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "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.accounts.v1beta.ShippingSettingsService", - "credentialsType": None, - } - ) - - def get_shipping_settings(self, - request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: - r"""Retrieve shipping setting information. - - .. 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_accounts_v1beta - - def sample_get_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetShippingSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_shipping_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest, dict]): - The request object. Request message for the ``GetShippingSetting`` method. - name (str): - Required. The name of the shipping setting to retrieve. - Format: ``accounts/{account}/shippingsetting`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.ShippingSettings: - The merchant account's [shipping - setting](\ https://support.google.com/merchants/answer/6069284). - - """ - # 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, shippingsettings.GetShippingSettingsRequest): - request = shippingsettings.GetShippingSettingsRequest(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.get_shipping_settings] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def insert_shipping_settings(self, - request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: - r"""Replace the shipping setting of a merchant with the - request shipping setting. Executing this method requires - admin access. - - .. 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_accounts_v1beta - - def sample_insert_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceClient() - - # Initialize request argument(s) - shipping_setting = merchant_accounts_v1beta.ShippingSettings() - shipping_setting.etag = "etag_value" - - request = merchant_accounts_v1beta.InsertShippingSettingsRequest( - parent="parent_value", - shipping_setting=shipping_setting, - ) - - # Make the request - response = client.insert_shipping_settings(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest, dict]): - The request object. Request message for the ``InsertShippingSetting`` - 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_accounts_v1beta.types.ShippingSettings: - The merchant account's [shipping - setting](\ https://support.google.com/merchants/answer/6069284). - - """ - # 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, shippingsettings.InsertShippingSettingsRequest): - request = shippingsettings.InsertShippingSettingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert_shipping_settings] - - # 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 __enter__(self) -> "ShippingSettingsServiceClient": - 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__ = ( - "ShippingSettingsServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst deleted file mode 100644 index a638b7b9035f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ShippingSettingsServiceTransport` is the ABC for all transports. -- public child `ShippingSettingsServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ShippingSettingsServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseShippingSettingsServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ShippingSettingsServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/__init__.py deleted file mode 100644 index cbb84e1b0a91..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_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 ShippingSettingsServiceTransport -from .grpc import ShippingSettingsServiceGrpcTransport -from .grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport -from .rest import ShippingSettingsServiceRestTransport -from .rest import ShippingSettingsServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ShippingSettingsServiceTransport]] -_transport_registry['grpc'] = ShippingSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ShippingSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ShippingSettingsServiceRestTransport - -__all__ = ( - 'ShippingSettingsServiceTransport', - 'ShippingSettingsServiceGrpcTransport', - 'ShippingSettingsServiceGrpcAsyncIOTransport', - 'ShippingSettingsServiceRestTransport', - 'ShippingSettingsServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py deleted file mode 100644 index f1317fbe2feb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import shippingsettings - -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 ShippingSettingsServiceTransport(abc.ABC): - """Abstract transport class for ShippingSettingsService.""" - - 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.get_shipping_settings: gapic_v1.method.wrap_method( - self.get_shipping_settings, - default_timeout=None, - client_info=client_info, - ), - self.insert_shipping_settings: gapic_v1.method.wrap_method( - self.insert_shipping_settings, - 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 get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - Union[ - shippingsettings.ShippingSettings, - Awaitable[shippingsettings.ShippingSettings] - ]]: - raise NotImplementedError() - - @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - Union[ - shippingsettings.ShippingSettings, - Awaitable[shippingsettings.ShippingSettings] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ShippingSettingsServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py deleted file mode 100644 index c33dd757a185..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc.py +++ /dev/null @@ -1,375 +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.shopping.merchant_accounts_v1beta.types import shippingsettings -from .base import ShippingSettingsServiceTransport, 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.accounts.v1beta.ShippingSettingsService", - "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.accounts.v1beta.ShippingSettingsService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ShippingSettingsServiceGrpcTransport(ShippingSettingsServiceTransport): - """gRPC backend transport for ShippingSettingsService. - - Service to get method call shipping setting information per - Merchant API method. - - 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 get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - shippingsettings.ShippingSettings]: - r"""Return a callable for the get shipping settings method over gRPC. - - Retrieve shipping setting information. - - Returns: - Callable[[~.GetShippingSettingsRequest], - ~.ShippingSettings]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_shipping_settings' not in self._stubs: - self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/GetShippingSettings', - request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, - response_deserializer=shippingsettings.ShippingSettings.deserialize, - ) - return self._stubs['get_shipping_settings'] - - @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - shippingsettings.ShippingSettings]: - r"""Return a callable for the insert shipping settings method over gRPC. - - Replace the shipping setting of a merchant with the - request shipping setting. Executing this method requires - admin access. - - Returns: - Callable[[~.InsertShippingSettingsRequest], - ~.ShippingSettings]: - 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_shipping_settings' not in self._stubs: - self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/InsertShippingSettings', - request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, - response_deserializer=shippingsettings.ShippingSettings.deserialize, - ) - return self._stubs['insert_shipping_settings'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ShippingSettingsServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py deleted file mode 100644 index 09d33b42d7bf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,401 +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.shopping.merchant_accounts_v1beta.types import shippingsettings -from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ShippingSettingsServiceGrpcTransport - -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.accounts.v1beta.ShippingSettingsService", - "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.accounts.v1beta.ShippingSettingsService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ShippingSettingsServiceGrpcAsyncIOTransport(ShippingSettingsServiceTransport): - """gRPC AsyncIO backend transport for ShippingSettingsService. - - Service to get method call shipping setting information per - Merchant API method. - - 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 get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - Awaitable[shippingsettings.ShippingSettings]]: - r"""Return a callable for the get shipping settings method over gRPC. - - Retrieve shipping setting information. - - Returns: - Callable[[~.GetShippingSettingsRequest], - Awaitable[~.ShippingSettings]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_shipping_settings' not in self._stubs: - self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/GetShippingSettings', - request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, - response_deserializer=shippingsettings.ShippingSettings.deserialize, - ) - return self._stubs['get_shipping_settings'] - - @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - Awaitable[shippingsettings.ShippingSettings]]: - r"""Return a callable for the insert shipping settings method over gRPC. - - Replace the shipping setting of a merchant with the - request shipping setting. Executing this method requires - admin access. - - Returns: - Callable[[~.InsertShippingSettingsRequest], - Awaitable[~.ShippingSettings]]: - 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_shipping_settings' not in self._stubs: - self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.ShippingSettingsService/InsertShippingSettings', - request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, - response_deserializer=shippingsettings.ShippingSettings.deserialize, - ) - return self._stubs['insert_shipping_settings'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_shipping_settings: self._wrap_method( - self.get_shipping_settings, - default_timeout=None, - client_info=client_info, - ), - self.insert_shipping_settings: self._wrap_method( - self.insert_shipping_settings, - 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__ = ( - 'ShippingSettingsServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py deleted file mode 100644 index d35cf9ffb93c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest.py +++ /dev/null @@ -1,531 +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.shopping.merchant_accounts_v1beta.types import shippingsettings - - -from .rest_base import _BaseShippingSettingsServiceRestTransport -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 ShippingSettingsServiceRestInterceptor: - """Interceptor for ShippingSettingsService. - - 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 ShippingSettingsServiceRestTransport. - - .. code-block:: python - class MyCustomShippingSettingsServiceInterceptor(ShippingSettingsServiceRestInterceptor): - def pre_get_shipping_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_shipping_settings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_insert_shipping_settings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_insert_shipping_settings(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ShippingSettingsServiceRestTransport(interceptor=MyCustomShippingSettingsServiceInterceptor()) - client = ShippingSettingsServiceClient(transport=transport) - - - """ - def pre_get_shipping_settings(self, request: shippingsettings.GetShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_shipping_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the ShippingSettingsService server. - """ - return request, metadata - - def post_get_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: - """Post-rpc interceptor for get_shipping_settings - - DEPRECATED. Please use the `post_get_shipping_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ShippingSettingsService server but before - it is returned to user code. This `post_get_shipping_settings` interceptor runs - before the `post_get_shipping_settings_with_metadata` interceptor. - """ - return response - - def post_get_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_shipping_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ShippingSettingsService server but before it is returned to user code. - - We recommend only using this `post_get_shipping_settings_with_metadata` - interceptor in new development instead of the `post_get_shipping_settings` interceptor. - When both interceptors are used, this `post_get_shipping_settings_with_metadata` interceptor runs after the - `post_get_shipping_settings` interceptor. The (possibly modified) response returned by - `post_get_shipping_settings` will be passed to - `post_get_shipping_settings_with_metadata`. - """ - return response, metadata - - def pre_insert_shipping_settings(self, request: shippingsettings.InsertShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for insert_shipping_settings - - Override in a subclass to manipulate the request or metadata - before they are sent to the ShippingSettingsService server. - """ - return request, metadata - - def post_insert_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: - """Post-rpc interceptor for insert_shipping_settings - - DEPRECATED. Please use the `post_insert_shipping_settings_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the ShippingSettingsService server but before - it is returned to user code. This `post_insert_shipping_settings` interceptor runs - before the `post_insert_shipping_settings_with_metadata` interceptor. - """ - return response - - def post_insert_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for insert_shipping_settings - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the ShippingSettingsService server but before it is returned to user code. - - We recommend only using this `post_insert_shipping_settings_with_metadata` - interceptor in new development instead of the `post_insert_shipping_settings` interceptor. - When both interceptors are used, this `post_insert_shipping_settings_with_metadata` interceptor runs after the - `post_insert_shipping_settings` interceptor. The (possibly modified) response returned by - `post_insert_shipping_settings` will be passed to - `post_insert_shipping_settings_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class ShippingSettingsServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ShippingSettingsServiceRestInterceptor - - -class ShippingSettingsServiceRestTransport(_BaseShippingSettingsServiceRestTransport): - """REST backend synchronous transport for ShippingSettingsService. - - Service to get method call shipping setting information per - Merchant API method. - - 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[ShippingSettingsServiceRestInterceptor] = 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 ShippingSettingsServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings, ShippingSettingsServiceRestStub): - def __hash__(self): - return hash("ShippingSettingsServiceRestTransport.GetShippingSettings") - - @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: shippingsettings.GetShippingSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> shippingsettings.ShippingSettings: - r"""Call the get shipping settings method over HTTP. - - Args: - request (~.shippingsettings.GetShippingSettingsRequest): - The request object. Request message for the ``GetShippingSetting`` 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: - ~.shippingsettings.ShippingSettings: - The merchant account's `shipping - setting `__. - - """ - - http_options = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_http_options() - - request, metadata = self._interceptor.pre_get_shipping_settings(request, metadata) - transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ShippingSettingsServiceClient.GetShippingSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "rpcName": "GetShippingSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ShippingSettingsServiceRestTransport._GetShippingSettings._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 = shippingsettings.ShippingSettings() - pb_resp = shippingsettings.ShippingSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_shipping_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_shipping_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = shippingsettings.ShippingSettings.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.accounts_v1beta.ShippingSettingsServiceClient.get_shipping_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "rpcName": "GetShippingSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _InsertShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings, ShippingSettingsServiceRestStub): - def __hash__(self): - return hash("ShippingSettingsServiceRestTransport.InsertShippingSettings") - - @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: shippingsettings.InsertShippingSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> shippingsettings.ShippingSettings: - r"""Call the insert shipping settings method over HTTP. - - Args: - request (~.shippingsettings.InsertShippingSettingsRequest): - The request object. Request message for the ``InsertShippingSetting`` - 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: - ~.shippingsettings.ShippingSettings: - The merchant account's `shipping - setting `__. - - """ - - http_options = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_http_options() - - request, metadata = self._interceptor.pre_insert_shipping_settings(request, metadata) - transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_transcoded_request(http_options, request) - - body = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.ShippingSettingsServiceClient.InsertShippingSettings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "rpcName": "InsertShippingSettings", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ShippingSettingsServiceRestTransport._InsertShippingSettings._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 = shippingsettings.ShippingSettings() - pb_resp = shippingsettings.ShippingSettings.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_insert_shipping_settings(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_shipping_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = shippingsettings.ShippingSettings.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.accounts_v1beta.ShippingSettingsServiceClient.insert_shipping_settings", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "rpcName": "InsertShippingSettings", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - shippingsettings.ShippingSettings]: - # 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._GetShippingSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - shippingsettings.ShippingSettings]: - # 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._InsertShippingSettings(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ShippingSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py deleted file mode 100644 index a8043324a71a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/shipping_settings_service/transports/rest_base.py +++ /dev/null @@ -1,175 +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 ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import shippingsettings - - -class _BaseShippingSettingsServiceRestTransport(ShippingSettingsServiceTransport): - """Base REST backend transport for ShippingSettingsService. - - 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 _BaseGetShippingSettings: - 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': '/accounts/v1beta/{name=accounts/*/shippingSettings}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = shippingsettings.GetShippingSettingsRequest.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(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseInsertShippingSettings: - 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': '/accounts/v1beta/{parent=accounts/*}/shippingSettings:insert', - 'body': 'shipping_setting', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = shippingsettings.InsertShippingSettingsRequest.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(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseShippingSettingsServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/__init__.py deleted file mode 100644 index c0461009811b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_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 TermsOfServiceAgreementStateServiceClient -from .async_client import TermsOfServiceAgreementStateServiceAsyncClient - -__all__ = ( - 'TermsOfServiceAgreementStateServiceClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py deleted file mode 100644 index be1a95259efa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/async_client.py +++ /dev/null @@ -1,536 +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_accounts_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_accounts_v1beta.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1beta.types import termsofservicekind -from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport -from .client import TermsOfServiceAgreementStateServiceClient - -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 TermsOfServiceAgreementStateServiceAsyncClient: - """Service to support ``TermsOfServiceAgreementState`` API.""" - - _client: TermsOfServiceAgreementStateServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.account_path) - parse_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_account_path) - terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_path) - parse_terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path) - terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path) - parse_terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path) - common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_organization_path) - common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_project_path) - parse_common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_project_path) - common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_location_path) - parse_common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.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: - TermsOfServiceAgreementStateServiceAsyncClient: The constructed client. - """ - return TermsOfServiceAgreementStateServiceClient.from_service_account_info.__func__(TermsOfServiceAgreementStateServiceAsyncClient, 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: - TermsOfServiceAgreementStateServiceAsyncClient: The constructed client. - """ - return TermsOfServiceAgreementStateServiceClient.from_service_account_file.__func__(TermsOfServiceAgreementStateServiceAsyncClient, 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 TermsOfServiceAgreementStateServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TermsOfServiceAgreementStateServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TermsOfServiceAgreementStateServiceTransport: 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 = TermsOfServiceAgreementStateServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the terms of service agreement state 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,TermsOfServiceAgreementStateServiceTransport,Callable[..., TermsOfServiceAgreementStateServiceTransport]]]): - 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 TermsOfServiceAgreementStateServiceTransport 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 = TermsOfServiceAgreementStateServiceClient( - 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.accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "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.accounts.v1beta.TermsOfServiceAgreementStateService", - "credentialsType": None, - } - ) - - async def get_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - r"""Returns the state of a terms of service agreement. - - .. 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_accounts_v1beta - - async def sample_get_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( - name="name_value", - ) - - # Make the request - response = await client.get_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest, dict]]): - The request object. Request message for the - ``GetTermsOfServiceAgreementState`` method. - name (:class:`str`): - Required. The resource name of the terms of service - version. Format: - ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` - The identifier format is: - ``{TermsOfServiceKind}-{country}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState: - This resource represents the agreement state for a given account and terms of - service kind. The state is as follows: - - \* If the merchant has accepted a terms of service: - [accepted](TermsOfServiceAggrementState.accepted) - will be populated, otherwise it will be empty \* If - the merchant must sign a terms of service: - [required](TermsOfServiceAggrementState.required) - will be populated, otherwise it will be empty. - - Note that both - [required](TermsOfServiceAggrementState.required) and - [accepted](TermsOfServiceAggrementState.accepted) can - be present. In this case the accepted terms of - services will have an expiration date set in the - [valid_until](Accepted.valid_until) field. The - required terms of services need to be accepted before - valid_until in order for the account to continue - having a valid agreement. When accepting new terms of - services we expect 3Ps to display the text associated - with the given terms of service agreement (the url to - the file containing the text is added in the Required - message below as - [tos_file_uri](Accepted.tos_file_uri). The actual - acceptance of the terms of service is done by calling - accept on the [TermsOfService](TermsOfService) - resource. - - """ - # 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, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(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.get_terms_of_service_agreement_state] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def retrieve_for_application_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - r"""Retrieves the state of the agreement for the - application terms of service. - - .. 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_accounts_v1beta - - async def sample_retrieve_for_application_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent="parent_value", - ) - - # Make the request - response = await client.retrieve_for_application_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest, dict]]): - The request object. Request message for the - ``RetrieveForApplicationTermsOfServiceAgreementState`` - method. - parent (:class:`str`): - Required. The account for which to get a - TermsOfServiceAgreementState Format: - ``accounts/{account}`` - - 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_accounts_v1beta.types.TermsOfServiceAgreementState: - This resource represents the agreement state for a given account and terms of - service kind. The state is as follows: - - \* If the merchant has accepted a terms of service: - [accepted](TermsOfServiceAggrementState.accepted) - will be populated, otherwise it will be empty \* If - the merchant must sign a terms of service: - [required](TermsOfServiceAggrementState.required) - will be populated, otherwise it will be empty. - - Note that both - [required](TermsOfServiceAggrementState.required) and - [accepted](TermsOfServiceAggrementState.accepted) can - be present. In this case the accepted terms of - services will have an expiration date set in the - [valid_until](Accepted.valid_until) field. The - required terms of services need to be accepted before - valid_until in order for the account to continue - having a valid agreement. When accepting new terms of - services we expect 3Ps to display the text associated - with the given terms of service agreement (the url to - the file containing the text is added in the Required - message below as - [tos_file_uri](Accepted.tos_file_uri). The actual - acceptance of the terms of service is done by calling - accept on the [TermsOfService](TermsOfService) - resource. - - """ - # 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, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(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.retrieve_for_application_terms_of_service_agreement_state] - - # 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 __aenter__(self) -> "TermsOfServiceAgreementStateServiceAsyncClient": - 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__ = ( - "TermsOfServiceAgreementStateServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py deleted file mode 100644 index 2addf61b12a1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/client.py +++ /dev/null @@ -1,913 +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_accounts_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_accounts_v1beta.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1beta.types import termsofservicekind -from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TermsOfServiceAgreementStateServiceGrpcTransport -from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport -from .transports.rest import TermsOfServiceAgreementStateServiceRestTransport - - -class TermsOfServiceAgreementStateServiceClientMeta(type): - """Metaclass for the TermsOfServiceAgreementStateService 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[TermsOfServiceAgreementStateServiceTransport]] - _transport_registry["grpc"] = TermsOfServiceAgreementStateServiceGrpcTransport - _transport_registry["grpc_asyncio"] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport - _transport_registry["rest"] = TermsOfServiceAgreementStateServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TermsOfServiceAgreementStateServiceTransport]: - """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 TermsOfServiceAgreementStateServiceClient(metaclass=TermsOfServiceAgreementStateServiceClientMeta): - """Service to support ``TermsOfServiceAgreementState`` API.""" - - @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: - TermsOfServiceAgreementStateServiceClient: 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: - TermsOfServiceAgreementStateServiceClient: 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) -> TermsOfServiceAgreementStateServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TermsOfServiceAgreementStateServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def terms_of_service_path(version: str,) -> str: - """Returns a fully-qualified terms_of_service string.""" - return "termsOfService/{version}".format(version=version, ) - - @staticmethod - def parse_terms_of_service_path(path: str) -> Dict[str,str]: - """Parses a terms_of_service path into its component segments.""" - m = re.match(r"^termsOfService/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def terms_of_service_agreement_state_path(account: str,identifier: str,) -> str: - """Returns a fully-qualified terms_of_service_agreement_state string.""" - return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) - - @staticmethod - def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str,str]: - """Parses a terms_of_service_agreement_state path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?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 = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = TermsOfServiceAgreementStateServiceClient._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 = TermsOfServiceAgreementStateServiceClient._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, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the terms of service agreement state 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,TermsOfServiceAgreementStateServiceTransport,Callable[..., TermsOfServiceAgreementStateServiceTransport]]]): - 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 TermsOfServiceAgreementStateServiceTransport 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 = TermsOfServiceAgreementStateServiceClient._read_environment_variables() - self._client_cert_source = TermsOfServiceAgreementStateServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = TermsOfServiceAgreementStateServiceClient._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, TermsOfServiceAgreementStateServiceTransport) - if transport_provided: - # transport is a TermsOfServiceAgreementStateServiceTransport 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(TermsOfServiceAgreementStateServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - TermsOfServiceAgreementStateServiceClient._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[TermsOfServiceAgreementStateServiceTransport], Callable[..., TermsOfServiceAgreementStateServiceTransport]] = ( - TermsOfServiceAgreementStateServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., TermsOfServiceAgreementStateServiceTransport], 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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "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.accounts.v1beta.TermsOfServiceAgreementStateService", - "credentialsType": None, - } - ) - - def get_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - r"""Returns the state of a terms of service agreement. - - .. 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_accounts_v1beta - - def sample_get_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( - name="name_value", - ) - - # Make the request - response = client.get_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest, dict]): - The request object. Request message for the - ``GetTermsOfServiceAgreementState`` method. - name (str): - Required. The resource name of the terms of service - version. Format: - ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` - The identifier format is: - ``{TermsOfServiceKind}-{country}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState: - This resource represents the agreement state for a given account and terms of - service kind. The state is as follows: - - \* If the merchant has accepted a terms of service: - [accepted](TermsOfServiceAggrementState.accepted) - will be populated, otherwise it will be empty \* If - the merchant must sign a terms of service: - [required](TermsOfServiceAggrementState.required) - will be populated, otherwise it will be empty. - - Note that both - [required](TermsOfServiceAggrementState.required) and - [accepted](TermsOfServiceAggrementState.accepted) can - be present. In this case the accepted terms of - services will have an expiration date set in the - [valid_until](Accepted.valid_until) field. The - required terms of services need to be accepted before - valid_until in order for the account to continue - having a valid agreement. When accepting new terms of - services we expect 3Ps to display the text associated - with the given terms of service agreement (the url to - the file containing the text is added in the Required - message below as - [tos_file_uri](Accepted.tos_file_uri). The actual - acceptance of the terms of service is done by calling - accept on the [TermsOfService](TermsOfService) - resource. - - """ - # 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, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(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.get_terms_of_service_agreement_state] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def retrieve_for_application_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - r"""Retrieves the state of the agreement for the - application terms of service. - - .. 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_accounts_v1beta - - def sample_retrieve_for_application_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent="parent_value", - ) - - # Make the request - response = client.retrieve_for_application_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest, dict]): - The request object. Request message for the - ``RetrieveForApplicationTermsOfServiceAgreementState`` - method. - parent (str): - Required. The account for which to get a - TermsOfServiceAgreementState Format: - ``accounts/{account}`` - - 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_accounts_v1beta.types.TermsOfServiceAgreementState: - This resource represents the agreement state for a given account and terms of - service kind. The state is as follows: - - \* If the merchant has accepted a terms of service: - [accepted](TermsOfServiceAggrementState.accepted) - will be populated, otherwise it will be empty \* If - the merchant must sign a terms of service: - [required](TermsOfServiceAggrementState.required) - will be populated, otherwise it will be empty. - - Note that both - [required](TermsOfServiceAggrementState.required) and - [accepted](TermsOfServiceAggrementState.accepted) can - be present. In this case the accepted terms of - services will have an expiration date set in the - [valid_until](Accepted.valid_until) field. The - required terms of services need to be accepted before - valid_until in order for the account to continue - having a valid agreement. When accepting new terms of - services we expect 3Ps to display the text associated - with the given terms of service agreement (the url to - the file containing the text is added in the Required - message below as - [tos_file_uri](Accepted.tos_file_uri). The actual - acceptance of the terms of service is done by calling - accept on the [TermsOfService](TermsOfService) - resource. - - """ - # 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, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(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.retrieve_for_application_terms_of_service_agreement_state] - - # 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 __enter__(self) -> "TermsOfServiceAgreementStateServiceClient": - 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__ = ( - "TermsOfServiceAgreementStateServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst deleted file mode 100644 index 344858fa2eb5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`TermsOfServiceAgreementStateServiceTransport` is the ABC for all transports. -- public child `TermsOfServiceAgreementStateServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseTermsOfServiceAgreementStateServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `TermsOfServiceAgreementStateServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/__init__.py deleted file mode 100644 index 3e5e8db05323..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_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 TermsOfServiceAgreementStateServiceTransport -from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport -from .grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport -from .rest import TermsOfServiceAgreementStateServiceRestTransport -from .rest import TermsOfServiceAgreementStateServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] -_transport_registry['grpc'] = TermsOfServiceAgreementStateServiceGrpcTransport -_transport_registry['grpc_asyncio'] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport -_transport_registry['rest'] = TermsOfServiceAgreementStateServiceRestTransport - -__all__ = ( - 'TermsOfServiceAgreementStateServiceTransport', - 'TermsOfServiceAgreementStateServiceGrpcTransport', - 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', - 'TermsOfServiceAgreementStateServiceRestTransport', - 'TermsOfServiceAgreementStateServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py deleted file mode 100644 index 949759e97599..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/base.py +++ /dev/null @@ -1,173 +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_accounts_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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate - -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 TermsOfServiceAgreementStateServiceTransport(abc.ABC): - """Abstract transport class for TermsOfServiceAgreementStateService.""" - - 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.get_terms_of_service_agreement_state: gapic_v1.method.wrap_method( - self.get_terms_of_service_agreement_state, - default_timeout=None, - client_info=client_info, - ), - self.retrieve_for_application_terms_of_service_agreement_state: gapic_v1.method.wrap_method( - self.retrieve_for_application_terms_of_service_agreement_state, - 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 get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - Union[ - termsofserviceagreementstate.TermsOfServiceAgreementState, - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] - ]]: - raise NotImplementedError() - - @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - Union[ - termsofserviceagreementstate.TermsOfServiceAgreementState, - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'TermsOfServiceAgreementStateServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py deleted file mode 100644 index b8d2002a1084..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc.py +++ /dev/null @@ -1,375 +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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate -from .base import TermsOfServiceAgreementStateServiceTransport, 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.accounts.v1beta.TermsOfServiceAgreementStateService", - "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.accounts.v1beta.TermsOfServiceAgreementStateService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class TermsOfServiceAgreementStateServiceGrpcTransport(TermsOfServiceAgreementStateServiceTransport): - """gRPC backend transport for TermsOfServiceAgreementStateService. - - Service to support ``TermsOfServiceAgreementState`` API. - - 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 get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: - r"""Return a callable for the get terms of service agreement - state method over gRPC. - - Returns the state of a terms of service agreement. - - Returns: - Callable[[~.GetTermsOfServiceAgreementStateRequest], - ~.TermsOfServiceAgreementState]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_terms_of_service_agreement_state' not in self._stubs: - self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', - request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, - response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, - ) - return self._stubs['get_terms_of_service_agreement_state'] - - @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: - r"""Return a callable for the retrieve for application terms - of service agreement state method over gRPC. - - Retrieves the state of the agreement for the - application terms of service. - - Returns: - Callable[[~.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - ~.TermsOfServiceAgreementState]: - 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 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: - self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', - request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, - response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, - ) - return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TermsOfServiceAgreementStateServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py deleted file mode 100644 index bdab2aaec7b5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,401 +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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate -from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport - -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.accounts.v1beta.TermsOfServiceAgreementStateService", - "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.accounts.v1beta.TermsOfServiceAgreementStateService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport(TermsOfServiceAgreementStateServiceTransport): - """gRPC AsyncIO backend transport for TermsOfServiceAgreementStateService. - - Service to support ``TermsOfServiceAgreementState`` API. - - 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 get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: - r"""Return a callable for the get terms of service agreement - state method over gRPC. - - Returns the state of a terms of service agreement. - - Returns: - Callable[[~.GetTermsOfServiceAgreementStateRequest], - Awaitable[~.TermsOfServiceAgreementState]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_terms_of_service_agreement_state' not in self._stubs: - self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', - request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, - response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, - ) - return self._stubs['get_terms_of_service_agreement_state'] - - @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: - r"""Return a callable for the retrieve for application terms - of service agreement state method over gRPC. - - Retrieves the state of the agreement for the - application terms of service. - - Returns: - Callable[[~.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - Awaitable[~.TermsOfServiceAgreementState]]: - 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 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: - self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', - request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, - response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, - ) - return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_terms_of_service_agreement_state: self._wrap_method( - self.get_terms_of_service_agreement_state, - default_timeout=None, - client_info=client_info, - ), - self.retrieve_for_application_terms_of_service_agreement_state: self._wrap_method( - self.retrieve_for_application_terms_of_service_agreement_state, - 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__ = ( - 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py deleted file mode 100644 index 1f798438960a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest.py +++ /dev/null @@ -1,583 +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.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate - - -from .rest_base import _BaseTermsOfServiceAgreementStateServiceRestTransport -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 TermsOfServiceAgreementStateServiceRestInterceptor: - """Interceptor for TermsOfServiceAgreementStateService. - - 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 TermsOfServiceAgreementStateServiceRestTransport. - - .. code-block:: python - class MyCustomTermsOfServiceAgreementStateServiceInterceptor(TermsOfServiceAgreementStateServiceRestInterceptor): - def pre_get_terms_of_service_agreement_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_terms_of_service_agreement_state(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_retrieve_for_application_terms_of_service_agreement_state(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_retrieve_for_application_terms_of_service_agreement_state(self, response): - logging.log(f"Received response: {response}") - return response - - transport = TermsOfServiceAgreementStateServiceRestTransport(interceptor=MyCustomTermsOfServiceAgreementStateServiceInterceptor()) - client = TermsOfServiceAgreementStateServiceClient(transport=transport) - - - """ - def pre_get_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_terms_of_service_agreement_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the TermsOfServiceAgreementStateService server. - """ - return request, metadata - - def post_get_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - """Post-rpc interceptor for get_terms_of_service_agreement_state - - DEPRECATED. Please use the `post_get_terms_of_service_agreement_state_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the TermsOfServiceAgreementStateService server but before - it is returned to user code. This `post_get_terms_of_service_agreement_state` interceptor runs - before the `post_get_terms_of_service_agreement_state_with_metadata` interceptor. - """ - return response - - def post_get_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_terms_of_service_agreement_state - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the TermsOfServiceAgreementStateService server but before it is returned to user code. - - We recommend only using this `post_get_terms_of_service_agreement_state_with_metadata` - interceptor in new development instead of the `post_get_terms_of_service_agreement_state` interceptor. - When both interceptors are used, this `post_get_terms_of_service_agreement_state_with_metadata` interceptor runs after the - `post_get_terms_of_service_agreement_state` interceptor. The (possibly modified) response returned by - `post_get_terms_of_service_agreement_state` will be passed to - `post_get_terms_of_service_agreement_state_with_metadata`. - """ - return response, metadata - - def pre_retrieve_for_application_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state - - Override in a subclass to manipulate the request or metadata - before they are sent to the TermsOfServiceAgreementStateService server. - """ - return request, metadata - - def post_retrieve_for_application_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state - - DEPRECATED. Please use the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the TermsOfServiceAgreementStateService server but before - it is returned to user code. This `post_retrieve_for_application_terms_of_service_agreement_state` interceptor runs - before the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` interceptor. - """ - return response - - def post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the TermsOfServiceAgreementStateService server but before it is returned to user code. - - We recommend only using this `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` - interceptor in new development instead of the `post_retrieve_for_application_terms_of_service_agreement_state` interceptor. - When both interceptors are used, this `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` interceptor runs after the - `post_retrieve_for_application_terms_of_service_agreement_state` interceptor. The (possibly modified) response returned by - `post_retrieve_for_application_terms_of_service_agreement_state` will be passed to - `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class TermsOfServiceAgreementStateServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: TermsOfServiceAgreementStateServiceRestInterceptor - - -class TermsOfServiceAgreementStateServiceRestTransport(_BaseTermsOfServiceAgreementStateServiceRestTransport): - """REST backend synchronous transport for TermsOfServiceAgreementStateService. - - Service to support ``TermsOfServiceAgreementState`` API. - - 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[TermsOfServiceAgreementStateServiceRestInterceptor] = 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 TermsOfServiceAgreementStateServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): - def __hash__(self): - return hash("TermsOfServiceAgreementStateServiceRestTransport.GetTermsOfServiceAgreementState") - - @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: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - r"""Call the get terms of service - agreement state method over HTTP. - - Args: - request (~.termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - The request object. Request message for the - ``GetTermsOfServiceAgreementState`` 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: - ~.termsofserviceagreementstate.TermsOfServiceAgreementState: - This resource represents the agreement state for a given - account and terms of service kind. The state is as - follows: - - - If the merchant has accepted a terms of service: - `accepted `__ - will be populated, otherwise it will be empty - - If the merchant must sign a terms of service: - `required `__ - will be populated, otherwise it will be empty. - - Note that both - `required `__ and - `accepted `__ can - be present. In this case the ``accepted`` terms of - services will have an expiration date set in the - `valid_until `__ field. The - ``required`` terms of services need to be accepted - before ``valid_until`` in order for the account to - continue having a valid agreement. When accepting new - terms of services we expect 3Ps to display the text - associated with the given terms of service agreement - (the url to the file containing the text is added in the - Required message below as - `tos_file_uri `__. The actual - acceptance of the terms of service is done by calling - accept on the `TermsOfService `__ - resource. - - """ - - http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_http_options() - - request, metadata = self._interceptor.pre_get_terms_of_service_agreement_state(request, metadata) - transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.GetTermsOfServiceAgreementState", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "rpcName": "GetTermsOfServiceAgreementState", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = TermsOfServiceAgreementStateServiceRestTransport._GetTermsOfServiceAgreementState._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 = termsofserviceagreementstate.TermsOfServiceAgreementState() - pb_resp = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_terms_of_service_agreement_state(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_terms_of_service_agreement_state_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "rpcName": "GetTermsOfServiceAgreementState", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _RetrieveForApplicationTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): - def __hash__(self): - return hash("TermsOfServiceAgreementStateServiceRestTransport.RetrieveForApplicationTermsOfServiceAgreementState") - - @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: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: - r"""Call the retrieve for application - terms of service agreement state method over HTTP. - - Args: - request (~.termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - The request object. Request message for the - ``RetrieveForApplicationTermsOfServiceAgreementState`` - 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: - ~.termsofserviceagreementstate.TermsOfServiceAgreementState: - This resource represents the agreement state for a given - account and terms of service kind. The state is as - follows: - - - If the merchant has accepted a terms of service: - `accepted `__ - will be populated, otherwise it will be empty - - If the merchant must sign a terms of service: - `required `__ - will be populated, otherwise it will be empty. - - Note that both - `required `__ and - `accepted `__ can - be present. In this case the ``accepted`` terms of - services will have an expiration date set in the - `valid_until `__ field. The - ``required`` terms of services need to be accepted - before ``valid_until`` in order for the account to - continue having a valid agreement. When accepting new - terms of services we expect 3Ps to display the text - associated with the given terms of service agreement - (the url to the file containing the text is added in the - Required message below as - `tos_file_uri `__. The actual - acceptance of the terms of service is done by calling - accept on the `TermsOfService `__ - resource. - - """ - - http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_http_options() - - request, metadata = self._interceptor.pre_retrieve_for_application_terms_of_service_agreement_state(request, metadata) - transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.RetrieveForApplicationTermsOfServiceAgreementState", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = TermsOfServiceAgreementStateServiceRestTransport._RetrieveForApplicationTermsOfServiceAgreementState._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 = termsofserviceagreementstate.TermsOfServiceAgreementState() - pb_resp = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1beta.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: - # 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._GetTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore - - @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: - # 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._RetrieveForApplicationTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'TermsOfServiceAgreementStateServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py deleted file mode 100644 index 875305eb1d7c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_agreement_state_service/transports/rest_base.py +++ /dev/null @@ -1,165 +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 TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate - - -class _BaseTermsOfServiceAgreementStateServiceRestTransport(TermsOfServiceAgreementStateServiceTransport): - """Base REST backend transport for TermsOfServiceAgreementStateService. - - 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 _BaseGetTermsOfServiceAgreementState: - 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': '/accounts/v1beta/{name=accounts/*/termsOfServiceAgreementStates/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRetrieveForApplicationTermsOfServiceAgreementState: - 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': '/accounts/v1beta/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseTermsOfServiceAgreementStateServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/__init__.py deleted file mode 100644 index 7bfe24f4bb51..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_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 TermsOfServiceServiceClient -from .async_client import TermsOfServiceServiceAsyncClient - -__all__ = ( - 'TermsOfServiceServiceClient', - 'TermsOfServiceServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py deleted file mode 100644 index cf45eb70297a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/async_client.py +++ /dev/null @@ -1,543 +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_accounts_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_accounts_v1beta.types import termsofservice -from google.shopping.merchant_accounts_v1beta.types import termsofservicekind -from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport -from .client import TermsOfServiceServiceClient - -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 TermsOfServiceServiceAsyncClient: - """Service to support ``TermsOfService`` API.""" - - _client: TermsOfServiceServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = TermsOfServiceServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(TermsOfServiceServiceClient.account_path) - parse_account_path = staticmethod(TermsOfServiceServiceClient.parse_account_path) - terms_of_service_path = staticmethod(TermsOfServiceServiceClient.terms_of_service_path) - parse_terms_of_service_path = staticmethod(TermsOfServiceServiceClient.parse_terms_of_service_path) - common_billing_account_path = staticmethod(TermsOfServiceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TermsOfServiceServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TermsOfServiceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(TermsOfServiceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(TermsOfServiceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(TermsOfServiceServiceClient.parse_common_organization_path) - common_project_path = staticmethod(TermsOfServiceServiceClient.common_project_path) - parse_common_project_path = staticmethod(TermsOfServiceServiceClient.parse_common_project_path) - common_location_path = staticmethod(TermsOfServiceServiceClient.common_location_path) - parse_common_location_path = staticmethod(TermsOfServiceServiceClient.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: - TermsOfServiceServiceAsyncClient: The constructed client. - """ - return TermsOfServiceServiceClient.from_service_account_info.__func__(TermsOfServiceServiceAsyncClient, 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: - TermsOfServiceServiceAsyncClient: The constructed client. - """ - return TermsOfServiceServiceClient.from_service_account_file.__func__(TermsOfServiceServiceAsyncClient, 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 TermsOfServiceServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> TermsOfServiceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TermsOfServiceServiceTransport: 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 = TermsOfServiceServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the terms of service 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,TermsOfServiceServiceTransport,Callable[..., TermsOfServiceServiceTransport]]]): - 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 TermsOfServiceServiceTransport 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 = TermsOfServiceServiceClient( - 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.accounts_v1beta.TermsOfServiceServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "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.accounts.v1beta.TermsOfServiceService", - "credentialsType": None, - } - ) - - async def get_terms_of_service(self, - request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: - r"""Retrieves the ``TermsOfService`` associated with the provided - version. - - .. 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_accounts_v1beta - - async def sample_get_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_terms_of_service(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest, dict]]): - The request object. Request message for the ``GetTermsOfService`` method. - name (:class:`str`): - Required. The resource name of the terms of service - version. Format: ``termsOfService/{version}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.TermsOfService: - A TermsOfService. - """ - # 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, termsofservice.GetTermsOfServiceRequest): - request = termsofservice.GetTermsOfServiceRequest(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.get_terms_of_service] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def retrieve_latest_terms_of_service(self, - request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: - r"""Retrieves the latest version of the ``TermsOfService`` for a - given ``kind`` and ``region_code``. - - .. 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_accounts_v1beta - - async def sample_retrieve_latest_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( - region_code="region_code_value", - kind="MERCHANT_CENTER", - ) - - # Make the request - response = await client.retrieve_latest_terms_of_service(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest, dict]]): - The request object. Request message for the ``RetrieveLatestTermsOfService`` - 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_accounts_v1beta.types.TermsOfService: - A TermsOfService. - """ - # 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, termsofservice.RetrieveLatestTermsOfServiceRequest): - request = termsofservice.RetrieveLatestTermsOfServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.retrieve_latest_terms_of_service] - - # 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 accept_terms_of_service(self, - request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, - *, - name: 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"""Accepts a ``TermsOfService``. Executing this method requires - admin access. - - .. 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_accounts_v1beta - - async def sample_accept_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( - name="name_value", - account="account_value", - region_code="region_code_value", - ) - - # Make the request - await client.accept_terms_of_service(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest, dict]]): - The request object. Request message for the ``AcceptTermsOfService`` method. - name (:class:`str`): - Required. The resource name of the terms of service - version. Format: ``termsOfService/{version}`` - - 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, termsofservice.AcceptTermsOfServiceRequest): - request = termsofservice.AcceptTermsOfServiceRequest(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.accept_terms_of_service] - - # 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) -> "TermsOfServiceServiceAsyncClient": - 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__ = ( - "TermsOfServiceServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py deleted file mode 100644 index 4df5b0c85e33..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/client.py +++ /dev/null @@ -1,911 +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_accounts_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_accounts_v1beta.types import termsofservice -from google.shopping.merchant_accounts_v1beta.types import termsofservicekind -from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import TermsOfServiceServiceGrpcTransport -from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport -from .transports.rest import TermsOfServiceServiceRestTransport - - -class TermsOfServiceServiceClientMeta(type): - """Metaclass for the TermsOfServiceService 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[TermsOfServiceServiceTransport]] - _transport_registry["grpc"] = TermsOfServiceServiceGrpcTransport - _transport_registry["grpc_asyncio"] = TermsOfServiceServiceGrpcAsyncIOTransport - _transport_registry["rest"] = TermsOfServiceServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TermsOfServiceServiceTransport]: - """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 TermsOfServiceServiceClient(metaclass=TermsOfServiceServiceClientMeta): - """Service to support ``TermsOfService`` API.""" - - @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: - TermsOfServiceServiceClient: 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: - TermsOfServiceServiceClient: 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) -> TermsOfServiceServiceTransport: - """Returns the transport used by the client instance. - - Returns: - TermsOfServiceServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def terms_of_service_path(version: str,) -> str: - """Returns a fully-qualified terms_of_service string.""" - return "termsOfService/{version}".format(version=version, ) - - @staticmethod - def parse_terms_of_service_path(path: str) -> Dict[str,str]: - """Parses a terms_of_service path into its component segments.""" - m = re.match(r"^termsOfService/(?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 = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient._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, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the terms of service 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,TermsOfServiceServiceTransport,Callable[..., TermsOfServiceServiceTransport]]]): - 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 TermsOfServiceServiceTransport 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 = TermsOfServiceServiceClient._read_environment_variables() - self._client_cert_source = TermsOfServiceServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = TermsOfServiceServiceClient._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, TermsOfServiceServiceTransport) - if transport_provided: - # transport is a TermsOfServiceServiceTransport 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(TermsOfServiceServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - TermsOfServiceServiceClient._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[TermsOfServiceServiceTransport], Callable[..., TermsOfServiceServiceTransport]] = ( - TermsOfServiceServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., TermsOfServiceServiceTransport], 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.accounts_v1beta.TermsOfServiceServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "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.accounts.v1beta.TermsOfServiceService", - "credentialsType": None, - } - ) - - def get_terms_of_service(self, - request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: - r"""Retrieves the ``TermsOfService`` associated with the provided - version. - - .. 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_accounts_v1beta - - def sample_get_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceRequest( - name="name_value", - ) - - # Make the request - response = client.get_terms_of_service(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest, dict]): - The request object. Request message for the ``GetTermsOfService`` method. - name (str): - Required. The resource name of the terms of service - version. Format: ``termsOfService/{version}`` - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.TermsOfService: - A TermsOfService. - """ - # 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, termsofservice.GetTermsOfServiceRequest): - request = termsofservice.GetTermsOfServiceRequest(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.get_terms_of_service] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def retrieve_latest_terms_of_service(self, - request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: - r"""Retrieves the latest version of the ``TermsOfService`` for a - given ``kind`` and ``region_code``. - - .. 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_accounts_v1beta - - def sample_retrieve_latest_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( - region_code="region_code_value", - kind="MERCHANT_CENTER", - ) - - # Make the request - response = client.retrieve_latest_terms_of_service(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest, dict]): - The request object. Request message for the ``RetrieveLatestTermsOfService`` - 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_accounts_v1beta.types.TermsOfService: - A TermsOfService. - """ - # 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, termsofservice.RetrieveLatestTermsOfServiceRequest): - request = termsofservice.RetrieveLatestTermsOfServiceRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.retrieve_latest_terms_of_service] - - # 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 accept_terms_of_service(self, - request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, - *, - name: 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"""Accepts a ``TermsOfService``. Executing this method requires - admin access. - - .. 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_accounts_v1beta - - def sample_accept_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( - name="name_value", - account="account_value", - region_code="region_code_value", - ) - - # Make the request - client.accept_terms_of_service(request=request) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest, dict]): - The request object. Request message for the ``AcceptTermsOfService`` method. - name (str): - Required. The resource name of the terms of service - version. Format: ``termsOfService/{version}`` - - 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, termsofservice.AcceptTermsOfServiceRequest): - request = termsofservice.AcceptTermsOfServiceRequest(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.accept_terms_of_service] - - # 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) -> "TermsOfServiceServiceClient": - 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__ = ( - "TermsOfServiceServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst deleted file mode 100644 index 3a13382bc0d2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`TermsOfServiceServiceTransport` is the ABC for all transports. -- public child `TermsOfServiceServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `TermsOfServiceServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseTermsOfServiceServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `TermsOfServiceServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/__init__.py deleted file mode 100644 index 04c865765be1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_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 TermsOfServiceServiceTransport -from .grpc import TermsOfServiceServiceGrpcTransport -from .grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport -from .rest import TermsOfServiceServiceRestTransport -from .rest import TermsOfServiceServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceServiceTransport]] -_transport_registry['grpc'] = TermsOfServiceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = TermsOfServiceServiceGrpcAsyncIOTransport -_transport_registry['rest'] = TermsOfServiceServiceRestTransport - -__all__ = ( - 'TermsOfServiceServiceTransport', - 'TermsOfServiceServiceGrpcTransport', - 'TermsOfServiceServiceGrpcAsyncIOTransport', - 'TermsOfServiceServiceRestTransport', - 'TermsOfServiceServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/base.py deleted file mode 100644 index 25ec7e23fc98..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_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_accounts_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_accounts_v1beta.types import termsofservice - -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 TermsOfServiceServiceTransport(abc.ABC): - """Abstract transport class for TermsOfServiceService.""" - - 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.get_terms_of_service: gapic_v1.method.wrap_method( - self.get_terms_of_service, - default_timeout=None, - client_info=client_info, - ), - self.retrieve_latest_terms_of_service: gapic_v1.method.wrap_method( - self.retrieve_latest_terms_of_service, - default_timeout=None, - client_info=client_info, - ), - self.accept_terms_of_service: gapic_v1.method.wrap_method( - self.accept_terms_of_service, - 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 get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - Union[ - termsofservice.TermsOfService, - Awaitable[termsofservice.TermsOfService] - ]]: - raise NotImplementedError() - - @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - Union[ - termsofservice.TermsOfService, - Awaitable[termsofservice.TermsOfService] - ]]: - raise NotImplementedError() - - @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'TermsOfServiceServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py deleted file mode 100644 index 3b06c226005b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc.py +++ /dev/null @@ -1,403 +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_accounts_v1beta.types import termsofservice -from .base import TermsOfServiceServiceTransport, 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.accounts.v1beta.TermsOfServiceService", - "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.accounts.v1beta.TermsOfServiceService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class TermsOfServiceServiceGrpcTransport(TermsOfServiceServiceTransport): - """gRPC backend transport for TermsOfServiceService. - - Service to support ``TermsOfService`` API. - - 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 get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - termsofservice.TermsOfService]: - r"""Return a callable for the get terms of service method over gRPC. - - Retrieves the ``TermsOfService`` associated with the provided - version. - - Returns: - Callable[[~.GetTermsOfServiceRequest], - ~.TermsOfService]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_terms_of_service' not in self._stubs: - self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/GetTermsOfService', - request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, - response_deserializer=termsofservice.TermsOfService.deserialize, - ) - return self._stubs['get_terms_of_service'] - - @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - termsofservice.TermsOfService]: - r"""Return a callable for the retrieve latest terms of - service method over gRPC. - - Retrieves the latest version of the ``TermsOfService`` for a - given ``kind`` and ``region_code``. - - Returns: - Callable[[~.RetrieveLatestTermsOfServiceRequest], - ~.TermsOfService]: - 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 'retrieve_latest_terms_of_service' not in self._stubs: - self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/RetrieveLatestTermsOfService', - request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, - response_deserializer=termsofservice.TermsOfService.deserialize, - ) - return self._stubs['retrieve_latest_terms_of_service'] - - @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - empty_pb2.Empty]: - r"""Return a callable for the accept terms of service method over gRPC. - - Accepts a ``TermsOfService``. Executing this method requires - admin access. - - Returns: - Callable[[~.AcceptTermsOfServiceRequest], - ~.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 'accept_terms_of_service' not in self._stubs: - self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/AcceptTermsOfService', - request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['accept_terms_of_service'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'TermsOfServiceServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py deleted file mode 100644 index 553dc4234e16..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,434 +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_accounts_v1beta.types import termsofservice -from .base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import TermsOfServiceServiceGrpcTransport - -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.accounts.v1beta.TermsOfServiceService", - "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.accounts.v1beta.TermsOfServiceService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class TermsOfServiceServiceGrpcAsyncIOTransport(TermsOfServiceServiceTransport): - """gRPC AsyncIO backend transport for TermsOfServiceService. - - Service to support ``TermsOfService`` API. - - 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 get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - Awaitable[termsofservice.TermsOfService]]: - r"""Return a callable for the get terms of service method over gRPC. - - Retrieves the ``TermsOfService`` associated with the provided - version. - - Returns: - Callable[[~.GetTermsOfServiceRequest], - Awaitable[~.TermsOfService]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_terms_of_service' not in self._stubs: - self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/GetTermsOfService', - request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, - response_deserializer=termsofservice.TermsOfService.deserialize, - ) - return self._stubs['get_terms_of_service'] - - @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - Awaitable[termsofservice.TermsOfService]]: - r"""Return a callable for the retrieve latest terms of - service method over gRPC. - - Retrieves the latest version of the ``TermsOfService`` for a - given ``kind`` and ``region_code``. - - Returns: - Callable[[~.RetrieveLatestTermsOfServiceRequest], - Awaitable[~.TermsOfService]]: - 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 'retrieve_latest_terms_of_service' not in self._stubs: - self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/RetrieveLatestTermsOfService', - request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, - response_deserializer=termsofservice.TermsOfService.deserialize, - ) - return self._stubs['retrieve_latest_terms_of_service'] - - @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the accept terms of service method over gRPC. - - Accepts a ``TermsOfService``. Executing this method requires - admin access. - - Returns: - Callable[[~.AcceptTermsOfServiceRequest], - 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 'accept_terms_of_service' not in self._stubs: - self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.TermsOfServiceService/AcceptTermsOfService', - request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['accept_terms_of_service'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_terms_of_service: self._wrap_method( - self.get_terms_of_service, - default_timeout=None, - client_info=client_info, - ), - self.retrieve_latest_terms_of_service: self._wrap_method( - self.retrieve_latest_terms_of_service, - default_timeout=None, - client_info=client_info, - ), - self.accept_terms_of_service: self._wrap_method( - self.accept_terms_of_service, - 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__ = ( - 'TermsOfServiceServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py deleted file mode 100644 index 6f19b49a6583..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest.py +++ /dev/null @@ -1,630 +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_accounts_v1beta.types import termsofservice - - -from .rest_base import _BaseTermsOfServiceServiceRestTransport -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 TermsOfServiceServiceRestInterceptor: - """Interceptor for TermsOfServiceService. - - 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 TermsOfServiceServiceRestTransport. - - .. code-block:: python - class MyCustomTermsOfServiceServiceInterceptor(TermsOfServiceServiceRestInterceptor): - def pre_accept_terms_of_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_terms_of_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_terms_of_service(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_retrieve_latest_terms_of_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_retrieve_latest_terms_of_service(self, response): - logging.log(f"Received response: {response}") - return response - - transport = TermsOfServiceServiceRestTransport(interceptor=MyCustomTermsOfServiceServiceInterceptor()) - client = TermsOfServiceServiceClient(transport=transport) - - - """ - def pre_accept_terms_of_service(self, request: termsofservice.AcceptTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for accept_terms_of_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the TermsOfServiceService server. - """ - return request, metadata - - def pre_get_terms_of_service(self, request: termsofservice.GetTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_terms_of_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the TermsOfServiceService server. - """ - return request, metadata - - def post_get_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: - """Post-rpc interceptor for get_terms_of_service - - DEPRECATED. Please use the `post_get_terms_of_service_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the TermsOfServiceService server but before - it is returned to user code. This `post_get_terms_of_service` interceptor runs - before the `post_get_terms_of_service_with_metadata` interceptor. - """ - return response - - def post_get_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_terms_of_service - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the TermsOfServiceService server but before it is returned to user code. - - We recommend only using this `post_get_terms_of_service_with_metadata` - interceptor in new development instead of the `post_get_terms_of_service` interceptor. - When both interceptors are used, this `post_get_terms_of_service_with_metadata` interceptor runs after the - `post_get_terms_of_service` interceptor. The (possibly modified) response returned by - `post_get_terms_of_service` will be passed to - `post_get_terms_of_service_with_metadata`. - """ - return response, metadata - - def pre_retrieve_latest_terms_of_service(self, request: termsofservice.RetrieveLatestTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for retrieve_latest_terms_of_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the TermsOfServiceService server. - """ - return request, metadata - - def post_retrieve_latest_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: - """Post-rpc interceptor for retrieve_latest_terms_of_service - - DEPRECATED. Please use the `post_retrieve_latest_terms_of_service_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the TermsOfServiceService server but before - it is returned to user code. This `post_retrieve_latest_terms_of_service` interceptor runs - before the `post_retrieve_latest_terms_of_service_with_metadata` interceptor. - """ - return response - - def post_retrieve_latest_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for retrieve_latest_terms_of_service - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the TermsOfServiceService server but before it is returned to user code. - - We recommend only using this `post_retrieve_latest_terms_of_service_with_metadata` - interceptor in new development instead of the `post_retrieve_latest_terms_of_service` interceptor. - When both interceptors are used, this `post_retrieve_latest_terms_of_service_with_metadata` interceptor runs after the - `post_retrieve_latest_terms_of_service` interceptor. The (possibly modified) response returned by - `post_retrieve_latest_terms_of_service` will be passed to - `post_retrieve_latest_terms_of_service_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class TermsOfServiceServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: TermsOfServiceServiceRestInterceptor - - -class TermsOfServiceServiceRestTransport(_BaseTermsOfServiceServiceRestTransport): - """REST backend synchronous transport for TermsOfServiceService. - - Service to support ``TermsOfService`` API. - - 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[TermsOfServiceServiceRestInterceptor] = 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 TermsOfServiceServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AcceptTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService, TermsOfServiceServiceRestStub): - def __hash__(self): - return hash("TermsOfServiceServiceRestTransport.AcceptTermsOfService") - - @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: termsofservice.AcceptTermsOfServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the accept terms of service method over HTTP. - - Args: - request (~.termsofservice.AcceptTermsOfServiceRequest): - The request object. Request message for the ``AcceptTermsOfService`` 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 = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_http_options() - - request, metadata = self._interceptor.pre_accept_terms_of_service(request, metadata) - transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceServiceClient.AcceptTermsOfService", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "rpcName": "AcceptTermsOfService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = TermsOfServiceServiceRestTransport._AcceptTermsOfService._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 _GetTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService, TermsOfServiceServiceRestStub): - def __hash__(self): - return hash("TermsOfServiceServiceRestTransport.GetTermsOfService") - - @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: termsofservice.GetTermsOfServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofservice.TermsOfService: - r"""Call the get terms of service method over HTTP. - - Args: - request (~.termsofservice.GetTermsOfServiceRequest): - The request object. Request message for the ``GetTermsOfService`` 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: - ~.termsofservice.TermsOfService: - A ``TermsOfService``. - """ - - http_options = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_http_options() - - request, metadata = self._interceptor.pre_get_terms_of_service(request, metadata) - transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceServiceClient.GetTermsOfService", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "rpcName": "GetTermsOfService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = TermsOfServiceServiceRestTransport._GetTermsOfService._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 = termsofservice.TermsOfService() - pb_resp = termsofservice.TermsOfService.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_terms_of_service(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_terms_of_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = termsofservice.TermsOfService.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.accounts_v1beta.TermsOfServiceServiceClient.get_terms_of_service", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "rpcName": "GetTermsOfService", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _RetrieveLatestTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService, TermsOfServiceServiceRestStub): - def __hash__(self): - return hash("TermsOfServiceServiceRestTransport.RetrieveLatestTermsOfService") - - @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: termsofservice.RetrieveLatestTermsOfServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofservice.TermsOfService: - r"""Call the retrieve latest terms of - service method over HTTP. - - Args: - request (~.termsofservice.RetrieveLatestTermsOfServiceRequest): - The request object. Request message for the ``RetrieveLatestTermsOfService`` - 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: - ~.termsofservice.TermsOfService: - A ``TermsOfService``. - """ - - http_options = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_http_options() - - request, metadata = self._interceptor.pre_retrieve_latest_terms_of_service(request, metadata) - transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.TermsOfServiceServiceClient.RetrieveLatestTermsOfService", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "rpcName": "RetrieveLatestTermsOfService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = TermsOfServiceServiceRestTransport._RetrieveLatestTermsOfService._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 = termsofservice.TermsOfService() - pb_resp = termsofservice.TermsOfService.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_retrieve_latest_terms_of_service(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_retrieve_latest_terms_of_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = termsofservice.TermsOfService.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.accounts_v1beta.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "rpcName": "RetrieveLatestTermsOfService", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - 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._AcceptTermsOfService(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - termsofservice.TermsOfService]: - # 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._GetTermsOfService(self._session, self._host, self._interceptor) # type: ignore - - @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - termsofservice.TermsOfService]: - # 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._RetrieveLatestTermsOfService(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'TermsOfServiceServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py deleted file mode 100644 index 5e200fbf9992..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/terms_of_service_service/transports/rest_base.py +++ /dev/null @@ -1,203 +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 TermsOfServiceServiceTransport, 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_accounts_v1beta.types import termsofservice - - -class _BaseTermsOfServiceServiceRestTransport(TermsOfServiceServiceTransport): - """Base REST backend transport for TermsOfServiceService. - - 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 _BaseAcceptTermsOfService: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "account" : "", "regionCode" : "", } - - @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': '/accounts/v1beta/{name=termsOfService/*}:accept', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = termsofservice.AcceptTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetTermsOfService: - 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': '/accounts/v1beta/{name=termsOfService/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = termsofservice.GetTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRetrieveLatestTermsOfService: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "regionCode" : "", "kind" : {}, } - - @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': '/accounts/v1beta/termsOfService:retrieveLatest', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = termsofservice.RetrieveLatestTermsOfServiceRequest.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(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseTermsOfServiceServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/__init__.py deleted file mode 100644 index d60a27bcbaf8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_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 UserServiceClient -from .async_client import UserServiceAsyncClient - -__all__ = ( - 'UserServiceClient', - 'UserServiceAsyncClient', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py deleted file mode 100644 index 48734d9b5d9d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/async_client.py +++ /dev/null @@ -1,827 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.user_service import pagers -from google.shopping.merchant_accounts_v1beta.types import accessright -from google.shopping.merchant_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user -from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport -from .client import UserServiceClient - -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 UserServiceAsyncClient: - """Service to support user API.""" - - _client: UserServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = UserServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = UserServiceClient._DEFAULT_UNIVERSE - - account_path = staticmethod(UserServiceClient.account_path) - parse_account_path = staticmethod(UserServiceClient.parse_account_path) - user_path = staticmethod(UserServiceClient.user_path) - parse_user_path = staticmethod(UserServiceClient.parse_user_path) - common_billing_account_path = staticmethod(UserServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserServiceClient.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: - UserServiceAsyncClient: The constructed client. - """ - return UserServiceClient.from_service_account_info.__func__(UserServiceAsyncClient, 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: - UserServiceAsyncClient: The constructed client. - """ - return UserServiceClient.from_service_account_file.__func__(UserServiceAsyncClient, 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 UserServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserServiceTransport: 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 = UserServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, UserServiceTransport, Callable[..., UserServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user 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,UserServiceTransport,Callable[..., UserServiceTransport]]]): - 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 UserServiceTransport 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 = UserServiceClient( - 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.accounts_v1beta.UserServiceAsyncClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "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.accounts.v1beta.UserService", - "credentialsType": None, - } - ) - - async def get_user(self, - request: Optional[Union[user.GetUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> user.User: - r"""Retrieves a Merchant Center account user. - - .. 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_accounts_v1beta - - async def sample_get_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetUserRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.GetUserRequest, dict]]): - The request object. Request message for the ``GetUser`` method. - name (:class:`str`): - Required. The name of the user to retrieve. Format: - ``accounts/{account}/users/{email}`` - - It is also possible to retrieve the user corresponding - to the caller by using ``me`` rather than an email - address as in ``accounts/{account}/users/me``. - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.User: - A - [user](https://support.google.com/merchants/answer/12160472). - - """ - # 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, user.GetUserRequest): - request = user.GetUserRequest(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.get_user] - - # 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. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_user(self, - request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, - *, - parent: Optional[str] = None, - user: Optional[gsma_user.User] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: - r"""Creates a Merchant Center account user. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_create_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateUserRequest( - parent="parent_value", - user_id="user_id_value", - ) - - # Make the request - response = await client.create_user(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.CreateUserRequest, dict]]): - The request object. Request message for the ``CreateUser`` method. - parent (:class:`str`): - Required. The resource name of the account for which a - user will be created. Format: ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user (:class:`google.shopping.merchant_accounts_v1beta.types.User`): - Required. The user to create. - This corresponds to the ``user`` 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_accounts_v1beta.types.User: - A - [user](https://support.google.com/merchants/answer/12160472). - - """ - # 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, user] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_user.CreateUserRequest): - request = gsma_user.CreateUserRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user is not None: - request.user = user - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user] - - # 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_user(self, - request: Optional[Union[user.DeleteUserRequest, dict]] = None, - *, - name: 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 a Merchant Center account user. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_delete_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteUserRequest( - name="name_value", - ) - - # Make the request - await client.delete_user(request=request) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest, dict]]): - The request object. Request message for the ``DeleteUser`` method. - name (:class:`str`): - Required. The name of the user to delete. Format: - ``accounts/{account}/users/{email}`` - - It is also possible to delete the user corresponding to - the caller by using ``me`` rather than an email address - as in ``accounts/{account}/users/me``. - - 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, user.DeleteUserRequest): - request = user.DeleteUserRequest(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_user] - - # 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 update_user(self, - request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, - *, - user: Optional[gsma_user.User] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: - r"""Updates a Merchant Center account user. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - async def sample_update_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateUserRequest( - ) - - # Make the request - response = await client.update_user(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest, dict]]): - The request object. Request message for the ``UpdateUser`` method. - user (:class:`google.shopping.merchant_accounts_v1beta.types.User`): - Required. The new version of the user. - - Use ``me`` to refer to your own email address, for - example ``accounts/{account}/users/me``. - - This corresponds to the ``user`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.User: - A - [user](https://support.google.com/merchants/answer/12160472). - - """ - # 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 = [user, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_user.UpdateUserRequest): - request = gsma_user.UpdateUserRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user is not None: - request.user = user - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user.name", request.user.name), - )), - ) - - # 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 list_users(self, - request: Optional[Union[user.ListUsersRequest, 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.ListUsersAsyncPager: - r"""Lists all users of a Merchant Center 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_accounts_v1beta - - async def sample_list_users(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListUsersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.shopping.merchant_accounts_v1beta.types.ListUsersRequest, dict]]): - The request object. Request message for the ``ListUsers`` method. - parent (:class:`str`): - Required. The parent, which owns this collection of - users. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.user_service.pagers.ListUsersAsyncPager: - Response message for the ListUsers 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, user.ListUsersRequest): - request = user.ListUsersRequest(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_users] - - # 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.ListUsersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "UserServiceAsyncClient": - 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__ = ( - "UserServiceAsyncClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py deleted file mode 100644 index 9756aa826c98..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/client.py +++ /dev/null @@ -1,1192 +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_accounts_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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.user_service import pagers -from google.shopping.merchant_accounts_v1beta.types import accessright -from google.shopping.merchant_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user -from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserServiceGrpcTransport -from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport -from .transports.rest import UserServiceRestTransport - - -class UserServiceClientMeta(type): - """Metaclass for the UserService 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[UserServiceTransport]] - _transport_registry["grpc"] = UserServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserServiceGrpcAsyncIOTransport - _transport_registry["rest"] = UserServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[UserServiceTransport]: - """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 UserServiceClient(metaclass=UserServiceClientMeta): - """Service to support user API.""" - - @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: - UserServiceClient: 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: - UserServiceClient: 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) -> UserServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def account_path(account: str,) -> str: - """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) - - @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: - """Parses a account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def user_path(account: str,email: str,) -> str: - """Returns a fully-qualified user string.""" - return "accounts/{account}/users/{email}".format(account=account, email=email, ) - - @staticmethod - def parse_user_path(path: str) -> Dict[str,str]: - """Parses a user path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/users/(?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 = UserServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = UserServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = UserServiceClient._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 = UserServiceClient._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, UserServiceTransport, Callable[..., UserServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user 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,UserServiceTransport,Callable[..., UserServiceTransport]]]): - 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 UserServiceTransport 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 = UserServiceClient._read_environment_variables() - self._client_cert_source = UserServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = UserServiceClient._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, UserServiceTransport) - if transport_provided: - # transport is a UserServiceTransport 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(UserServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - UserServiceClient._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[UserServiceTransport], Callable[..., UserServiceTransport]] = ( - UserServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., UserServiceTransport], 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.accounts_v1beta.UserServiceClient`.", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "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.accounts.v1beta.UserService", - "credentialsType": None, - } - ) - - def get_user(self, - request: Optional[Union[user.GetUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> user.User: - r"""Retrieves a Merchant Center account user. - - .. 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_accounts_v1beta - - def sample_get_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetUserRequest( - name="name_value", - ) - - # Make the request - response = client.get_user(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.GetUserRequest, dict]): - The request object. Request message for the ``GetUser`` method. - name (str): - Required. The name of the user to retrieve. Format: - ``accounts/{account}/users/{email}`` - - It is also possible to retrieve the user corresponding - to the caller by using ``me`` rather than an email - address as in ``accounts/{account}/users/me``. - - 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`. - - Returns: - google.shopping.merchant_accounts_v1beta.types.User: - A - [user](https://support.google.com/merchants/answer/12160472). - - """ - # 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, user.GetUserRequest): - request = user.GetUserRequest(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.get_user] - - # 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. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_user(self, - request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, - *, - parent: Optional[str] = None, - user: Optional[gsma_user.User] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: - r"""Creates a Merchant Center account user. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - def sample_create_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateUserRequest( - parent="parent_value", - user_id="user_id_value", - ) - - # Make the request - response = client.create_user(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.CreateUserRequest, dict]): - The request object. Request message for the ``CreateUser`` method. - parent (str): - Required. The resource name of the account for which a - user will be created. Format: ``accounts/{account}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - user (google.shopping.merchant_accounts_v1beta.types.User): - Required. The user to create. - This corresponds to the ``user`` 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_accounts_v1beta.types.User: - A - [user](https://support.google.com/merchants/answer/12160472). - - """ - # 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, user] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_user.CreateUserRequest): - request = gsma_user.CreateUserRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if user is not None: - request.user = user - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_user] - - # 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_user(self, - request: Optional[Union[user.DeleteUserRequest, dict]] = None, - *, - name: 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 a Merchant Center account user. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - def sample_delete_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteUserRequest( - name="name_value", - ) - - # Make the request - client.delete_user(request=request) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest, dict]): - The request object. Request message for the ``DeleteUser`` method. - name (str): - Required. The name of the user to delete. Format: - ``accounts/{account}/users/{email}`` - - It is also possible to delete the user corresponding to - the caller by using ``me`` rather than an email address - as in ``accounts/{account}/users/me``. - - 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, user.DeleteUserRequest): - request = user.DeleteUserRequest(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_user] - - # 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 update_user(self, - request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, - *, - user: Optional[gsma_user.User] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: - r"""Updates a Merchant Center account user. Executing - this method requires admin access. - - .. 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_accounts_v1beta - - def sample_update_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateUserRequest( - ) - - # Make the request - response = client.update_user(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest, dict]): - The request object. Request message for the ``UpdateUser`` method. - user (google.shopping.merchant_accounts_v1beta.types.User): - Required. The new version of the user. - - Use ``me`` to refer to your own email address, for - example ``accounts/{account}/users/me``. - - This corresponds to the ``user`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being - updated. - - This corresponds to the ``update_mask`` 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_accounts_v1beta.types.User: - A - [user](https://support.google.com/merchants/answer/12160472). - - """ - # 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 = [user, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 - if request is 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, gsma_user.UpdateUserRequest): - request = gsma_user.UpdateUserRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if user is not None: - request.user = user - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_user] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user.name", request.user.name), - )), - ) - - # 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 list_users(self, - request: Optional[Union[user.ListUsersRequest, 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.ListUsersPager: - r"""Lists all users of a Merchant Center 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_accounts_v1beta - - def sample_list_users(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListUsersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.shopping.merchant_accounts_v1beta.types.ListUsersRequest, dict]): - The request object. Request message for the ``ListUsers`` method. - parent (str): - Required. The parent, which owns this collection of - users. Format: ``accounts/{account}`` - - 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_accounts_v1beta.services.user_service.pagers.ListUsersPager: - Response message for the ListUsers 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, user.ListUsersRequest): - request = user.ListUsersRequest(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_users] - - # 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.ListUsersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "UserServiceClient": - 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__ = ( - "UserServiceClient", -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/pagers.py deleted file mode 100644 index 8b1b771c7d7c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_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_accounts_v1beta.types import user - - -class ListUsersPager: - """A pager for iterating through ``list_users`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``users`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListUsers`` requests and continue to iterate - through the ``users`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` - 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[..., user.ListUsersResponse], - request: user.ListUsersRequest, - response: user.ListUsersResponse, - *, - 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_accounts_v1beta.types.ListUsersRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListUsersResponse): - 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 = user.ListUsersRequest(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[user.ListUsersResponse]: - 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[user.User]: - for page in self.pages: - yield from page.users - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListUsersAsyncPager: - """A pager for iterating through ``list_users`` requests. - - This class thinly wraps an initial - :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``users`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListUsers`` requests and continue to iterate - through the ``users`` field on the - corresponding responses. - - All the usual :class:`google.shopping.merchant_accounts_v1beta.types.ListUsersResponse` - 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[user.ListUsersResponse]], - request: user.ListUsersRequest, - response: user.ListUsersResponse, - *, - 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_accounts_v1beta.types.ListUsersRequest): - The initial request object. - response (google.shopping.merchant_accounts_v1beta.types.ListUsersResponse): - 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 = user.ListUsersRequest(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[user.ListUsersResponse]: - 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[user.User]: - async def async_generator(): - async for page in self.pages: - for response in page.users: - 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst deleted file mode 100644 index 815387def1a4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`UserServiceTransport` is the ABC for all transports. -- public child `UserServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `UserServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseUserServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `UserServiceRestTransport` 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-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/__init__.py deleted file mode 100644 index b8429533bdc0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_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 UserServiceTransport -from .grpc import UserServiceGrpcTransport -from .grpc_asyncio import UserServiceGrpcAsyncIOTransport -from .rest import UserServiceRestTransport -from .rest import UserServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserServiceTransport]] -_transport_registry['grpc'] = UserServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserServiceGrpcAsyncIOTransport -_transport_registry['rest'] = UserServiceRestTransport - -__all__ = ( - 'UserServiceTransport', - 'UserServiceGrpcTransport', - 'UserServiceGrpcAsyncIOTransport', - 'UserServiceRestTransport', - 'UserServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py deleted file mode 100644 index ab10f30f7dc8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/base.py +++ /dev/null @@ -1,217 +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_accounts_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_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user - -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 UserServiceTransport(abc.ABC): - """Abstract transport class for UserService.""" - - 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.get_user: gapic_v1.method.wrap_method( - self.get_user, - default_timeout=None, - client_info=client_info, - ), - self.create_user: gapic_v1.method.wrap_method( - self.create_user, - default_timeout=None, - client_info=client_info, - ), - self.delete_user: gapic_v1.method.wrap_method( - self.delete_user, - default_timeout=None, - client_info=client_info, - ), - self.update_user: gapic_v1.method.wrap_method( - self.update_user, - default_timeout=None, - client_info=client_info, - ), - self.list_users: gapic_v1.method.wrap_method( - self.list_users, - 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 get_user(self) -> Callable[ - [user.GetUserRequest], - Union[ - user.User, - Awaitable[user.User] - ]]: - raise NotImplementedError() - - @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - Union[ - gsma_user.User, - Awaitable[gsma_user.User] - ]]: - raise NotImplementedError() - - @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - Union[ - gsma_user.User, - Awaitable[gsma_user.User] - ]]: - raise NotImplementedError() - - @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - Union[ - user.ListUsersResponse, - Awaitable[user.ListUsersResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserServiceTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py deleted file mode 100644 index e71109e7ff7c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc.py +++ /dev/null @@ -1,455 +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_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user -from .base import UserServiceTransport, 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.accounts.v1beta.UserService", - "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.accounts.v1beta.UserService", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class UserServiceGrpcTransport(UserServiceTransport): - """gRPC backend transport for UserService. - - Service to support user API. - - 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 get_user(self) -> Callable[ - [user.GetUserRequest], - user.User]: - r"""Return a callable for the get user method over gRPC. - - Retrieves a Merchant Center account user. - - Returns: - Callable[[~.GetUserRequest], - ~.User]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_user' not in self._stubs: - self._stubs['get_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/GetUser', - request_serializer=user.GetUserRequest.serialize, - response_deserializer=user.User.deserialize, - ) - return self._stubs['get_user'] - - @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - gsma_user.User]: - r"""Return a callable for the create user method over gRPC. - - Creates a Merchant Center account user. Executing - this method requires admin access. - - Returns: - Callable[[~.CreateUserRequest], - ~.User]: - 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 'create_user' not in self._stubs: - self._stubs['create_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/CreateUser', - request_serializer=gsma_user.CreateUserRequest.serialize, - response_deserializer=gsma_user.User.deserialize, - ) - return self._stubs['create_user'] - - @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete user method over gRPC. - - Deletes a Merchant Center account user. Executing - this method requires admin access. - - Returns: - Callable[[~.DeleteUserRequest], - ~.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_user' not in self._stubs: - self._stubs['delete_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/DeleteUser', - request_serializer=user.DeleteUserRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user'] - - @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - gsma_user.User]: - r"""Return a callable for the update user method over gRPC. - - Updates a Merchant Center account user. Executing - this method requires admin access. - - Returns: - Callable[[~.UpdateUserRequest], - ~.User]: - 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 'update_user' not in self._stubs: - self._stubs['update_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/UpdateUser', - request_serializer=gsma_user.UpdateUserRequest.serialize, - response_deserializer=gsma_user.User.deserialize, - ) - return self._stubs['update_user'] - - @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - user.ListUsersResponse]: - r"""Return a callable for the list users method over gRPC. - - Lists all users of a Merchant Center account. - - Returns: - Callable[[~.ListUsersRequest], - ~.ListUsersResponse]: - 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_users' not in self._stubs: - self._stubs['list_users'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/ListUsers', - request_serializer=user.ListUsersRequest.serialize, - response_deserializer=user.ListUsersResponse.deserialize, - ) - return self._stubs['list_users'] - - def close(self): - self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py deleted file mode 100644 index de69a24dbbf8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,496 +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_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user -from .base import UserServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserServiceGrpcTransport - -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.accounts.v1beta.UserService", - "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.accounts.v1beta.UserService", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class UserServiceGrpcAsyncIOTransport(UserServiceTransport): - """gRPC AsyncIO backend transport for UserService. - - Service to support user API. - - 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 get_user(self) -> Callable[ - [user.GetUserRequest], - Awaitable[user.User]]: - r"""Return a callable for the get user method over gRPC. - - Retrieves a Merchant Center account user. - - Returns: - Callable[[~.GetUserRequest], - Awaitable[~.User]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'get_user' not in self._stubs: - self._stubs['get_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/GetUser', - request_serializer=user.GetUserRequest.serialize, - response_deserializer=user.User.deserialize, - ) - return self._stubs['get_user'] - - @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - Awaitable[gsma_user.User]]: - r"""Return a callable for the create user method over gRPC. - - Creates a Merchant Center account user. Executing - this method requires admin access. - - Returns: - Callable[[~.CreateUserRequest], - Awaitable[~.User]]: - 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 'create_user' not in self._stubs: - self._stubs['create_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/CreateUser', - request_serializer=gsma_user.CreateUserRequest.serialize, - response_deserializer=gsma_user.User.deserialize, - ) - return self._stubs['create_user'] - - @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete user method over gRPC. - - Deletes a Merchant Center account user. Executing - this method requires admin access. - - Returns: - Callable[[~.DeleteUserRequest], - 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_user' not in self._stubs: - self._stubs['delete_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/DeleteUser', - request_serializer=user.DeleteUserRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_user'] - - @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - Awaitable[gsma_user.User]]: - r"""Return a callable for the update user method over gRPC. - - Updates a Merchant Center account user. Executing - this method requires admin access. - - Returns: - Callable[[~.UpdateUserRequest], - Awaitable[~.User]]: - 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 'update_user' not in self._stubs: - self._stubs['update_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/UpdateUser', - request_serializer=gsma_user.UpdateUserRequest.serialize, - response_deserializer=gsma_user.User.deserialize, - ) - return self._stubs['update_user'] - - @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - Awaitable[user.ListUsersResponse]]: - r"""Return a callable for the list users method over gRPC. - - Lists all users of a Merchant Center account. - - Returns: - Callable[[~.ListUsersRequest], - Awaitable[~.ListUsersResponse]]: - 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_users' not in self._stubs: - self._stubs['list_users'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1beta.UserService/ListUsers', - request_serializer=user.ListUsersRequest.serialize, - response_deserializer=user.ListUsersResponse.deserialize, - ) - return self._stubs['list_users'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.get_user: self._wrap_method( - self.get_user, - default_timeout=None, - client_info=client_info, - ), - self.create_user: self._wrap_method( - self.create_user, - default_timeout=None, - client_info=client_info, - ), - self.delete_user: self._wrap_method( - self.delete_user, - default_timeout=None, - client_info=client_info, - ), - self.update_user: self._wrap_method( - self.update_user, - default_timeout=None, - client_info=client_info, - ), - self.list_users: self._wrap_method( - self.list_users, - 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__ = ( - 'UserServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py deleted file mode 100644 index 822c4b850064..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest.py +++ /dev/null @@ -1,983 +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_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user - - -from .rest_base import _BaseUserServiceRestTransport -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 UserServiceRestInterceptor: - """Interceptor for UserService. - - 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 UserServiceRestTransport. - - .. code-block:: python - class MyCustomUserServiceInterceptor(UserServiceRestInterceptor): - def pre_create_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_user(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_user(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_users(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_users(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_user(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_user(self, response): - logging.log(f"Received response: {response}") - return response - - transport = UserServiceRestTransport(interceptor=MyCustomUserServiceInterceptor()) - client = UserServiceClient(transport=transport) - - - """ - def pre_create_user(self, request: gsma_user.CreateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserService server. - """ - return request, metadata - - def post_create_user(self, response: gsma_user.User) -> gsma_user.User: - """Post-rpc interceptor for create_user - - DEPRECATED. Please use the `post_create_user_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the UserService server but before - it is returned to user code. This `post_create_user` interceptor runs - before the `post_create_user_with_metadata` interceptor. - """ - return response - - def post_create_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_user - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the UserService server but before it is returned to user code. - - We recommend only using this `post_create_user_with_metadata` - interceptor in new development instead of the `post_create_user` interceptor. - When both interceptors are used, this `post_create_user_with_metadata` interceptor runs after the - `post_create_user` interceptor. The (possibly modified) response returned by - `post_create_user` will be passed to - `post_create_user_with_metadata`. - """ - return response, metadata - - def pre_delete_user(self, request: user.DeleteUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserService server. - """ - return request, metadata - - def pre_get_user(self, request: user.GetUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserService server. - """ - return request, metadata - - def post_get_user(self, response: user.User) -> user.User: - """Post-rpc interceptor for get_user - - DEPRECATED. Please use the `post_get_user_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the UserService server but before - it is returned to user code. This `post_get_user` interceptor runs - before the `post_get_user_with_metadata` interceptor. - """ - return response - - def post_get_user_with_metadata(self, response: user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_user - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the UserService server but before it is returned to user code. - - We recommend only using this `post_get_user_with_metadata` - interceptor in new development instead of the `post_get_user` interceptor. - When both interceptors are used, this `post_get_user_with_metadata` interceptor runs after the - `post_get_user` interceptor. The (possibly modified) response returned by - `post_get_user` will be passed to - `post_get_user_with_metadata`. - """ - return response, metadata - - def pre_list_users(self, request: user.ListUsersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_users - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserService server. - """ - return request, metadata - - def post_list_users(self, response: user.ListUsersResponse) -> user.ListUsersResponse: - """Post-rpc interceptor for list_users - - DEPRECATED. Please use the `post_list_users_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the UserService server but before - it is returned to user code. This `post_list_users` interceptor runs - before the `post_list_users_with_metadata` interceptor. - """ - return response - - def post_list_users_with_metadata(self, response: user.ListUsersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_users - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the UserService server but before it is returned to user code. - - We recommend only using this `post_list_users_with_metadata` - interceptor in new development instead of the `post_list_users` interceptor. - When both interceptors are used, this `post_list_users_with_metadata` interceptor runs after the - `post_list_users` interceptor. The (possibly modified) response returned by - `post_list_users` will be passed to - `post_list_users_with_metadata`. - """ - return response, metadata - - def pre_update_user(self, request: gsma_user.UpdateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_user - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserService server. - """ - return request, metadata - - def post_update_user(self, response: gsma_user.User) -> gsma_user.User: - """Post-rpc interceptor for update_user - - DEPRECATED. Please use the `post_update_user_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the UserService server but before - it is returned to user code. This `post_update_user` interceptor runs - before the `post_update_user_with_metadata` interceptor. - """ - return response - - def post_update_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_user - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the UserService server but before it is returned to user code. - - We recommend only using this `post_update_user_with_metadata` - interceptor in new development instead of the `post_update_user` interceptor. - When both interceptors are used, this `post_update_user_with_metadata` interceptor runs after the - `post_update_user` interceptor. The (possibly modified) response returned by - `post_update_user` will be passed to - `post_update_user_with_metadata`. - """ - return response, metadata - - -@dataclasses.dataclass -class UserServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: UserServiceRestInterceptor - - -class UserServiceRestTransport(_BaseUserServiceRestTransport): - """REST backend synchronous transport for UserService. - - Service to support user API. - - 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[UserServiceRestInterceptor] = 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 UserServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateUser(_BaseUserServiceRestTransport._BaseCreateUser, UserServiceRestStub): - def __hash__(self): - return hash("UserServiceRestTransport.CreateUser") - - @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: gsma_user.CreateUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_user.User: - r"""Call the create user method over HTTP. - - Args: - request (~.gsma_user.CreateUserRequest): - The request object. Request message for the ``CreateUser`` 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: - ~.gsma_user.User: - A - `user `__. - - """ - - http_options = _BaseUserServiceRestTransport._BaseCreateUser._get_http_options() - - request, metadata = self._interceptor.pre_create_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseCreateUser._get_transcoded_request(http_options, request) - - body = _BaseUserServiceRestTransport._BaseCreateUser._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseCreateUser._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.CreateUser", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "CreateUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = UserServiceRestTransport._CreateUser._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 = gsma_user.User() - pb_resp = gsma_user.User.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_user(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gsma_user.User.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.accounts_v1beta.UserServiceClient.create_user", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "CreateUser", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteUser(_BaseUserServiceRestTransport._BaseDeleteUser, UserServiceRestStub): - def __hash__(self): - return hash("UserServiceRestTransport.DeleteUser") - - @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: user.DeleteUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete user method over HTTP. - - Args: - request (~.user.DeleteUserRequest): - The request object. Request message for the ``DeleteUser`` 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 = _BaseUserServiceRestTransport._BaseDeleteUser._get_http_options() - - request, metadata = self._interceptor.pre_delete_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseDeleteUser._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseDeleteUser._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.DeleteUser", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "DeleteUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = UserServiceRestTransport._DeleteUser._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 _GetUser(_BaseUserServiceRestTransport._BaseGetUser, UserServiceRestStub): - def __hash__(self): - return hash("UserServiceRestTransport.GetUser") - - @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: user.GetUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> user.User: - r"""Call the get user method over HTTP. - - Args: - request (~.user.GetUserRequest): - The request object. Request message for the ``GetUser`` 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: - ~.user.User: - A - `user `__. - - """ - - http_options = _BaseUserServiceRestTransport._BaseGetUser._get_http_options() - - request, metadata = self._interceptor.pre_get_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseGetUser._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseGetUser._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.GetUser", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "GetUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = UserServiceRestTransport._GetUser._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 = user.User() - pb_resp = user.User.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_user(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = user.User.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.accounts_v1beta.UserServiceClient.get_user", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "GetUser", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListUsers(_BaseUserServiceRestTransport._BaseListUsers, UserServiceRestStub): - def __hash__(self): - return hash("UserServiceRestTransport.ListUsers") - - @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: user.ListUsersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> user.ListUsersResponse: - r"""Call the list users method over HTTP. - - Args: - request (~.user.ListUsersRequest): - The request object. Request message for the ``ListUsers`` 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: - ~.user.ListUsersResponse: - Response message for the ``ListUsers`` method. - """ - - http_options = _BaseUserServiceRestTransport._BaseListUsers._get_http_options() - - request, metadata = self._interceptor.pre_list_users(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseListUsers._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseListUsers._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.ListUsers", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "ListUsers", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = UserServiceRestTransport._ListUsers._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 = user.ListUsersResponse() - pb_resp = user.ListUsersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_users(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_users_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = user.ListUsersResponse.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.accounts_v1beta.UserServiceClient.list_users", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "ListUsers", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateUser(_BaseUserServiceRestTransport._BaseUpdateUser, UserServiceRestStub): - def __hash__(self): - return hash("UserServiceRestTransport.UpdateUser") - - @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: gsma_user.UpdateUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_user.User: - r"""Call the update user method over HTTP. - - Args: - request (~.gsma_user.UpdateUserRequest): - The request object. Request message for the ``UpdateUser`` 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: - ~.gsma_user.User: - A - `user `__. - - """ - - http_options = _BaseUserServiceRestTransport._BaseUpdateUser._get_http_options() - - request, metadata = self._interceptor.pre_update_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseUpdateUser._get_transcoded_request(http_options, request) - - body = _BaseUserServiceRestTransport._BaseUpdateUser._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseUpdateUser._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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.accounts_v1beta.UserServiceClient.UpdateUser", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "UpdateUser", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = UserServiceRestTransport._UpdateUser._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 = gsma_user.User() - pb_resp = gsma_user.User.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_update_user(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = gsma_user.User.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.accounts_v1beta.UserServiceClient.update_user", - extra = { - "serviceName": "google.shopping.merchant.accounts.v1beta.UserService", - "rpcName": "UpdateUser", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - gsma_user.User]: - # 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._CreateUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - 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._DeleteUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_user(self) -> Callable[ - [user.GetUserRequest], - user.User]: - # 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._GetUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - user.ListUsersResponse]: - # 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._ListUsers(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - gsma_user.User]: - # 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._UpdateUser(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'UserServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py deleted file mode 100644 index e015cbbed371..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/user_service/transports/rest_base.py +++ /dev/null @@ -1,298 +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 UserServiceTransport, 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_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user - - -class _BaseUserServiceRestTransport(UserServiceTransport): - """Base REST backend transport for UserService. - - 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 _BaseCreateUser: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userId" : "", } - - @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': '/accounts/v1beta/{parent=accounts/*}/users', - 'body': 'user', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gsma_user.CreateUserRequest.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(_BaseUserServiceRestTransport._BaseCreateUser._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteUser: - 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': '/accounts/v1beta/{name=accounts/*/users/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = user.DeleteUserRequest.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(_BaseUserServiceRestTransport._BaseDeleteUser._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetUser: - 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': '/accounts/v1beta/{name=accounts/*/users/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = user.GetUserRequest.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(_BaseUserServiceRestTransport._BaseGetUser._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListUsers: - 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': '/accounts/v1beta/{parent=accounts/*}/users', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = user.ListUsersRequest.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(_BaseUserServiceRestTransport._BaseListUsers._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateUser: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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': 'patch', - 'uri': '/accounts/v1beta/{user.name=accounts/*/users/*}', - 'body': 'user', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = gsma_user.UpdateUserRequest.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(_BaseUserServiceRestTransport._BaseUpdateUser._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - -__all__=( - '_BaseUserServiceRestTransport', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py deleted file mode 100644 index 79ebdd0dd449..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/__init__.py +++ /dev/null @@ -1,338 +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 .accessright import ( - AccessRight, -) -from .account_tax import ( - AccountTax, - GetAccountTaxRequest, - ListAccountTaxRequest, - ListAccountTaxResponse, - UpdateAccountTaxRequest, -) -from .accountissue import ( - AccountIssue, - ListAccountIssuesRequest, - ListAccountIssuesResponse, -) -from .accounts import ( - Account, - CreateAndConfigureAccountRequest, - DeleteAccountRequest, - GetAccountRequest, - ListAccountsRequest, - ListAccountsResponse, - ListSubAccountsRequest, - ListSubAccountsResponse, - UpdateAccountRequest, -) -from .accountservices import ( - AccountAggregation, -) -from .autofeedsettings import ( - AutofeedSettings, - GetAutofeedSettingsRequest, - UpdateAutofeedSettingsRequest, -) -from .automaticimprovements import ( - AutomaticImageImprovements, - AutomaticImprovements, - AutomaticItemUpdates, - AutomaticShippingImprovements, - GetAutomaticImprovementsRequest, - UpdateAutomaticImprovementsRequest, -) -from .businessidentity import ( - BusinessIdentity, - GetBusinessIdentityRequest, - UpdateBusinessIdentityRequest, -) -from .businessinfo import ( - BusinessInfo, - GetBusinessInfoRequest, - UpdateBusinessInfoRequest, -) -from .checkoutsettings import ( - CheckoutSettings, - CreateCheckoutSettingsRequest, - DeleteCheckoutSettingsRequest, - GetCheckoutSettingsRequest, - UpdateCheckoutSettingsRequest, - UriSettings, -) -from .customerservice import ( - CustomerService, -) -from .emailpreferences import ( - EmailPreferences, - GetEmailPreferencesRequest, - UpdateEmailPreferencesRequest, -) -from .gbpaccounts import ( - GbpAccount, - LinkGbpAccountRequest, - LinkGbpAccountResponse, - ListGbpAccountsRequest, - ListGbpAccountsResponse, -) -from .homepage import ( - ClaimHomepageRequest, - GetHomepageRequest, - Homepage, - UnclaimHomepageRequest, - UpdateHomepageRequest, -) -from .lfpproviders import ( - FindLfpProvidersRequest, - FindLfpProvidersResponse, - LfpProvider, - LinkLfpProviderRequest, - LinkLfpProviderResponse, -) -from .omnichannelsettings import ( - About, - CreateOmnichannelSettingRequest, - GetOmnichannelSettingRequest, - InStock, - InventoryVerification, - LfpLink, - ListOmnichannelSettingsRequest, - ListOmnichannelSettingsResponse, - OmnichannelSetting, - OnDisplayToOrder, - Pickup, - RequestInventoryVerificationRequest, - RequestInventoryVerificationResponse, - ReviewState, - UpdateOmnichannelSettingRequest, -) -from .online_return_policy import ( - CreateOnlineReturnPolicyRequest, - DeleteOnlineReturnPolicyRequest, - GetOnlineReturnPolicyRequest, - ListOnlineReturnPoliciesRequest, - ListOnlineReturnPoliciesResponse, - OnlineReturnPolicy, - UpdateOnlineReturnPolicyRequest, -) -from .phoneverificationstate import ( - PhoneVerificationState, -) -from .programs import ( - DisableProgramRequest, - EnableProgramRequest, - GetProgramRequest, - ListProgramsRequest, - ListProgramsResponse, - Program, -) -from .regions import ( - CreateRegionRequest, - DeleteRegionRequest, - GetRegionRequest, - ListRegionsRequest, - ListRegionsResponse, - Region, - UpdateRegionRequest, -) -from .shippingsettings import ( - Address, - BusinessDayConfig, - CarrierRate, - CutoffTime, - DeliveryTime, - Distance, - GetShippingSettingsRequest, - Headers, - InsertShippingSettingsRequest, - LocationIdSet, - MinimumOrderValueTable, - RateGroup, - Row, - Service, - ShippingSettings, - Table, - TransitTable, - Value, - Warehouse, - WarehouseBasedDeliveryTime, - WarehouseCutoffTime, -) -from .tax_rule import ( - TaxRule, -) -from .termsofservice import ( - AcceptTermsOfServiceRequest, - GetTermsOfServiceRequest, - RetrieveLatestTermsOfServiceRequest, - TermsOfService, -) -from .termsofserviceagreementstate import ( - Accepted, - GetTermsOfServiceAgreementStateRequest, - Required, - RetrieveForApplicationTermsOfServiceAgreementStateRequest, - TermsOfServiceAgreementState, -) -from .termsofservicekind import ( - TermsOfServiceKind, -) -from .user import ( - CreateUserRequest, - DeleteUserRequest, - GetUserRequest, - ListUsersRequest, - ListUsersResponse, - UpdateUserRequest, - User, -) - -__all__ = ( - 'AccessRight', - 'AccountTax', - 'GetAccountTaxRequest', - 'ListAccountTaxRequest', - 'ListAccountTaxResponse', - 'UpdateAccountTaxRequest', - 'AccountIssue', - 'ListAccountIssuesRequest', - 'ListAccountIssuesResponse', - 'Account', - 'CreateAndConfigureAccountRequest', - 'DeleteAccountRequest', - 'GetAccountRequest', - 'ListAccountsRequest', - 'ListAccountsResponse', - 'ListSubAccountsRequest', - 'ListSubAccountsResponse', - 'UpdateAccountRequest', - 'AccountAggregation', - 'AutofeedSettings', - 'GetAutofeedSettingsRequest', - 'UpdateAutofeedSettingsRequest', - 'AutomaticImageImprovements', - 'AutomaticImprovements', - 'AutomaticItemUpdates', - 'AutomaticShippingImprovements', - 'GetAutomaticImprovementsRequest', - 'UpdateAutomaticImprovementsRequest', - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - 'CheckoutSettings', - 'CreateCheckoutSettingsRequest', - 'DeleteCheckoutSettingsRequest', - 'GetCheckoutSettingsRequest', - 'UpdateCheckoutSettingsRequest', - 'UriSettings', - 'CustomerService', - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - 'GbpAccount', - 'LinkGbpAccountRequest', - 'LinkGbpAccountResponse', - 'ListGbpAccountsRequest', - 'ListGbpAccountsResponse', - 'ClaimHomepageRequest', - 'GetHomepageRequest', - 'Homepage', - 'UnclaimHomepageRequest', - 'UpdateHomepageRequest', - 'FindLfpProvidersRequest', - 'FindLfpProvidersResponse', - 'LfpProvider', - 'LinkLfpProviderRequest', - 'LinkLfpProviderResponse', - 'About', - 'CreateOmnichannelSettingRequest', - 'GetOmnichannelSettingRequest', - 'InStock', - 'InventoryVerification', - 'LfpLink', - 'ListOmnichannelSettingsRequest', - 'ListOmnichannelSettingsResponse', - 'OmnichannelSetting', - 'OnDisplayToOrder', - 'Pickup', - 'RequestInventoryVerificationRequest', - 'RequestInventoryVerificationResponse', - 'ReviewState', - 'UpdateOmnichannelSettingRequest', - 'CreateOnlineReturnPolicyRequest', - 'DeleteOnlineReturnPolicyRequest', - 'GetOnlineReturnPolicyRequest', - 'ListOnlineReturnPoliciesRequest', - 'ListOnlineReturnPoliciesResponse', - 'OnlineReturnPolicy', - 'UpdateOnlineReturnPolicyRequest', - 'PhoneVerificationState', - 'DisableProgramRequest', - 'EnableProgramRequest', - 'GetProgramRequest', - 'ListProgramsRequest', - 'ListProgramsResponse', - 'Program', - 'CreateRegionRequest', - 'DeleteRegionRequest', - 'GetRegionRequest', - 'ListRegionsRequest', - 'ListRegionsResponse', - 'Region', - 'UpdateRegionRequest', - 'Address', - 'BusinessDayConfig', - 'CarrierRate', - 'CutoffTime', - 'DeliveryTime', - 'Distance', - 'GetShippingSettingsRequest', - 'Headers', - 'InsertShippingSettingsRequest', - 'LocationIdSet', - 'MinimumOrderValueTable', - 'RateGroup', - 'Row', - 'Service', - 'ShippingSettings', - 'Table', - 'TransitTable', - 'Value', - 'Warehouse', - 'WarehouseBasedDeliveryTime', - 'WarehouseCutoffTime', - 'TaxRule', - 'AcceptTermsOfServiceRequest', - 'GetTermsOfServiceRequest', - 'RetrieveLatestTermsOfServiceRequest', - 'TermsOfService', - 'Accepted', - 'GetTermsOfServiceAgreementStateRequest', - 'Required', - 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', - 'TermsOfServiceAgreementState', - 'TermsOfServiceKind', - 'CreateUserRequest', - 'DeleteUserRequest', - 'GetUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - 'UpdateUserRequest', - 'User', -) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.py deleted file mode 100644 index c3620ee9ff75..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accessright.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 __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'AccessRight', - }, -) - - -class AccessRight(proto.Enum): - r"""The access right. - - Values: - ACCESS_RIGHT_UNSPECIFIED (0): - Default value. This value is unused. - STANDARD (1): - Standard access rights. - ADMIN (2): - Admin access rights. - PERFORMANCE_REPORTING (3): - Users with this right have access to - performance and insights. - """ - ACCESS_RIGHT_UNSPECIFIED = 0 - STANDARD = 1 - ADMIN = 2 - PERFORMANCE_REPORTING = 3 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py deleted file mode 100644 index 57bd399773f3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/account_tax.py +++ /dev/null @@ -1,167 +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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import tax_rule - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'AccountTax', - 'GetAccountTaxRequest', - 'UpdateAccountTaxRequest', - 'ListAccountTaxRequest', - 'ListAccountTaxResponse', - }, -) - - -class AccountTax(proto.Message): - r"""The tax settings of a merchant account. All methods require - the admin role. - - Attributes: - name (str): - Identifier. The name of the tax setting. Format: - "{account_tax.name=accounts/{account}}". - account (int): - Output only. The ID of the account to which - these account tax settings belong. - tax_rules (MutableSequence[google.shopping.merchant_accounts_v1beta.types.TaxRule]): - Tax rules. "Define the tax rules in each - region. No tax will be presented if a region has - no rule.". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account: int = proto.Field( - proto.INT64, - number=2, - ) - tax_rules: MutableSequence[tax_rule.TaxRule] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=tax_rule.TaxRule, - ) - - -class GetAccountTaxRequest(proto.Message): - r"""Request to get tax settings - - Attributes: - name (str): - Required. The name from which tax settings - will be retrieved - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAccountTaxRequest(proto.Message): - r"""Request to update the tax settings - - Attributes: - account_tax (google.shopping.merchant_accounts_v1beta.types.AccountTax): - Required. The tax setting that will be - updated - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated - """ - - account_tax: 'AccountTax' = proto.Field( - proto.MESSAGE, - number=1, - message='AccountTax', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListAccountTaxRequest(proto.Message): - r"""Request to list all sub-account tax settings only for the - requesting merchant This method can only be called on a - multi-client account, otherwise it'll return an error. - - Attributes: - parent (str): - Required. The parent, which owns this - collection of account tax. Format: - accounts/{account} - page_size (int): - The maximum number of tax settings to return - in the response, used for paging. - page_token (str): - The token returned by 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 ListAccountTaxResponse(proto.Message): - r"""Response to account tax list request - This method can only be called on a multi-client account, - otherwise it'll return an error. - - Attributes: - account_taxes (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountTax]): - Page of accounttax settings - next_page_token (str): - The token for the retrieval of the next page - of account tax settings. - """ - - @property - def raw_page(self): - return self - - account_taxes: MutableSequence['AccountTax'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AccountTax', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.py deleted file mode 100644 index 5cbd1eb246d3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountissue.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 - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'AccountIssue', - 'ListAccountIssuesRequest', - 'ListAccountIssuesResponse', - }, -) - - -class AccountIssue(proto.Message): - r"""An - ```AccountIssue`` `__. - - Attributes: - name (str): - Identifier. The resource name of the account issue. Format: - ``accounts/{account}/issues/{id}`` - title (str): - The localized title of the issue. - severity (google.shopping.merchant_accounts_v1beta.types.AccountIssue.Severity): - The overall severity of the issue. - impacted_destinations (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountIssue.ImpactedDestination]): - The impact this issue has on various - destinations. - detail (str): - Further localized details about the issue. - documentation_uri (str): - Link to Merchant Center Help Center providing - further information about the issue and how to - fix it. - """ - class Severity(proto.Enum): - r"""All possible issue severities. - - Values: - SEVERITY_UNSPECIFIED (0): - The severity is unknown. - CRITICAL (1): - The issue causes offers to not serve. - ERROR (2): - The issue might affect offers (in the future) - or might be an indicator of issues with offers. - SUGGESTION (3): - The issue is a suggestion for improvement. - """ - SEVERITY_UNSPECIFIED = 0 - CRITICAL = 1 - ERROR = 2 - SUGGESTION = 3 - - class ImpactedDestination(proto.Message): - r"""The impact of the issue on a destination. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - reporting_context (google.shopping.type.types.ReportingContext.ReportingContextEnum): - The impacted reporting context. - - This field is a member of `oneof`_ ``_reporting_context``. - impacts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountIssue.ImpactedDestination.Impact]): - The (negative) impact for various regions on - the given destination. - """ - - class Impact(proto.Message): - r"""The impact of the issue on a region. - - Attributes: - region_code (str): - The `CLDR region code `__ where - this issue applies. - severity (google.shopping.merchant_accounts_v1beta.types.AccountIssue.Severity): - The severity of the issue on the destination - and region. - """ - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - severity: 'AccountIssue.Severity' = proto.Field( - proto.ENUM, - number=2, - enum='AccountIssue.Severity', - ) - - reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( - proto.ENUM, - number=1, - optional=True, - enum=types.ReportingContext.ReportingContextEnum, - ) - impacts: MutableSequence['AccountIssue.ImpactedDestination.Impact'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AccountIssue.ImpactedDestination.Impact', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - title: str = proto.Field( - proto.STRING, - number=2, - ) - severity: Severity = proto.Field( - proto.ENUM, - number=3, - enum=Severity, - ) - impacted_destinations: MutableSequence[ImpactedDestination] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=ImpactedDestination, - ) - detail: str = proto.Field( - proto.STRING, - number=5, - ) - documentation_uri: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListAccountIssuesRequest(proto.Message): - r"""Request message for the ``ListAccountIssues`` method. - - Attributes: - parent (str): - Required. The parent, which owns this collection of issues. - Format: ``accounts/{account}`` - page_size (int): - Optional. The maximum number of issues to - return. The service may return fewer than this - value. If unspecified, at most 50 users will be - returned. The maximum value is 100; values above - 100 will be coerced to 100 - page_token (str): - Optional. A page token, received from a previous - ``ListAccountIssues`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListAccountIssues`` must match the call that provided the - page token. - language_code (str): - Optional. The issues in the response will have - human-readable fields in the given language. The format is - `BCP-47 `__, such as - ``en-US`` or ``sr-Latn``. If not value is provided, - ``en-US`` will be used. - time_zone (str): - Optional. The `IANA `__ - timezone used to localize times in human-readable fields. - For example 'America/Los_Angeles'. If not set, - 'America/Los_Angeles' will be used. - """ - - 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, - ) - language_code: str = proto.Field( - proto.STRING, - number=4, - ) - time_zone: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListAccountIssuesResponse(proto.Message): - r"""Response message for the ``ListAccountIssues`` method. - - Attributes: - account_issues (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccountIssue]): - The issues from the specified account. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - account_issues: MutableSequence['AccountIssue'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='AccountIssue', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py deleted file mode 100644 index 1e367e052f02..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accounts.py +++ /dev/null @@ -1,408 +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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import accountservices -from google.shopping.merchant_accounts_v1beta.types import user -from google.type import datetime_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'Account', - 'GetAccountRequest', - 'CreateAndConfigureAccountRequest', - 'DeleteAccountRequest', - 'UpdateAccountRequest', - 'ListAccountsRequest', - 'ListAccountsResponse', - 'ListSubAccountsRequest', - 'ListSubAccountsResponse', - }, -) - - -class Account(proto.Message): - r"""An account. - - Attributes: - name (str): - Identifier. The resource name of the account. Format: - ``accounts/{account}`` - account_id (int): - Output only. The ID of the account. - account_name (str): - Required. A human-readable name of the account. See `store - name `__ - and `business - name `__ - for more information. - adult_content (bool): - Whether this account contains adult content. - test_account (bool): - Output only. Whether this is a test account. - time_zone (google.type.datetime_pb2.TimeZone): - Required. The time zone of the account. - - On writes, ``time_zone`` sets both the - ``reporting_time_zone`` and the ``display_time_zone``. - - For reads, ``time_zone`` always returns the - ``display_time_zone``. If ``display_time_zone`` doesn't - exist for your account, ``time_zone`` is empty. - language_code (str): - Required. The account's `BCP-47 language - code `__, such as - ``en-US`` or ``sr-Latn``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account_id: int = proto.Field( - proto.INT64, - number=2, - ) - account_name: str = proto.Field( - proto.STRING, - number=3, - ) - adult_content: bool = proto.Field( - proto.BOOL, - number=4, - ) - test_account: bool = proto.Field( - proto.BOOL, - number=5, - ) - time_zone: datetime_pb2.TimeZone = proto.Field( - proto.MESSAGE, - number=6, - message=datetime_pb2.TimeZone, - ) - language_code: str = proto.Field( - proto.STRING, - number=7, - ) - - -class GetAccountRequest(proto.Message): - r"""Request message for the ``GetAccount`` method. - - Attributes: - name (str): - Required. The name of the account to retrieve. Format: - ``accounts/{account}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateAndConfigureAccountRequest(proto.Message): - r"""Request message for the ``CreateAndConfigureAccount`` method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - account (google.shopping.merchant_accounts_v1beta.types.Account): - Required. The account to be created. - users (MutableSequence[google.shopping.merchant_accounts_v1beta.types.CreateUserRequest]): - Optional. Users to be added to the account. - accept_terms_of_service (google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest.AcceptTermsOfService): - Optional. The Terms of Service (ToS) to be - accepted immediately upon account creation. - - This field is a member of `oneof`_ ``_accept_terms_of_service``. - service (MutableSequence[google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest.AddAccountService]): - Required. An account service between the account to be - created and the provider account is initialized as part of - the creation. At least one such service needs to be - provided. Currently exactly one of these needs to be - ``account_aggregation``, which means you can only create sub - accounts, not standalone account through this method. - Additional ``account_management`` or ``product_management`` - services may be provided. - """ - - class AcceptTermsOfService(proto.Message): - r"""Reference to a Terms of Service resource. - - Attributes: - name (str): - Required. The resource name of the terms of service version - in the format ``termsOfService/{version}``. To retrieve the - latest version, use the - `termsOfService.retrieveLatest `__ - method. - region_code (str): - Required. Region code as defined by - `CLDR `__. This is either a - country when the ToS applies specifically to that country or - ``001`` when it applies globally. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - ) - - class AddAccountService(proto.Message): - r"""Additional instructions to add account services during - creation of the account. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - account_aggregation (google.shopping.merchant_accounts_v1beta.types.AccountAggregation): - The provider is an - `aggregator `__ - for the account. Payload for service type Account - Aggregation. - - This field is a member of `oneof`_ ``service_type``. - provider (str): - Optional. The provider of the service. Format: - ``accounts/{account}`` - - This field is a member of `oneof`_ ``_provider``. - """ - - account_aggregation: accountservices.AccountAggregation = proto.Field( - proto.MESSAGE, - number=103, - oneof='service_type', - message=accountservices.AccountAggregation, - ) - provider: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - - account: 'Account' = proto.Field( - proto.MESSAGE, - number=1, - message='Account', - ) - users: MutableSequence[user.CreateUserRequest] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=user.CreateUserRequest, - ) - accept_terms_of_service: AcceptTermsOfService = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=AcceptTermsOfService, - ) - service: MutableSequence[AddAccountService] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=AddAccountService, - ) - - -class DeleteAccountRequest(proto.Message): - r"""Request message for the ``DeleteAccount`` method. - - Attributes: - name (str): - Required. The name of the account to delete. Format: - ``accounts/{account}`` - force (bool): - Optional. If set to ``true``, the account is deleted even if - it provides services to other accounts or has processed - offers. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class UpdateAccountRequest(proto.Message): - r"""Request message for the ``UpdateAccount`` method. - - Attributes: - account (google.shopping.merchant_accounts_v1beta.types.Account): - Required. The new version of the account. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - account: 'Account' = proto.Field( - proto.MESSAGE, - number=1, - message='Account', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListAccountsRequest(proto.Message): - r"""Request message for the ``ListAccounts`` method. - - Attributes: - page_size (int): - Optional. The maximum number of accounts to - return. The service may return fewer than this - value. If unspecified, at most 250 accounts are - returned. The maximum value is 500; values above - 500 are coerced to 500. - page_token (str): - Optional. A page token, received from a previous - ``ListAccounts`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListAccounts`` must match the call that provided the page - token. - filter (str): - Optional. Returns only accounts that match the - `filter `__. For more - details, see the `filter syntax - reference `__. - """ - - page_size: int = proto.Field( - proto.INT32, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListAccountsResponse(proto.Message): - r"""Response message for the ``ListAccounts`` method. - - Attributes: - accounts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Account]): - The accounts matching the ``ListAccountsRequest``. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - accounts: MutableSequence['Account'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Account', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListSubAccountsRequest(proto.Message): - r"""Request message for the ``ListSubAccounts`` method. - - Attributes: - provider (str): - Required. The parent account. Format: ``accounts/{account}`` - page_size (int): - Optional. The maximum number of accounts to - return. The service may return fewer than this - value. If unspecified, at most 250 accounts are - returned. The maximum value is 500; values above - 500 are coerced to 500. - page_token (str): - Optional. A page token, received from a previous - ``ListAccounts`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListAccounts`` must match the call that provided the page - token. - """ - - provider: 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 ListSubAccountsResponse(proto.Message): - r"""Response message for the ``ListSubAccounts`` method. - - Attributes: - accounts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Account]): - The accounts for which the given parent - account is an aggregator. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - accounts: MutableSequence['Account'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Account', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py deleted file mode 100644 index a3173fe74b97..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/accountservices.py +++ /dev/null @@ -1,36 +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 - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'AccountAggregation', - }, -) - - -class AccountAggregation(proto.Message): - r"""``AccountAggregation`` payload. - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py deleted file mode 100644 index a9a0952a44bf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/autofeedsettings.py +++ /dev/null @@ -1,111 +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.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'AutofeedSettings', - 'GetAutofeedSettingsRequest', - 'UpdateAutofeedSettingsRequest', - }, -) - - -class AutofeedSettings(proto.Message): - r"""Collection of information related to the - `autofeed `__ - settings. - - Attributes: - name (str): - Identifier. The resource name of the autofeed settings. - Format: ``accounts/{account}/autofeedSettings``. - enable_products (bool): - Required. Enables or disables product crawling through the - autofeed for the given account. Autofeed accounts must meet - `certain - conditions `__, - which can be checked through the ``eligible`` field. The - account must **not** be a marketplace. When the autofeed is - enabled for the first time, the products usually appear - instantly. When re-enabling, it might take up to 24 hours - for products to appear. - eligible (bool): - Output only. Determines whether merchant is - eligible for being enrolled into an autofeed. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - enable_products: bool = proto.Field( - proto.BOOL, - number=2, - ) - eligible: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class GetAutofeedSettingsRequest(proto.Message): - r"""Request message for the ``GetAutofeedSettings`` method. - - Attributes: - name (str): - Required. The resource name of the autofeed settings. - Format: ``accounts/{account}/autofeedSettings`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAutofeedSettingsRequest(proto.Message): - r"""Request message for the ``UpdateAutofeedSettings`` method. - - Attributes: - autofeed_settings (google.shopping.merchant_accounts_v1beta.types.AutofeedSettings): - Required. The new version of the autofeed - setting. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - autofeed_settings: 'AutofeedSettings' = proto.Field( - proto.MESSAGE, - number=1, - message='AutofeedSettings', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py deleted file mode 100644 index c4d67cbfcd3b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/automaticimprovements.py +++ /dev/null @@ -1,386 +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.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'AutomaticImprovements', - 'AutomaticItemUpdates', - 'AutomaticImageImprovements', - 'AutomaticShippingImprovements', - 'GetAutomaticImprovementsRequest', - 'UpdateAutomaticImprovementsRequest', - }, -) - - -class AutomaticImprovements(proto.Message): - r"""Collection of information related to the `automatic - improvements `__ - of an account. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the automatic improvements. - Format: ``accounts/{account}/automaticImprovements``. - item_updates (google.shopping.merchant_accounts_v1beta.types.AutomaticItemUpdates): - Turning on `item - updates `__ - allows Google to automatically update items for you. When - item updates are on, Google uses the structured data markup - on the website and advanced data extractors to update the - price and availability of the items. When the item updates - are off, items with mismatched data aren't shown. This field - is only updated (cleared) if provided in the update mask. - - This field is a member of `oneof`_ ``_item_updates``. - image_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticImageImprovements): - This improvement will attempt to automatically correct - submitted images if they don't meet the `image - requirements `__, - for example, removing overlays. If successful, the image - will be replaced and approved. This improvement is only - applied to images of disapproved offers. For more - information see: `Automatic image - improvements `__ - This field is only updated (cleared) if provided in the - update mask. - - This field is a member of `oneof`_ ``_image_improvements``. - shipping_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticShippingImprovements): - Not available for MCAs - `accounts `__. - By turning on `automatic shipping - improvements `__, - you are allowing Google to improve the accuracy of your - delivery times shown to shoppers using Google. More accurate - delivery times, especially when faster, typically lead to - better conversion rates. Google will improve your estimated - delivery times based on various factors: - - - Delivery address of an order - - Current handling time and shipping time settings - - Estimated weekdays or business days - - Parcel tracking data This field is only updated (cleared) - if provided in the update mask. - - This field is a member of `oneof`_ ``_shipping_improvements``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - item_updates: 'AutomaticItemUpdates' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='AutomaticItemUpdates', - ) - image_improvements: 'AutomaticImageImprovements' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='AutomaticImageImprovements', - ) - shipping_improvements: 'AutomaticShippingImprovements' = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message='AutomaticShippingImprovements', - ) - - -class AutomaticItemUpdates(proto.Message): - r"""Turning on `item - updates `__ - allows Google to automatically update items for you. When item - updates are on, Google uses the structured data markup on the - website and advanced data extractors to update the price and - availability of the items. When the item updates are off, items with - mismatched data aren't shown. - - Attributes: - account_item_updates_settings (google.shopping.merchant_accounts_v1beta.types.AutomaticItemUpdates.ItemUpdatesAccountLevelSettings): - Optional. Determines which attributes of the - items should be automatically updated. If this - field is not present and provided in the update - mask, then the settings will be deleted. If - there are no settings for subaccount, they are - inherited from aggregator. - effective_allow_price_updates (bool): - Output only. The effective value of allow_price_updates. If - account_item_updates_settings is present, then this value is - the same. Otherwise, it represents the inherited value of - the parent account. The default value is true if no settings - are present. Read-only. - effective_allow_availability_updates (bool): - Output only. The effective value of - allow_availability_updates. If account_item_updates_settings - is present, then this value is the same. Otherwise, it - represents the inherited value of the parent account. The - default value is true if no settings are present. Read-only. - effective_allow_strict_availability_updates (bool): - Output only. The effective value of - allow_strict_availability_updates. If - account_item_updates_settings is present, then this value is - the same. Otherwise, it represents the inherited value of - the parent account. The default value is true if no settings - are present. Read-only. - effective_allow_condition_updates (bool): - Output only. The effective value of allow_condition_updates. - If account_item_updates_settings is present, then this value - is the same. Otherwise, it represents the inherited value of - the parent account. The default value is true if no settings - are present. Read-only. - """ - - class ItemUpdatesAccountLevelSettings(proto.Message): - r"""Settings for the Automatic Item Updates. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - allow_price_updates (bool): - If price updates are enabled, Google always - updates the active price with the crawled - information. - - This field is a member of `oneof`_ ``_allow_price_updates``. - allow_availability_updates (bool): - If availability updates are enabled, any previous - availability values get overwritten if Google finds an - out-of-stock annotation on the offer's page. If additionally - ``allow_strict_availability_updates`` field is set to true, - values get overwritten if Google finds an in-stock - annotation on the offer’s page. - - This field is a member of `oneof`_ ``_allow_availability_updates``. - allow_strict_availability_updates (bool): - If ``allow_availability_updates`` is enabled, items are - automatically updated in all your Shopping target countries. - By default, availability updates will only be applied to - items that are 'out of stock' on your website but 'in stock' - on Shopping. Set this to true to also update items that are - 'in stock' on your website, but 'out of stock' on Google - Shopping. In order for this field to have an effect, you - must also set ``allow_availability_updates``. - - This field is a member of `oneof`_ ``_allow_strict_availability_updates``. - allow_condition_updates (bool): - If condition updates are enabled, Google - always updates item condition with the condition - detected from the details of your product. - - This field is a member of `oneof`_ ``_allow_condition_updates``. - """ - - allow_price_updates: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - allow_availability_updates: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - allow_strict_availability_updates: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - allow_condition_updates: bool = proto.Field( - proto.BOOL, - number=4, - optional=True, - ) - - account_item_updates_settings: ItemUpdatesAccountLevelSettings = proto.Field( - proto.MESSAGE, - number=1, - message=ItemUpdatesAccountLevelSettings, - ) - effective_allow_price_updates: bool = proto.Field( - proto.BOOL, - number=2, - ) - effective_allow_availability_updates: bool = proto.Field( - proto.BOOL, - number=3, - ) - effective_allow_strict_availability_updates: bool = proto.Field( - proto.BOOL, - number=4, - ) - effective_allow_condition_updates: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class AutomaticImageImprovements(proto.Message): - r"""This improvement will attempt to automatically correct submitted - images if they don't meet the `image - requirements `__, - for example, removing overlays. If successful, the image will be - replaced and approved. This improvement is only applied to images of - disapproved offers. For more information see: `Automatic image - improvements `__ - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - account_image_improvements_settings (google.shopping.merchant_accounts_v1beta.types.AutomaticImageImprovements.ImageImprovementsAccountLevelSettings): - Optional. Determines how the images should be - automatically updated. If this field is not - present and provided in the update mask, then - the settings will be deleted. If there are no - settings for subaccount, they are inherited from - aggregator. - - This field is a member of `oneof`_ ``_account_image_improvements_settings``. - effective_allow_automatic_image_improvements (bool): - Output only. The effective value of - allow_automatic_image_improvements. If - account_image_improvements_settings is present, then this - value is the same. Otherwise, it represents the inherited - value of the parent account. Read-only. - """ - - class ImageImprovementsAccountLevelSettings(proto.Message): - r"""Settings for the Automatic Image Improvements. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - allow_automatic_image_improvements (bool): - Enables automatic image improvements. - - This field is a member of `oneof`_ ``_allow_automatic_image_improvements``. - """ - - allow_automatic_image_improvements: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - - account_image_improvements_settings: ImageImprovementsAccountLevelSettings = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message=ImageImprovementsAccountLevelSettings, - ) - effective_allow_automatic_image_improvements: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class AutomaticShippingImprovements(proto.Message): - r"""Not available for MCAs - `accounts `__. - By turning on `automatic shipping - improvements `__, - you are allowing Google to improve the accuracy of your delivery - times shown to shoppers using Google. More accurate delivery times, - especially when faster, typically lead to better conversion rates. - Google will improve your estimated delivery times based on various - factors: - - - Delivery address of an order - - Current handling time and shipping time settings - - Estimated weekdays or business days - - Parcel tracking data - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - allow_shipping_improvements (bool): - Enables automatic shipping improvements. - - This field is a member of `oneof`_ ``_allow_shipping_improvements``. - """ - - allow_shipping_improvements: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - - -class GetAutomaticImprovementsRequest(proto.Message): - r"""Request message for the ``GetAutomaticImprovements`` method. - - Attributes: - name (str): - Required. The resource name of the automatic improvements. - Format: ``accounts/{account}/automaticImprovements`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateAutomaticImprovementsRequest(proto.Message): - r"""Request message for the ``UpdateAutomaticImprovements`` method. - - Attributes: - automatic_improvements (google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements): - Required. The new version of the automatic - imrovements. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. The following fields - are supported (in both ``snake_case`` and - ``lowerCamelCase``): - - - ``item_updates`` - - ``item_updates.account_level_settings`` - - ``image_improvements`` - - ``image_improvements.account_level_settings`` - - ``shipping_improvements`` - - ``shipping_improvements.allow_shipping_improvements`` - """ - - automatic_improvements: 'AutomaticImprovements' = proto.Field( - proto.MESSAGE, - number=1, - message='AutomaticImprovements', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py deleted file mode 100644 index c17161fc7d74..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessidentity.py +++ /dev/null @@ -1,204 +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.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - }, -) - - -class BusinessIdentity(proto.Message): - r"""Collection of information related to the `identity of a - business `__. - - Attributes: - name (str): - Identifier. The resource name of the business identity. - Format: ``accounts/{account}/businessIdentity`` - promotions_consent (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.PromotionsConsent): - Optional. Whether the identity attributes may - be used for promotions. - black_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): - Optional. Specifies whether the business identifies itself - as being black-owned. This optional field will only be - available for merchants with a business country set to - ``US``. It is also not applicable for marketplaces or - marketplace sellers. - women_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): - Optional. Specifies whether the business identifies itself - as being women-owned. This optional field will only be - available for merchants with a business country set to - ``US``. It is also not applicable for marketplaces or - marketplace sellers. - veteran_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): - Optional. Specifies whether the business identifies itself - as being veteran-owned. This optional field will only be - available for merchants with a business country set to - ``US``. It is also not applicable for marketplaces or - marketplace sellers. - latino_owned (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): - Optional. Specifies whether the business identifies itself - as being latino-owned. This optional field will only be - available for merchants with a business country set to - ``US``. It is also not applicable for marketplaces or - marketplace sellers. - small_business (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute): - Optional. Specifies whether the business identifies itself - as a small business. This optional field will only be - available for merchants with a business country set to - ``US``. It is also not applicable for marketplaces. - """ - class PromotionsConsent(proto.Enum): - r"""All possible settings regarding promotions related to the - business identity. - - Values: - PROMOTIONS_CONSENT_UNSPECIFIED (0): - Default value indicating that no selection - was made. - PROMOTIONS_CONSENT_GIVEN (1): - Indicates that the account consented to - having their business identity used for - promotions. - PROMOTIONS_CONSENT_DENIED (2): - Indicates that the account did not consent to - having their business identity used for - promotions. - """ - PROMOTIONS_CONSENT_UNSPECIFIED = 0 - PROMOTIONS_CONSENT_GIVEN = 1 - PROMOTIONS_CONSENT_DENIED = 2 - - class IdentityAttribute(proto.Message): - r"""All information related to an identity attribute. - - Attributes: - identity_declaration (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity.IdentityAttribute.IdentityDeclaration): - Required. The declaration of identity for - this attribute. - """ - class IdentityDeclaration(proto.Enum): - r"""All possible settings regarding the declaration of an - identity. - - Values: - IDENTITY_DECLARATION_UNSPECIFIED (0): - Default value indicating that no selection - was made. - SELF_IDENTIFIES_AS (1): - Indicates that the account identifies with - the attribute. - DOES_NOT_SELF_IDENTIFY_AS (2): - Indicates that the account does not identify - with the attribute. - """ - IDENTITY_DECLARATION_UNSPECIFIED = 0 - SELF_IDENTIFIES_AS = 1 - DOES_NOT_SELF_IDENTIFY_AS = 2 - - identity_declaration: 'BusinessIdentity.IdentityAttribute.IdentityDeclaration' = proto.Field( - proto.ENUM, - number=1, - enum='BusinessIdentity.IdentityAttribute.IdentityDeclaration', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - promotions_consent: PromotionsConsent = proto.Field( - proto.ENUM, - number=2, - enum=PromotionsConsent, - ) - black_owned: IdentityAttribute = proto.Field( - proto.MESSAGE, - number=3, - message=IdentityAttribute, - ) - women_owned: IdentityAttribute = proto.Field( - proto.MESSAGE, - number=4, - message=IdentityAttribute, - ) - veteran_owned: IdentityAttribute = proto.Field( - proto.MESSAGE, - number=5, - message=IdentityAttribute, - ) - latino_owned: IdentityAttribute = proto.Field( - proto.MESSAGE, - number=6, - message=IdentityAttribute, - ) - small_business: IdentityAttribute = proto.Field( - proto.MESSAGE, - number=7, - message=IdentityAttribute, - ) - - -class GetBusinessIdentityRequest(proto.Message): - r"""Request message for the ``GetBusinessIdentity`` method. - - Attributes: - name (str): - Required. The resource name of the business identity. - Format: ``accounts/{account}/businessIdentity`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateBusinessIdentityRequest(proto.Message): - r"""Request message for the ``UpdateBusinessIdentity`` method. - - Attributes: - business_identity (google.shopping.merchant_accounts_v1beta.types.BusinessIdentity): - Required. The new version of the business - identity. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - business_identity: 'BusinessIdentity' = proto.Field( - proto.MESSAGE, - number=1, - message='BusinessIdentity', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py deleted file mode 100644 index a92014b2ae3a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/businessinfo.py +++ /dev/null @@ -1,148 +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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import customerservice -from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate -from google.type import phone_number_pb2 # type: ignore -from google.type import postal_address_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - }, -) - - -class BusinessInfo(proto.Message): - r"""Collection of information related to a business. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the business info. Format: - ``accounts/{account}/businessInfo`` - address (google.type.postal_address_pb2.PostalAddress): - Optional. The address of the business. - - This field is a member of `oneof`_ ``_address``. - phone (google.type.phone_number_pb2.PhoneNumber): - Output only. The phone number of the - business. - - This field is a member of `oneof`_ ``_phone``. - phone_verification_state (google.shopping.merchant_accounts_v1beta.types.PhoneVerificationState): - Output only. The phone verification state of - the business. - - This field is a member of `oneof`_ ``_phone_verification_state``. - customer_service (google.shopping.merchant_accounts_v1beta.types.CustomerService): - Optional. The customer service of the - business. - - This field is a member of `oneof`_ ``_customer_service``. - korean_business_registration_number (str): - Optional. The 10-digit `Korean business registration - number `__ - separated with dashes in the format: XXX-XX-XXXXX. - - This field is a member of `oneof`_ ``_korean_business_registration_number``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - address: postal_address_pb2.PostalAddress = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=postal_address_pb2.PostalAddress, - ) - phone: phone_number_pb2.PhoneNumber = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=phone_number_pb2.PhoneNumber, - ) - phone_verification_state: phoneverificationstate.PhoneVerificationState = proto.Field( - proto.ENUM, - number=4, - optional=True, - enum=phoneverificationstate.PhoneVerificationState, - ) - customer_service: customerservice.CustomerService = proto.Field( - proto.MESSAGE, - number=5, - optional=True, - message=customerservice.CustomerService, - ) - korean_business_registration_number: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - - -class GetBusinessInfoRequest(proto.Message): - r"""Request message for the ``GetBusinessInfo`` method. - - Attributes: - name (str): - Required. The resource name of the business info. Format: - ``accounts/{account}/businessInfo`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateBusinessInfoRequest(proto.Message): - r"""Request message for the ``UpdateBusinessInfo`` method. - - Attributes: - business_info (google.shopping.merchant_accounts_v1beta.types.BusinessInfo): - Required. The new version of the business - info. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - business_info: 'BusinessInfo' = proto.Field( - proto.MESSAGE, - number=1, - message='BusinessInfo', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py deleted file mode 100644 index 88e49becac97..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/checkoutsettings.py +++ /dev/null @@ -1,316 +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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.type.types import types - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'GetCheckoutSettingsRequest', - 'CreateCheckoutSettingsRequest', - 'UpdateCheckoutSettingsRequest', - 'DeleteCheckoutSettingsRequest', - 'CheckoutSettings', - 'UriSettings', - }, -) - - -class GetCheckoutSettingsRequest(proto.Message): - r"""Request message for ``GetCheckoutSettings`` method. - - Attributes: - name (str): - Required. The name/identifier of the merchant account. - Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateCheckoutSettingsRequest(proto.Message): - r"""Request message for the ``CreateCheckoutSettings`` method. - - Attributes: - parent (str): - Required. The merchant account for which the - ``CheckoutSettings`` will be created. - checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): - Required. The ``CheckoutSettings`` object to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - checkout_settings: 'CheckoutSettings' = proto.Field( - proto.MESSAGE, - number=2, - message='CheckoutSettings', - ) - - -class UpdateCheckoutSettingsRequest(proto.Message): - r"""Request message for the ``UpdateCheckoutSettings`` method. - - Attributes: - checkout_settings (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings): - Required. The updated version of the ``CheckoutSettings``. - The ``name`` field is used to identify the - ``CheckoutSettings``. Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. The following fields - are supported (in both ``snake_case`` and - ``lowerCamelCase``): - - - ``eligible_destinations`` - - ``uri_settings`` - """ - - checkout_settings: 'CheckoutSettings' = proto.Field( - proto.MESSAGE, - number=1, - message='CheckoutSettings', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteCheckoutSettingsRequest(proto.Message): - r"""Request message for the ``DeleteCheckoutSettings`` method. - - Attributes: - name (str): - Required. The name/identifier of the merchant account. - Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CheckoutSettings(proto.Message): - r"""`CheckoutSettings `__ - for a specific merchant. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the program configuration - settings. Format: - ``accounts/{account}/programs/{program}/checkoutSettings`` - uri_settings (google.shopping.merchant_accounts_v1beta.types.UriSettings): - URI settings for cart or checkout URL. - - This field is a member of `oneof`_ ``_uri_settings``. - eligible_destinations (MutableSequence[google.shopping.type.types.Destination.DestinationEnum]): - Optional. The destinations to which the checkout program - applies, valid destination values are ``SHOPPING_ADS``, - ``FREE_LISTINGS`` - enrollment_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutEnrollmentState): - Output only. Reflects the merchant enrollment state in - ``Checkout`` program. - - This field is a member of `oneof`_ ``_enrollment_state``. - review_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutReviewState): - Output only. Reflects the merchant review state in - ``Checkout`` program. This is set based on the data quality - reviews of the URL provided by the merchant. A merchant with - enrollment state as ``ENROLLED`` can be in the following - review states: ``IN_REVIEW``, ``APPROVED`` or - ``DISAPPROVED``. A merchant must be in an - ``enrollment_state`` of ``ENROLLED`` before a review can - begin for the merchant.For more details, check the help - center doc. - - This field is a member of `oneof`_ ``_review_state``. - effective_uri_settings (google.shopping.merchant_accounts_v1beta.types.UriSettings): - Output only. The effective value of ``uri_settings`` for a - given merchant. If account level settings are present then - this value will be a copy of url settings. Otherwise, it - will have the value of the parent account (for only - marketplace sellers). - effective_enrollment_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutEnrollmentState): - Output only. The effective value of enrollment_state for a - given merchant ID. If account level settings are present - then this value will be a copy of the account level - settings. Otherwise, it will have the value of the parent - account (for only marketplace sellers). - - This field is a member of `oneof`_ ``_effective_enrollment_state``. - effective_review_state (google.shopping.merchant_accounts_v1beta.types.CheckoutSettings.CheckoutReviewState): - Output only. The effective value of ``review_state`` for a - given merchant ID. If account level settings are present - then this value will be a copy of the account level - settings. Otherwise, it will have the value of the parent - account (for only marketplace sellers). - - This field is a member of `oneof`_ ``_effective_review_state``. - """ - class CheckoutEnrollmentState(proto.Enum): - r"""Enum indicating the enrollment state of merchant in ``Checkout`` - program. - - Values: - CHECKOUT_ENROLLMENT_STATE_UNSPECIFIED (0): - Default enrollment state when enrollment - state is not specified. - INACTIVE (1): - Merchant has not enrolled into the program. - ENROLLED (2): - Merchant has enrolled into the program by - providing either an account level URL or - checkout URLs as part of their feed. - OPTED_OUT (3): - Merchant has previously enrolled but opted - out of the program. - """ - CHECKOUT_ENROLLMENT_STATE_UNSPECIFIED = 0 - INACTIVE = 1 - ENROLLED = 2 - OPTED_OUT = 3 - - class CheckoutReviewState(proto.Enum): - r"""Enum indicating the review state of merchant in ``Checkout`` - program. - - Values: - CHECKOUT_REVIEW_STATE_UNSPECIFIED (0): - Default review state when review state is not - specified. - IN_REVIEW (1): - Merchant provided URLs are being reviewed for - data quality issues. - APPROVED (2): - Merchant account has been approved. Indicates - the data quality checks have passed. - DISAPPROVED (3): - Merchant account has been disapproved due to - data quality issues. - """ - CHECKOUT_REVIEW_STATE_UNSPECIFIED = 0 - IN_REVIEW = 1 - APPROVED = 2 - DISAPPROVED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri_settings: 'UriSettings' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='UriSettings', - ) - eligible_destinations: MutableSequence[types.Destination.DestinationEnum] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=types.Destination.DestinationEnum, - ) - enrollment_state: CheckoutEnrollmentState = proto.Field( - proto.ENUM, - number=3, - optional=True, - enum=CheckoutEnrollmentState, - ) - review_state: CheckoutReviewState = proto.Field( - proto.ENUM, - number=4, - optional=True, - enum=CheckoutReviewState, - ) - effective_uri_settings: 'UriSettings' = proto.Field( - proto.MESSAGE, - number=5, - message='UriSettings', - ) - effective_enrollment_state: CheckoutEnrollmentState = proto.Field( - proto.ENUM, - number=6, - optional=True, - enum=CheckoutEnrollmentState, - ) - effective_review_state: CheckoutReviewState = proto.Field( - proto.ENUM, - number=7, - optional=True, - enum=CheckoutReviewState, - ) - - -class UriSettings(proto.Message): - r"""URL settings for cart or checkout URL. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - checkout_uri_template (str): - Checkout URL template. When the placeholders are expanded - will redirect the buyer to the merchant checkout page with - the item in the cart. For more details, check the `help - center - doc `__ - - This field is a member of `oneof`_ ``uri_template``. - cart_uri_template (str): - Cart URL template. When the placeholders are expanded will - redirect the buyer to the cart page on the merchant website - with the selected item in cart. For more details, check the - `help center - doc `__ - - This field is a member of `oneof`_ ``uri_template``. - """ - - checkout_uri_template: str = proto.Field( - proto.STRING, - number=1, - oneof='uri_template', - ) - cart_uri_template: str = proto.Field( - proto.STRING, - number=2, - oneof='uri_template', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py deleted file mode 100644 index a314f422c53b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/customerservice.py +++ /dev/null @@ -1,74 +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.type import phone_number_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'CustomerService', - }, -) - - -class CustomerService(proto.Message): - r"""Customer service information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - Optional. The URI where customer service may - be found. - - This field is a member of `oneof`_ ``_uri``. - email (str): - Optional. The email address where customer - service may be reached. - - This field is a member of `oneof`_ ``_email``. - phone (google.type.phone_number_pb2.PhoneNumber): - Optional. The phone number where customer - service may be called. - - This field is a member of `oneof`_ ``_phone``. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - email: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - phone: phone_number_pb2.PhoneNumber = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=phone_number_pb2.PhoneNumber, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py deleted file mode 100644 index cf0589a015b8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/emailpreferences.py +++ /dev/null @@ -1,121 +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.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - }, -) - - -class EmailPreferences(proto.Message): - r"""The categories of notifications the user opted into / opted - out of. The email preferences do not include mandatory - announcements as users can't opt out of them. - - Attributes: - name (str): - Identifier. The name of the EmailPreferences. - The endpoint is only supported for the - authenticated user. - news_and_tips (google.shopping.merchant_accounts_v1beta.types.EmailPreferences.OptInState): - Optional. Updates on new features, tips and - best practices. - """ - class OptInState(proto.Enum): - r"""Opt in state of the email preference. - - Values: - OPT_IN_STATE_UNSPECIFIED (0): - Opt-in status is not specified. - OPTED_OUT (1): - User has opted out of receiving this type of - email. - OPTED_IN (2): - User has opted in to receiving this type of - email. - UNCONFIRMED (3): - User has opted in to receiving this type of - email and the confirmation email has been sent, - but user has not yet confirmed the opt in - (applies only to certain countries). - """ - OPT_IN_STATE_UNSPECIFIED = 0 - OPTED_OUT = 1 - OPTED_IN = 2 - UNCONFIRMED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - news_and_tips: OptInState = proto.Field( - proto.ENUM, - number=2, - enum=OptInState, - ) - - -class GetEmailPreferencesRequest(proto.Message): - r"""Request message for GetEmailPreferences method. - - Attributes: - name (str): - Required. The name of the ``EmailPreferences`` resource. - Format: - ``accounts/{account}/users/{email}/emailPreferences`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateEmailPreferencesRequest(proto.Message): - r"""Request message for UpdateEmailPreferences method. - - Attributes: - email_preferences (google.shopping.merchant_accounts_v1beta.types.EmailPreferences): - Required. Email Preferences to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - email_preferences: 'EmailPreferences' = proto.Field( - proto.MESSAGE, - number=1, - message='EmailPreferences', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py deleted file mode 100644 index 1f95aae295de..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/gbpaccounts.py +++ /dev/null @@ -1,198 +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.protobuf import empty_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'GbpAccount', - 'ListGbpAccountsRequest', - 'ListGbpAccountsResponse', - 'LinkGbpAccountRequest', - 'LinkGbpAccountResponse', - }, -) - - -class GbpAccount(proto.Message): - r"""Collection of information related to a Google Business - Profile (GBP) account. - - Attributes: - name (str): - Identifier. The resource name of the GBP account. Format: - ``accounts/{account}/gbpAccount/{gbp_account}`` - gbp_account_id (str): - The id of the GBP account. - type_ (google.shopping.merchant_accounts_v1beta.types.GbpAccount.Type): - The type of the Business Profile. - gbp_account_name (str): - The name of the Business Profile. - For personal accounts: Email id of the owner. - For Business accounts: Name of the Business - Account. - listing_count (int): - Number of listings under this account. - """ - class Type(proto.Enum): - r"""The type of the GBP account. - - Values: - TYPE_UNSPECIFIED (0): - Default value. This value is unused. - USER (1): - The GBP account is a user account. - BUSINESS_ACCOUNT (2): - The GBP account is a business account. - """ - TYPE_UNSPECIFIED = 0 - USER = 1 - BUSINESS_ACCOUNT = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - gbp_account_id: str = proto.Field( - proto.STRING, - number=2, - ) - type_: Type = proto.Field( - proto.ENUM, - number=3, - enum=Type, - ) - gbp_account_name: str = proto.Field( - proto.STRING, - number=5, - ) - listing_count: int = proto.Field( - proto.INT64, - number=6, - ) - - -class ListGbpAccountsRequest(proto.Message): - r"""Request message for the ListGbpAccounts method. - - Attributes: - parent (str): - Required. The name of the parent resource under which the - GBP accounts are listed. Format: ``accounts/{account}``. - page_size (int): - Optional. The maximum number of ``GbpAccount`` resources to - return. The service returns fewer than this value if the - number of gbp accounts is less that than the ``pageSize``. - The default value is 50. The maximum value is 1000; If a - value higher than the maximum is specified, then the - ``pageSize`` will default to the maximum. - page_token (str): - Optional. A page token, received from a previous - ``ListGbpAccounts`` call. Provide the page token to retrieve - the subsequent page. - - When paginating, all other parameters provided to - ``ListGbpAccounts`` must match the call that provided the - page token. - """ - - 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 ListGbpAccountsResponse(proto.Message): - r"""Response message for the ListGbpAccounts method. - - Attributes: - gbp_accounts (MutableSequence[google.shopping.merchant_accounts_v1beta.types.GbpAccount]): - The GBP accounts from the specified merchant - in the specified country. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - gbp_accounts: MutableSequence['GbpAccount'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='GbpAccount', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class LinkGbpAccountRequest(proto.Message): - r"""Request message for the LinkGbpAccount method. - - Attributes: - parent (str): - Required. The name of the parent resource to which the GBP - account is linked. Format: ``accounts/{account}``. - gbp_email (str): - Required. The email address of the Business - Profile account. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - gbp_email: str = proto.Field( - proto.STRING, - number=2, - ) - - -class LinkGbpAccountResponse(proto.Message): - r"""Response message for the LinkGbpAccount method. - - Attributes: - response (google.protobuf.empty_pb2.Empty): - Empty response. - """ - - response: empty_pb2.Empty = proto.Field( - proto.MESSAGE, - number=1, - message=empty_pb2.Empty, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py deleted file mode 100644 index 45384433e2f9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/homepage.py +++ /dev/null @@ -1,139 +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.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'Homepage', - 'GetHomepageRequest', - 'UpdateHomepageRequest', - 'ClaimHomepageRequest', - 'UnclaimHomepageRequest', - }, -) - - -class Homepage(proto.Message): - r"""A store's homepage. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the store's homepage. - Format: ``accounts/{account}/homepage`` - uri (str): - Required. The URI (typically a URL) of the - store's homepage. - - This field is a member of `oneof`_ ``_uri``. - claimed (bool): - Output only. Whether the homepage is claimed. - See - https://support.google.com/merchants/answer/176793. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - uri: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - claimed: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class GetHomepageRequest(proto.Message): - r"""Request message for the ``GetHomepage`` method. - - Attributes: - name (str): - Required. The name of the homepage to retrieve. Format: - ``accounts/{account}/homepage`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateHomepageRequest(proto.Message): - r"""Request message for the ``UpdateHomepage`` method. - - Attributes: - homepage (google.shopping.merchant_accounts_v1beta.types.Homepage): - Required. The new version of the homepage. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - homepage: 'Homepage' = proto.Field( - proto.MESSAGE, - number=1, - message='Homepage', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ClaimHomepageRequest(proto.Message): - r"""Request message for the ``ClaimHomepage`` method. - - Attributes: - name (str): - Required. The name of the homepage to claim. Format: - ``accounts/{account}/homepage`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UnclaimHomepageRequest(proto.Message): - r"""Request message for the ``UnclaimHomepage`` method. - - Attributes: - name (str): - Required. The name of the homepage to unclaim. Format: - ``accounts/{account}/homepage`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py deleted file mode 100644 index 564ef8dd933a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/lfpproviders.py +++ /dev/null @@ -1,172 +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.protobuf import empty_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'LfpProvider', - 'FindLfpProvidersRequest', - 'FindLfpProvidersResponse', - 'LinkLfpProviderRequest', - 'LinkLfpProviderResponse', - }, -) - - -class LfpProvider(proto.Message): - r"""Collection of information related to a Local Feed Partnership - (LFP) provider. - - Attributes: - name (str): - Identifier. The resource name of the LFP provider. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}`` - region_code (str): - Output only. Region code defined by - `CLDR `__. - display_name (str): - The display name of the LFP provider. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - - -class FindLfpProvidersRequest(proto.Message): - r"""Request message for the FindLfpProviders method. - - Attributes: - parent (str): - Required. The name of the parent resource under which the - LFP providers are found. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}``. - page_size (int): - Optional. The maximum number of ``LfpProvider`` resources to - return. The service returns fewer than this value if the - number of lfp providers is less that than the ``pageSize``. - The default value is 50. The maximum value is 1000; If a - value higher than the maximum is specified, then the - ``pageSize`` will default to the maximum. - page_token (str): - Optional. A page token, received from a previous - ``FindLfpProviders`` call. Provide the page token to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``FindLfpProviders`` must match the call that provided the - page token. - """ - - 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 FindLfpProvidersResponse(proto.Message): - r"""Response message for the FindLfpProviders method. - - Attributes: - lfp_providers (MutableSequence[google.shopping.merchant_accounts_v1beta.types.LfpProvider]): - The LFP providers from the specified merchant - in the specified country. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - lfp_providers: MutableSequence['LfpProvider'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='LfpProvider', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class LinkLfpProviderRequest(proto.Message): - r"""Request message for the LinkLfpProvider method. - - Attributes: - name (str): - Required. The name of the LFP provider resource to link. - Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}``. - The ``lfp_provider`` is the LFP provider ID. - external_account_id (str): - Required. The external account ID by which - this merchant is known to the LFP provider. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - external_account_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class LinkLfpProviderResponse(proto.Message): - r"""Response message for the LinkLfpProvider method. - - Attributes: - response (google.protobuf.empty_pb2.Empty): - Empty response. - """ - - response: empty_pb2.Empty = proto.Field( - proto.MESSAGE, - number=1, - message=empty_pb2.Empty, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py deleted file mode 100644 index 07e6f2a3c1f5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/omnichannelsettings.py +++ /dev/null @@ -1,548 +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.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'OmnichannelSetting', - 'ReviewState', - 'InStock', - 'Pickup', - 'LfpLink', - 'OnDisplayToOrder', - 'About', - 'InventoryVerification', - 'GetOmnichannelSettingRequest', - 'ListOmnichannelSettingsRequest', - 'ListOmnichannelSettingsResponse', - 'CreateOmnichannelSettingRequest', - 'UpdateOmnichannelSettingRequest', - 'RequestInventoryVerificationRequest', - 'RequestInventoryVerificationResponse', - }, -) - - -class OmnichannelSetting(proto.Message): - r"""Collection of information related to the omnichannel settings - of a merchant. - - Attributes: - name (str): - Identifier. The resource name of the omnichannel setting. - Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - region_code (str): - Required. Immutable. Region code defined by - `CLDR `__. Must be provided in - the Create method, and is immutable. - lsf_type (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting.LsfType): - Required. The Local Store Front type for this - country. - in_stock (google.shopping.merchant_accounts_v1beta.types.InStock): - Optional. The InStock URI and state for this - country. - pickup (google.shopping.merchant_accounts_v1beta.types.Pickup): - Optional. The Pickup URI and state for this - country. - lfp_link (google.shopping.merchant_accounts_v1beta.types.LfpLink): - Output only. The established link to a LFP - provider. - odo (google.shopping.merchant_accounts_v1beta.types.OnDisplayToOrder): - Optional. The On Display to Order (ODO) - policy URI and state for this country. - about (google.shopping.merchant_accounts_v1beta.types.About): - Optional. The about page URI and state for - this country. - inventory_verification (google.shopping.merchant_accounts_v1beta.types.InventoryVerification): - Optional. The inventory verification contact - and state for this country. - """ - class LsfType(proto.Enum): - r"""The product page experience type, which is also called the Local - Store Front (LSF) type. Check the `HC - article `__ for - more details. - - Values: - LSF_TYPE_UNSPECIFIED (0): - Default value. This value is unused. - GHLSF (1): - Google-Hosted Local Store Front. Check the `HC - article `__ - for more details. - MHLSF_BASIC (2): - Merchant-Hosted Local Store Front Basic. Check the `HC - article `__ - for more details. - MHLSF_FULL (3): - Merchant-Hosted Local Store Front Full. Check the `HC - article `__ - for more details. - """ - LSF_TYPE_UNSPECIFIED = 0 - GHLSF = 1 - MHLSF_BASIC = 2 - MHLSF_FULL = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - lsf_type: LsfType = proto.Field( - proto.ENUM, - number=12, - enum=LsfType, - ) - in_stock: 'InStock' = proto.Field( - proto.MESSAGE, - number=13, - message='InStock', - ) - pickup: 'Pickup' = proto.Field( - proto.MESSAGE, - number=14, - message='Pickup', - ) - lfp_link: 'LfpLink' = proto.Field( - proto.MESSAGE, - number=5, - message='LfpLink', - ) - odo: 'OnDisplayToOrder' = proto.Field( - proto.MESSAGE, - number=6, - message='OnDisplayToOrder', - ) - about: 'About' = proto.Field( - proto.MESSAGE, - number=7, - message='About', - ) - inventory_verification: 'InventoryVerification' = proto.Field( - proto.MESSAGE, - number=8, - message='InventoryVerification', - ) - - -class ReviewState(proto.Message): - r"""The state of a omnichannel setting related review process. - """ - class State(proto.Enum): - r"""The state of the review process. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTIVE (1): - The review process has concluded - successfully. The reviewed item is active. - FAILED (2): - The review process failed. - RUNNING (3): - The review process is running. - ACTION_REQUIRED (4): - The review process is waiting for the - merchant to take action. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - FAILED = 2 - RUNNING = 3 - ACTION_REQUIRED = 4 - - -class InStock(proto.Message): - r"""Collection of information related to InStock. - - Attributes: - uri (str): - Optional. Product landing page URI. It is only used for the - review of MHLSF in-stock serving. This URI domain should - match with the business's homepage. Required to be empty if - the lsf_type is GHLSF, and required when the lsf_type is - MHLSF_FULL or MHLSF_BASIC. - state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): - Output only. The state of the in-stock - serving. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - state: 'ReviewState.State' = proto.Field( - proto.ENUM, - number=2, - enum='ReviewState.State', - ) - - -class Pickup(proto.Message): - r"""Collection of information related to Pickup. - - Attributes: - uri (str): - Required. Pickup product page URI. It is only - used for the review of pickup serving. This URI - domain should match with the business's - homepage. - state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): - Output only. The state of the pickup serving. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - state: 'ReviewState.State' = proto.Field( - proto.ENUM, - number=2, - enum='ReviewState.State', - ) - - -class LfpLink(proto.Message): - r"""Collection of information related to the LFP link. - - Attributes: - lfp_provider (str): - Required. The resource name of the LFP provider. Format: - ``lfpProviders/{lfp_provider}`` - external_account_id (str): - Required. The account ID by which this - merchant is known to the LFP provider. - state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): - Output only. The state of the LFP link. - """ - - lfp_provider: str = proto.Field( - proto.STRING, - number=1, - ) - external_account_id: str = proto.Field( - proto.STRING, - number=2, - ) - state: 'ReviewState.State' = proto.Field( - proto.ENUM, - number=3, - enum='ReviewState.State', - ) - - -class OnDisplayToOrder(proto.Message): - r"""Collection of information related to the on display to order - (`ODO `__). - - Attributes: - uri (str): - Required. The on display to order (ODO) - policy URI. - state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): - Output only. The state of the URI. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - state: 'ReviewState.State' = proto.Field( - proto.ENUM, - number=2, - enum='ReviewState.State', - ) - - -class About(proto.Message): - r"""Collection of information related to the about page - (`impressum `__). - - Attributes: - uri (str): - Required. The about page URI. - state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): - Output only. The state of the URI. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - state: 'ReviewState.State' = proto.Field( - proto.ENUM, - number=2, - enum='ReviewState.State', - ) - - -class InventoryVerification(proto.Message): - r"""Collection of information related to `inventory - verification `__. - - Attributes: - state (google.shopping.merchant_accounts_v1beta.types.InventoryVerification.State): - Output only. The state of the inventory - verification process. - contact (str): - Required. The name of the contact for the - inventory verification process. - contact_email (str): - Required. The email address of the contact - for the inventory verification process. - contact_state (google.shopping.merchant_accounts_v1beta.types.ReviewState.State): - Output only. The state of the contact - verification. - """ - class State(proto.Enum): - r"""The state of the `inventory - verification `__ - process. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - ACTION_REQUIRED (1): - When the merchant needs to initiate the - inventory verification process. The next state - is INACTIVE. - INACTIVE (5): - When the merchant is ready to request - inventory verification. - RUNNING (2): - The inventory verification process is - running. If the merchant is rejected, the next - state is INACTIVE. - SUCCEEDED (3): - The inventory verification process succeeded. - SUSPENDED (4): - When merchant fails the inventory - verification process and all attempts are - exhausted. - """ - STATE_UNSPECIFIED = 0 - ACTION_REQUIRED = 1 - INACTIVE = 5 - RUNNING = 2 - SUCCEEDED = 3 - SUSPENDED = 4 - - state: State = proto.Field( - proto.ENUM, - number=1, - enum=State, - ) - contact: str = proto.Field( - proto.STRING, - number=2, - ) - contact_email: str = proto.Field( - proto.STRING, - number=3, - ) - contact_state: 'ReviewState.State' = proto.Field( - proto.ENUM, - number=4, - enum='ReviewState.State', - ) - - -class GetOmnichannelSettingRequest(proto.Message): - r"""Request message for the GetOmnichannelSettings method. - - Attributes: - name (str): - Required. The name of the omnichannel setting to retrieve. - Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListOmnichannelSettingsRequest(proto.Message): - r"""Request message for the ListOmnichannelSettings method. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - omnichannel settings. Format: ``accounts/{account}`` - page_size (int): - Optional. The maximum number of omnichannel - settings to return. The service may return fewer - than this value. If unspecified, at most 50 - omnichannel settings will be returned. The - maximum value is 1000; values above 1000 will be - coerced to 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListOmnichannelSettings`` call. Provide this to retrieve - the subsequent page. - - When paginating, all other parameters provided to - ``ListOmnichannelSettings`` must match the call that - provided the page token. - """ - - 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 ListOmnichannelSettingsResponse(proto.Message): - r"""Response message for the ListOmnichannelSettings method. - - Attributes: - omnichannel_settings (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting]): - The omnichannel settings from the specified - merchant. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - omnichannel_settings: MutableSequence['OmnichannelSetting'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='OmnichannelSetting', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateOmnichannelSettingRequest(proto.Message): - r"""Request message for the CreateOmnichannelSetting method. - - Attributes: - parent (str): - Required. The parent resource where this omnichannel setting - will be created. Format: ``accounts/{account}`` - omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): - Required. The omnichannel setting to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - omnichannel_setting: 'OmnichannelSetting' = proto.Field( - proto.MESSAGE, - number=2, - message='OmnichannelSetting', - ) - - -class UpdateOmnichannelSettingRequest(proto.Message): - r"""Request message for the UpdateOmnichannelSetting method. - - Attributes: - omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): - Required. The omnichannel setting to update. - - The omnichannel setting's ``name`` field is used to identify - the omnichannel setting to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to be updated. - - The following fields are supported in snake_case only: - - - ``lsf_type`` - - ``in_stock`` - - ``pickup`` - - ``odo`` - - ``about`` - - ``inventory_verification`` - - Full replacement with wildcard ``*``\ is supported, while - empty/implied update mask is not. - """ - - omnichannel_setting: 'OmnichannelSetting' = proto.Field( - proto.MESSAGE, - number=1, - message='OmnichannelSetting', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class RequestInventoryVerificationRequest(proto.Message): - r"""Request message for the RequestInventoryVerification method. - - Attributes: - name (str): - Required. The name of the omnichannel setting to request - inventory verification. Format: - ``accounts/{account}/omnichannelSettings/{omnichannel_setting}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RequestInventoryVerificationResponse(proto.Message): - r"""Response message for the RequestInventoryVerification method. - - Attributes: - omnichannel_setting (google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting): - The omnichannel setting that was updated. - """ - - omnichannel_setting: 'OmnichannelSetting' = proto.Field( - proto.MESSAGE, - number=1, - message='OmnichannelSetting', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py deleted file mode 100644 index fa93dab9ca27..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/online_return_policy.py +++ /dev/null @@ -1,581 +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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.type.types import types -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'GetOnlineReturnPolicyRequest', - 'CreateOnlineReturnPolicyRequest', - 'UpdateOnlineReturnPolicyRequest', - 'DeleteOnlineReturnPolicyRequest', - 'ListOnlineReturnPoliciesRequest', - 'ListOnlineReturnPoliciesResponse', - 'OnlineReturnPolicy', - }, -) - - -class GetOnlineReturnPolicyRequest(proto.Message): - r"""Request message for the ``GetOnlineReturnPolicy`` method. - - Attributes: - name (str): - Required. The name of the return policy to retrieve. Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateOnlineReturnPolicyRequest(proto.Message): - r"""Request message for the ``CreateOnlineReturnPolicy`` method. - - Attributes: - parent (str): - Required. The merchant account for which the return policy - will be created. Format: ``accounts/{account}`` - online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): - Required. The return policy object to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - online_return_policy: 'OnlineReturnPolicy' = proto.Field( - proto.MESSAGE, - number=2, - message='OnlineReturnPolicy', - ) - - -class UpdateOnlineReturnPolicyRequest(proto.Message): - r"""Request message for the ``UpdateOnlineReturnPolicy`` method. The - method supports field masks and when the mask is provided, only the - fields specified in the mask are updated. - - Attributes: - online_return_policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy): - Required. The online return policy to update. The online - return policy's ``name`` field is used to identify the - online return policy to be updated. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. List of fields being updated. - - The following fields are supported (in both ``snake_case`` - and ``lowerCamelCase``): - - - ``accept_defective_only`` - - ``accept_exchange`` - - ``item_conditions`` - - ``policy`` - - ``process_refund_days`` - - ``restocking_fee`` - - ``return_methods`` - - ``return_policy_uri`` - - ``return_shipping_fee`` - """ - - online_return_policy: 'OnlineReturnPolicy' = proto.Field( - proto.MESSAGE, - number=1, - message='OnlineReturnPolicy', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteOnlineReturnPolicyRequest(proto.Message): - r"""Request message for the ``DeleteOnlineReturnPolicy`` method. - - Attributes: - name (str): - Required. The name of the return policy to delete. Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListOnlineReturnPoliciesRequest(proto.Message): - r"""Request message for the ``ListOnlineReturnPolicies`` method. - - Attributes: - parent (str): - Required. The merchant account for which to list return - policies. Format: ``accounts/{account}`` - page_size (int): - Optional. The maximum number of ``OnlineReturnPolicy`` - resources to return. The service returns fewer than this - value if the number of return policies for the given - merchant is less that than the ``pageSize``. The default - value is 10. The maximum value is 100; If a value higher - than the maximum is specified, then the ``pageSize`` will - default to the maximum - page_token (str): - Optional. A page token, received from a previous - ``ListOnlineReturnPolicies`` call. Provide the page token to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListOnlineReturnPolicies`` must match the call that - provided the page token. The token returned as - [nextPageToken][google.shopping.merchant.accounts.v1beta.ListOnlineReturnPoliciesResponse.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 ListOnlineReturnPoliciesResponse(proto.Message): - r"""Response message for the ``ListOnlineReturnPolicies`` method. - - Attributes: - online_return_policies (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy]): - The retrieved return policies. - 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 - - online_return_policies: MutableSequence['OnlineReturnPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='OnlineReturnPolicy', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class OnlineReturnPolicy(proto.Message): - r"""`Online return - policy `__ - object. This is currently used to represent return policies for ads - and free listings programs. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The name of the ``OnlineReturnPolicy`` resource. - Format: - ``accounts/{account}/onlineReturnPolicies/{return_policy}`` - return_policy_id (str): - Output only. Return policy ID generated by - Google. - label (str): - Required. Immutable. This field represents the unique - user-defined label of the return policy. It is important to - note that the same label cannot be used in different return - policies for the same country. Unless a product specifies a - specific label attribute, policies will be automatically - labeled as 'default'. To assign a custom return policy to - certain product groups, follow the instructions provided in - the [Return policy label] - (https://support.google.com/merchants/answer/9445425). The - label can contain up to 50 characters. - countries (MutableSequence[str]): - Required. Immutable. The countries of sale - where the return policy applies. The values must - be a valid 2 letter ISO 3166 code. - policy (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.Policy): - Optional. The return policy. - seasonal_overrides (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.SeasonalOverride]): - Optional. Overrides to the general policy for - orders placed during a specific set of time - intervals. - restocking_fee (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.RestockingFee): - Optional. The restocking fee that applies to - all return reason categories. This would be - treated as a free restocking fee if the value is - not set. - return_methods (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnMethod]): - Optional. The return methods of how customers - can return an item. This value is required to - not be empty unless the type of return policy is - noReturns. - item_conditions (MutableSequence[google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ItemCondition]): - Optional. The item conditions accepted for - returns must not be empty unless the type of - return policy is 'noReturns'. - return_shipping_fee (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnShippingFee): - Optional. The return shipping fee. Should be - set only when customer need to download and - print the return label. - return_policy_uri (str): - Required. The return policy uri. This can - used by Google to do a sanity check for the - policy. It must be a valid URL. - accept_defective_only (bool): - Optional. This field specifies if merchant - only accepts defective products for returns. - - This field is a member of `oneof`_ ``_accept_defective_only``. - process_refund_days (int): - Optional. The field specifies the number of - days it takes for merchants to process refunds. - - This field is a member of `oneof`_ ``_process_refund_days``. - accept_exchange (bool): - Optional. This field specifies if merchant - allows customers to exchange products. - - This field is a member of `oneof`_ ``_accept_exchange``. - return_label_source (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnLabelSource): - Optional. The field specifies the return - label source. - - This field is a member of `oneof`_ ``_return_label_source``. - """ - class ReturnMethod(proto.Enum): - r"""The available return methods. - - Values: - RETURN_METHOD_UNSPECIFIED (0): - Default value. This value is unused. - BY_MAIL (1): - Return by mail. - IN_STORE (2): - Return in store. - AT_A_KIOSK (3): - Return at a kiosk. - """ - RETURN_METHOD_UNSPECIFIED = 0 - BY_MAIL = 1 - IN_STORE = 2 - AT_A_KIOSK = 3 - - class ItemCondition(proto.Enum): - r"""The available item conditions. - - Values: - ITEM_CONDITION_UNSPECIFIED (0): - Default value. This value is unused. - NEW (1): - New. - USED (2): - Used. - """ - ITEM_CONDITION_UNSPECIFIED = 0 - NEW = 1 - USED = 2 - - class ReturnLabelSource(proto.Enum): - r"""The available return label sources. - - Values: - RETURN_LABEL_SOURCE_UNSPECIFIED (0): - Default value. This value is unused. - DOWNLOAD_AND_PRINT (1): - Download and print. - IN_THE_PACKAGE (2): - Label include in the package. - CUSTOMER_RESPONSIBILITY (3): - Customer to provide. - """ - RETURN_LABEL_SOURCE_UNSPECIFIED = 0 - DOWNLOAD_AND_PRINT = 1 - IN_THE_PACKAGE = 2 - CUSTOMER_RESPONSIBILITY = 3 - - class ReturnShippingFee(proto.Message): - r"""The return shipping fee. This can either be a fixed fee or a - boolean to indicate that the customer pays the actual shipping - cost. - - Attributes: - type_ (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.ReturnShippingFee.Type): - Required. Type of return shipping fee. - fixed_fee (google.shopping.type.types.Price): - Fixed return shipping fee amount. This value is only - applicable when type is ``FIXED``. We will treat the return - shipping fee as free if type is ``FIXED`` and this value is - not set. - """ - class Type(proto.Enum): - r"""Return shipping fee types. - - Values: - TYPE_UNSPECIFIED (0): - Default value. This value is unused. - FIXED (1): - The return shipping fee is a fixed value. - CUSTOMER_PAYING_ACTUAL_FEE (2): - Customers will pay the actual return shipping - fee. - """ - TYPE_UNSPECIFIED = 0 - FIXED = 1 - CUSTOMER_PAYING_ACTUAL_FEE = 2 - - type_: 'OnlineReturnPolicy.ReturnShippingFee.Type' = proto.Field( - proto.ENUM, - number=1, - enum='OnlineReturnPolicy.ReturnShippingFee.Type', - ) - fixed_fee: types.Price = proto.Field( - proto.MESSAGE, - number=2, - message=types.Price, - ) - - class RestockingFee(proto.Message): - r"""The restocking fee. This can be a flat fee or a micro - percent. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - fixed_fee (google.shopping.type.types.Price): - Fixed restocking fee. - - This field is a member of `oneof`_ ``type``. - micro_percent (int): - Percent of total price in micros. 15,000,000 - means 15% of the total price would be charged. - - This field is a member of `oneof`_ ``type``. - """ - - fixed_fee: types.Price = proto.Field( - proto.MESSAGE, - number=1, - oneof='type', - message=types.Price, - ) - micro_percent: int = proto.Field( - proto.INT32, - number=2, - oneof='type', - ) - - class Policy(proto.Message): - r"""The available policies. - - Attributes: - type_ (google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy.Policy.Type): - Policy type. - days (int): - The number of days items can be returned after delivery, - where one day is defined as 24 hours after the delivery - timestamp. Required for ``NUMBER_OF_DAYS_AFTER_DELIVERY`` - returns. - """ - class Type(proto.Enum): - r"""Return policy types. - - Values: - TYPE_UNSPECIFIED (0): - Default value. This value is unused. - NUMBER_OF_DAYS_AFTER_DELIVERY (1): - The number of days within which a return is - valid after delivery. - NO_RETURNS (2): - No returns. - LIFETIME_RETURNS (3): - Life time returns. - """ - TYPE_UNSPECIFIED = 0 - NUMBER_OF_DAYS_AFTER_DELIVERY = 1 - NO_RETURNS = 2 - LIFETIME_RETURNS = 3 - - type_: 'OnlineReturnPolicy.Policy.Type' = proto.Field( - proto.ENUM, - number=1, - enum='OnlineReturnPolicy.Policy.Type', - ) - days: int = proto.Field( - proto.INT64, - number=2, - ) - - class SeasonalOverride(proto.Message): - r""" - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - return_days (int): - Number of days (from the delivery date) that - the product can be returned. - - This field is a member of `oneof`_ ``return_window``. - return_until_date (google.type.date_pb2.Date): - Fixed end date until which the product can be - returned. - - This field is a member of `oneof`_ ``return_window``. - label (str): - Required. Display name of this seasonal - override in Merchant Center. - start_date (google.type.date_pb2.Date): - Required. Defines the date range when this seasonal override - applies. Both start_date and end_date are inclusive. The - dates of the seasonal overrides should not overlap. - end_date (google.type.date_pb2.Date): - Required. seasonal override end date - (inclusive). - """ - - return_days: int = proto.Field( - proto.INT32, - number=5, - oneof='return_window', - ) - return_until_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=6, - oneof='return_window', - message=date_pb2.Date, - ) - label: str = proto.Field( - proto.STRING, - number=1, - ) - start_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=2, - message=date_pb2.Date, - ) - end_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - message=date_pb2.Date, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - return_policy_id: str = proto.Field( - proto.STRING, - number=2, - ) - label: str = proto.Field( - proto.STRING, - number=3, - ) - countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - policy: Policy = proto.Field( - proto.MESSAGE, - number=5, - message=Policy, - ) - seasonal_overrides: MutableSequence[SeasonalOverride] = proto.RepeatedField( - proto.MESSAGE, - number=14, - message=SeasonalOverride, - ) - restocking_fee: RestockingFee = proto.Field( - proto.MESSAGE, - number=6, - message=RestockingFee, - ) - return_methods: MutableSequence[ReturnMethod] = proto.RepeatedField( - proto.ENUM, - number=7, - enum=ReturnMethod, - ) - item_conditions: MutableSequence[ItemCondition] = proto.RepeatedField( - proto.ENUM, - number=8, - enum=ItemCondition, - ) - return_shipping_fee: ReturnShippingFee = proto.Field( - proto.MESSAGE, - number=9, - message=ReturnShippingFee, - ) - return_policy_uri: str = proto.Field( - proto.STRING, - number=10, - ) - accept_defective_only: bool = proto.Field( - proto.BOOL, - number=11, - optional=True, - ) - process_refund_days: int = proto.Field( - proto.INT32, - number=12, - optional=True, - ) - accept_exchange: bool = proto.Field( - proto.BOOL, - number=13, - optional=True, - ) - return_label_source: ReturnLabelSource = proto.Field( - proto.ENUM, - number=15, - optional=True, - enum=ReturnLabelSource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py deleted file mode 100644 index 3400b5c96854..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/phoneverificationstate.py +++ /dev/null @@ -1,47 +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 - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'PhoneVerificationState', - }, -) - - -class PhoneVerificationState(proto.Enum): - r"""The phone verification state. - - Values: - PHONE_VERIFICATION_STATE_UNSPECIFIED (0): - Default value. This value is unused. - PHONE_VERIFICATION_STATE_VERIFIED (1): - The phone is verified. - PHONE_VERIFICATION_STATE_UNVERIFIED (2): - The phone is unverified - """ - PHONE_VERIFICATION_STATE_UNSPECIFIED = 0 - PHONE_VERIFICATION_STATE_VERIFIED = 1 - PHONE_VERIFICATION_STATE_UNVERIFIED = 2 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py deleted file mode 100644 index aa2de4c33766..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/programs.py +++ /dev/null @@ -1,254 +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 - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'Program', - 'GetProgramRequest', - 'ListProgramsRequest', - 'ListProgramsResponse', - 'EnableProgramRequest', - 'DisableProgramRequest', - }, -) - - -class Program(proto.Message): - r"""Defines participation in a given program for the specified account. - - Programs provide a mechanism for adding functionality to merchant - accounts. A typical example of this is the `Free product - listings `__ - program, which enables products from a merchant's store to be shown - across Google for free. - - Attributes: - name (str): - Identifier. The resource name of the program. Format: - ``accounts/{account}/programs/{program}`` - documentation_uri (str): - Output only. The URL of a Merchant Center - help page describing the program. - state (google.shopping.merchant_accounts_v1beta.types.Program.State): - Output only. The participation state of the - account in the program. - active_region_codes (MutableSequence[str]): - Output only. The regions in which the account is actively - participating in the program. Active regions are defined as - those where all program requirements affecting the regions - have been met. - - Region codes are defined by - `CLDR `__. This is either a - country where the program applies specifically to that - country or ``001`` when the program applies globally. - unmet_requirements (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Program.Requirement]): - Output only. The requirements that the - account has not yet satisfied that are affecting - participation in the program. - """ - class State(proto.Enum): - r"""Possible program participation states for the account. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - NOT_ELIGIBLE (1): - The account is not eligible to participate in - the program. - ELIGIBLE (2): - The account is eligible to participate in the - program. - ENABLED (3): - The program is enabled for the account. - """ - STATE_UNSPECIFIED = 0 - NOT_ELIGIBLE = 1 - ELIGIBLE = 2 - ENABLED = 3 - - class Requirement(proto.Message): - r"""Defines a requirement specified for participation in the - program. - - Attributes: - title (str): - Output only. Name of the requirement. - documentation_uri (str): - Output only. The URL of a help page - describing the requirement. - affected_region_codes (MutableSequence[str]): - Output only. The regions that are currently affected by this - requirement not being met. - - Region codes are defined by - `CLDR `__. This is either a - country where the program applies specifically to that - country or ``001`` when the program applies globally. - """ - - title: str = proto.Field( - proto.STRING, - number=1, - ) - documentation_uri: str = proto.Field( - proto.STRING, - number=2, - ) - affected_region_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - documentation_uri: str = proto.Field( - proto.STRING, - number=2, - ) - state: State = proto.Field( - proto.ENUM, - number=3, - enum=State, - ) - active_region_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - unmet_requirements: MutableSequence[Requirement] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=Requirement, - ) - - -class GetProgramRequest(proto.Message): - r"""Request message for the GetProgram method. - - Attributes: - name (str): - Required. The name of the program to retrieve. Format: - ``accounts/{account}/programs/{program}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListProgramsRequest(proto.Message): - r"""Request message for the ListPrograms method. - - Attributes: - parent (str): - Required. The name of the account for which to retrieve all - programs. Format: ``accounts/{account}`` - page_size (int): - Optional. The maximum number of programs to - return in a single response. If unspecified (or - 0), a default size of 1000 is used. The maximum - value is 1000; values above 1000 will be coerced - to 1000. - page_token (str): - Optional. A continuation token, received from a previous - ``ListPrograms`` call. Provide this to retrieve the next - page. - """ - - 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 ListProgramsResponse(proto.Message): - r"""Response message for the ListPrograms method. - - Attributes: - programs (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Program]): - The programs for the given account. - next_page_token (str): - A token that can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - programs: MutableSequence['Program'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Program', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class EnableProgramRequest(proto.Message): - r"""Request message for the EnableProgram method. - - Attributes: - name (str): - Required. The name of the program for which to enable - participation for the given account. Format: - ``accounts/{account}/programs/{program}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class DisableProgramRequest(proto.Message): - r"""Request message for the DisableProgram method. - - Attributes: - name (str): - Required. The name of the program for which to disable - participation for the given account. Format: - ``accounts/{account}/programs/{program}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py deleted file mode 100644 index 1bbb36f4bb73..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/regions.py +++ /dev/null @@ -1,323 +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.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'GetRegionRequest', - 'CreateRegionRequest', - 'UpdateRegionRequest', - 'DeleteRegionRequest', - 'ListRegionsRequest', - 'ListRegionsResponse', - 'Region', - }, -) - - -class GetRegionRequest(proto.Message): - r"""Request message for the ``GetRegion`` method. - - Attributes: - name (str): - Required. The name of the region to retrieve. Format: - ``accounts/{account}/regions/{region}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateRegionRequest(proto.Message): - r"""Request message for the ``CreateRegion`` method. - - Attributes: - parent (str): - Required. The account to create a region for. Format: - ``accounts/{account}`` - region_id (str): - Required. The identifier for the region, - unique over all regions of the same account. - region (google.shopping.merchant_accounts_v1beta.types.Region): - Required. The region to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - region_id: str = proto.Field( - proto.STRING, - number=2, - ) - region: 'Region' = proto.Field( - proto.MESSAGE, - number=3, - message='Region', - ) - - -class UpdateRegionRequest(proto.Message): - r"""Request message for the ``UpdateRegion`` method. - - Attributes: - region (google.shopping.merchant_accounts_v1beta.types.Region): - Required. The updated region. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The comma-separated field mask indicating the - fields to update. Example: - ``"displayName,postalCodeArea.regionCode"``. - """ - - region: 'Region' = proto.Field( - proto.MESSAGE, - number=1, - message='Region', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteRegionRequest(proto.Message): - r"""Request message for the ``DeleteRegion`` method. - - Attributes: - name (str): - Required. The name of the region to delete. Format: - ``accounts/{account}/regions/{region}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListRegionsRequest(proto.Message): - r"""Request message for the ``ListRegions`` method. - - Attributes: - parent (str): - Required. The account to list regions for. Format: - ``accounts/{account}`` - page_size (int): - Optional. The maximum number of regions to - return. The service may return fewer than this - value. If unspecified, at most 50 regions will - be returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListRegions`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListRegions`` must match the call that provided the page - token. - """ - - 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 ListRegionsResponse(proto.Message): - r"""Response message for the ``ListRegions`` method. - - Attributes: - regions (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Region]): - The regions from the specified merchant. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - regions: MutableSequence['Region'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Region', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class Region(proto.Message): - r"""Represents a geographic region that you can use as a target with - both the ``RegionalInventory`` and ``ShippingSettings`` services. - You can define regions as collections of either postal codes or, in - some countries, using predefined geotargets. For more information, - see `Set up - regions `__ - for more information. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the region. Format: - ``accounts/{account}/regions/{region}`` - display_name (str): - Optional. The display name of the region. - - This field is a member of `oneof`_ ``_display_name``. - postal_code_area (google.shopping.merchant_accounts_v1beta.types.Region.PostalCodeArea): - Optional. A list of postal codes that defines - the region area. - geotarget_area (google.shopping.merchant_accounts_v1beta.types.Region.GeoTargetArea): - Optional. A list of geotargets that defines - the region area. - regional_inventory_eligible (google.protobuf.wrappers_pb2.BoolValue): - Output only. Indicates if the region is - eligible for use in the Regional Inventory - configuration. - shipping_eligible (google.protobuf.wrappers_pb2.BoolValue): - Output only. Indicates if the region is - eligible for use in the Shipping Services - configuration. - """ - - class PostalCodeArea(proto.Message): - r"""A list of postal codes that defines the region area. Note: All - regions defined using postal codes are accessible through the - account's ``ShippingSettings.postalCodeGroups`` resource. - - Attributes: - region_code (str): - Required. `CLDR territory - code `__ - or the country the postal code group applies to. - postal_codes (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Region.PostalCodeArea.PostalCodeRange]): - Required. A range of postal codes. - """ - - class PostalCodeRange(proto.Message): - r"""A range of postal codes that defines the region area. - - Attributes: - begin (str): - Required. A postal code or a pattern of the form prefix\* - denoting the inclusive lower bound of the range defining the - area. Examples values: ``94108``, ``9410*``, ``9*``. - end (str): - Optional. A postal code or a pattern of the form ``prefix*`` - denoting the inclusive upper bound of the range defining the - area. It must have the same length as postalCodeRangeBegin: - if postalCodeRangeBegin is a postal code then - postalCodeRangeEnd must be a postal code too; if - postalCodeRangeBegin is a pattern then postalCodeRangeEnd - must be a pattern with the same prefix length. Optional: if - not set, then the area is defined as being all the postal - codes matching postalCodeRangeBegin. - """ - - begin: str = proto.Field( - proto.STRING, - number=1, - ) - end: str = proto.Field( - proto.STRING, - number=2, - ) - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - postal_codes: MutableSequence['Region.PostalCodeArea.PostalCodeRange'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Region.PostalCodeArea.PostalCodeRange', - ) - - class GeoTargetArea(proto.Message): - r"""A list of geotargets that defines the region area. - - Attributes: - geotarget_criteria_ids (MutableSequence[int]): - Required. A non-empty list of `location - IDs `__. - They must all be of the same location type (for example, - state). - """ - - geotarget_criteria_ids: MutableSequence[int] = proto.RepeatedField( - proto.INT64, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - postal_code_area: PostalCodeArea = proto.Field( - proto.MESSAGE, - number=3, - message=PostalCodeArea, - ) - geotarget_area: GeoTargetArea = proto.Field( - proto.MESSAGE, - number=4, - message=GeoTargetArea, - ) - regional_inventory_eligible: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.BoolValue, - ) - shipping_eligible: wrappers_pb2.BoolValue = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.BoolValue, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py deleted file mode 100644 index 2fc37070a317..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/shippingsettings.py +++ /dev/null @@ -1,1489 +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 - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'ShippingSettings', - 'Service', - 'Distance', - 'Warehouse', - 'WarehouseCutoffTime', - 'Address', - 'DeliveryTime', - 'CutoffTime', - 'BusinessDayConfig', - 'WarehouseBasedDeliveryTime', - 'RateGroup', - 'Table', - 'TransitTable', - 'MinimumOrderValueTable', - 'Headers', - 'LocationIdSet', - 'Row', - 'Value', - 'CarrierRate', - 'GetShippingSettingsRequest', - 'InsertShippingSettingsRequest', - }, -) - - -class ShippingSettings(proto.Message): - r"""The merchant account's `shipping - setting `__. - - Attributes: - name (str): - Identifier. The resource name of the shipping setting. - Format: ``accounts/{account}/shippingSetting`` - services (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Service]): - Optional. The target account's list of - services. - warehouses (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Warehouse]): - Optional. A list of warehouses which can be referred to in - ``services``. - etag (str): - Required. This field is used for avoid async - issue. Make sure shipping setting data - didn't change between get call and insert call. - The user should do following steps: - - 1. Set etag field as empty string for initial - shipping setting creation. - - 2. After initial creation, call get method to - obtain an etag and current shipping setting - data before call insert. - - 3. Modify to wanted shipping setting - information. - - 4. Call insert method with the wanted shipping - setting information with the etag obtained - from step 2. - - 5. If shipping setting data changed between step - 2 and step 4. Insert request will fail - because the etag changes every time the - shipping setting data changes. User should - repeate step 2-4 with the new etag. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - services: MutableSequence['Service'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Service', - ) - warehouses: MutableSequence['Warehouse'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='Warehouse', - ) - etag: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Service(proto.Message): - r"""Shipping service. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - service_name (str): - Required. Free-form name of the service. Must - be unique within target account. - - This field is a member of `oneof`_ ``_service_name``. - active (bool): - Required. A boolean exposing the active - status of the shipping service. - - This field is a member of `oneof`_ ``_active``. - delivery_countries (MutableSequence[str]): - Required. The CLDR territory code of the - countries to which the service applies. - currency_code (str): - The CLDR code of the currency to which this - service applies. Must match that of the prices - in rate groups. - - This field is a member of `oneof`_ ``_currency_code``. - delivery_time (google.shopping.merchant_accounts_v1beta.types.DeliveryTime): - Required. Time spent in various aspects from - order to the delivery of the product. - - This field is a member of `oneof`_ ``_delivery_time``. - rate_groups (MutableSequence[google.shopping.merchant_accounts_v1beta.types.RateGroup]): - Optional. Shipping rate group definitions. Only the last one - is allowed to have an empty ``applicable_shipping_labels``, - which means "everything else". The other - ``applicable_shipping_labels`` must not overlap. - shipment_type (google.shopping.merchant_accounts_v1beta.types.Service.ShipmentType): - Type of locations this service ships orders - to. - - This field is a member of `oneof`_ ``_shipment_type``. - minimum_order_value (google.shopping.type.types.Price): - Minimum order value for this service. If set, indicates that - customers will have to spend at least this amount. All - prices within a service must have the same currency. Cannot - be set together with minimum_order_value_table. - - This field is a member of `oneof`_ ``_minimum_order_value``. - minimum_order_value_table (google.shopping.merchant_accounts_v1beta.types.MinimumOrderValueTable): - Table of per store minimum order values for the pickup - fulfillment type. Cannot be set together with - minimum_order_value. - - This field is a member of `oneof`_ ``_minimum_order_value_table``. - store_config (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig): - A list of stores your products are delivered - from. This is only valid for the local delivery - shipment type. - - This field is a member of `oneof`_ ``_store_config``. - loyalty_programs (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Service.LoyaltyProgram]): - Optional. Loyalty programs that this shipping - service is limited to. - """ - class ShipmentType(proto.Enum): - r"""Shipment type of shipping service. - - Values: - SHIPMENT_TYPE_UNSPECIFIED (0): - This service did not specify shipment type. - DELIVERY (1): - This service ships orders to an address - chosen by the customer. - LOCAL_DELIVERY (2): - This service ships orders to an address - chosen by the customer. The order is shipped - from a local store near by. - COLLECTION_POINT (3): - This service ships orders to an address - chosen by the customer. The order is shipped - from a collection point. - """ - SHIPMENT_TYPE_UNSPECIFIED = 0 - DELIVERY = 1 - LOCAL_DELIVERY = 2 - COLLECTION_POINT = 3 - - class StoreConfig(proto.Message): - r"""A list of stores your products are delivered from. - This is only valid for the local delivery shipment type. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - store_service_type (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig.StoreServiceType): - Indicates whether all stores, or selected - stores, listed by this merchant provide local - delivery. - - This field is a member of `oneof`_ ``_store_service_type``. - store_codes (MutableSequence[str]): - Optional. A list of store codes that provide local delivery. - If empty, then ``all_stores`` must be true. - cutoff_config (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig.CutoffConfig): - Configs related to local delivery ends for - the day. - - This field is a member of `oneof`_ ``_cutoff_config``. - service_radius (google.shopping.merchant_accounts_v1beta.types.Distance): - Maximum delivery radius. - This is only required for the local delivery - shipment type. - - This field is a member of `oneof`_ ``_service_radius``. - """ - class StoreServiceType(proto.Enum): - r"""Indicates whether all stores, or selected stores, listed by - the merchant provide local delivery. - - Values: - STORE_SERVICE_TYPE_UNSPECIFIED (0): - Did not specify store service type. - ALL_STORES (1): - Indicates whether all stores, current and - future, listed by this merchant provide local - delivery. - SELECTED_STORES (2): - Indicates that only the stores listed in ``store_codes`` are - eligible for local delivery. - """ - STORE_SERVICE_TYPE_UNSPECIFIED = 0 - ALL_STORES = 1 - SELECTED_STORES = 2 - - class CutoffConfig(proto.Message): - r"""Configs related to local delivery ends for the day. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - local_cutoff_time (google.shopping.merchant_accounts_v1beta.types.Service.StoreConfig.CutoffConfig.LocalCutoffTime): - Time that local delivery ends for the day. - - This field is a member of `oneof`_ ``_local_cutoff_time``. - store_close_offset_hours (int): - Only valid with local delivery fulfillment. Represents - cutoff time as the number of hours before store closing. - Mutually exclusive with ``local_cutoff_time``. - - This field is a member of `oneof`_ ``_store_close_offset_hours``. - no_delivery_post_cutoff (bool): - Merchants can opt-out of showing n+1 day local delivery when - they have a shipping service configured to n day local - delivery. For example, if the shipping service defines - same-day delivery, and it's past the cut-off, setting this - field to ``true`` results in the calculated shipping service - rate returning ``NO_DELIVERY_POST_CUTOFF``. In the same - example, setting this field to ``false`` results in the - calculated shipping time being one day. This is only for - local delivery. - - This field is a member of `oneof`_ ``_no_delivery_post_cutoff``. - """ - - class LocalCutoffTime(proto.Message): - r"""Time that local delivery ends for the day. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - hour (int): - Hour local delivery orders must be placed by - to process the same day. - - This field is a member of `oneof`_ ``_hour``. - minute (int): - Minute local delivery orders must be placed - by to process the same day. - - This field is a member of `oneof`_ ``_minute``. - """ - - hour: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - minute: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - - local_cutoff_time: 'Service.StoreConfig.CutoffConfig.LocalCutoffTime' = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message='Service.StoreConfig.CutoffConfig.LocalCutoffTime', - ) - store_close_offset_hours: int = proto.Field( - proto.INT64, - number=2, - optional=True, - ) - no_delivery_post_cutoff: bool = proto.Field( - proto.BOOL, - number=3, - optional=True, - ) - - store_service_type: 'Service.StoreConfig.StoreServiceType' = proto.Field( - proto.ENUM, - number=1, - optional=True, - enum='Service.StoreConfig.StoreServiceType', - ) - store_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - cutoff_config: 'Service.StoreConfig.CutoffConfig' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='Service.StoreConfig.CutoffConfig', - ) - service_radius: 'Distance' = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message='Distance', - ) - - class LoyaltyProgram(proto.Message): - r"""`Loyalty - program `__ - provided by a merchant. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - program_label (str): - This is the loyalty program label set in your - loyalty program settings in Merchant Center. - This sub-attribute allows Google to map your - loyalty program to eligible offers. - - This field is a member of `oneof`_ ``_program_label``. - loyalty_program_tiers (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Service.LoyaltyProgram.LoyaltyProgramTiers]): - Optional. Loyalty program tier of this - shipping service. - """ - - class LoyaltyProgramTiers(proto.Message): - r"""Subset of a merchants loyalty program. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - tier_label (str): - The tier label [tier_label] sub-attribute differentiates - offer level benefits between each tier. This value is also - set in your program settings in Merchant Center, and is - required for data source changes even if your loyalty - program only has 1 tier. - - This field is a member of `oneof`_ ``_tier_label``. - """ - - tier_label: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - - program_label: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - loyalty_program_tiers: MutableSequence['Service.LoyaltyProgram.LoyaltyProgramTiers'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Service.LoyaltyProgram.LoyaltyProgramTiers', - ) - - service_name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - active: bool = proto.Field( - proto.BOOL, - number=2, - optional=True, - ) - delivery_countries: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - currency_code: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - delivery_time: 'DeliveryTime' = proto.Field( - proto.MESSAGE, - number=5, - optional=True, - message='DeliveryTime', - ) - rate_groups: MutableSequence['RateGroup'] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message='RateGroup', - ) - shipment_type: ShipmentType = proto.Field( - proto.ENUM, - number=7, - optional=True, - enum=ShipmentType, - ) - minimum_order_value: types.Price = proto.Field( - proto.MESSAGE, - number=8, - optional=True, - message=types.Price, - ) - minimum_order_value_table: 'MinimumOrderValueTable' = proto.Field( - proto.MESSAGE, - number=9, - optional=True, - message='MinimumOrderValueTable', - ) - store_config: StoreConfig = proto.Field( - proto.MESSAGE, - number=10, - optional=True, - message=StoreConfig, - ) - loyalty_programs: MutableSequence[LoyaltyProgram] = proto.RepeatedField( - proto.MESSAGE, - number=11, - message=LoyaltyProgram, - ) - - -class Distance(proto.Message): - r"""Maximum delivery radius. - This is only required for the local delivery shipment type. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (int): - Integer value of distance. - - This field is a member of `oneof`_ ``_value``. - unit (google.shopping.merchant_accounts_v1beta.types.Distance.Unit): - Unit can differ based on country, it is - parameterized to include miles and kilometers. - - This field is a member of `oneof`_ ``_unit``. - """ - class Unit(proto.Enum): - r"""Unit can differ based on country, it is parameterized to - include miles and kilometers. - - Values: - UNIT_UNSPECIFIED (0): - Unit unspecified - MILES (1): - Unit in miles - KILOMETERS (2): - Unit in kilometers - """ - UNIT_UNSPECIFIED = 0 - MILES = 1 - KILOMETERS = 2 - - value: int = proto.Field( - proto.INT64, - number=1, - optional=True, - ) - unit: Unit = proto.Field( - proto.ENUM, - number=2, - optional=True, - enum=Unit, - ) - - -class Warehouse(proto.Message): - r"""A fulfillment warehouse, which stores and handles inventory. - Next tag: 7 - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. The name of the warehouse. Must be - unique within account. - - This field is a member of `oneof`_ ``_name``. - shipping_address (google.shopping.merchant_accounts_v1beta.types.Address): - Required. Shipping address of the warehouse. - - This field is a member of `oneof`_ ``_shipping_address``. - cutoff_time (google.shopping.merchant_accounts_v1beta.types.WarehouseCutoffTime): - Required. The latest time of day that an - order can be accepted and begin processing. - Later orders will be processed in the next day. - The time is based on the warehouse postal code. - - This field is a member of `oneof`_ ``_cutoff_time``. - handling_days (int): - Required. The number of days it takes for - this warehouse to pack up and ship an item. This - is on the warehouse level, but can be overridden - on the offer level based on the attributes of an - item. - - This field is a member of `oneof`_ ``_handling_days``. - business_day_config (google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig): - Business days of the warehouse. - If not set, will be Monday to Friday by default. - - This field is a member of `oneof`_ ``_business_day_config``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - shipping_address: 'Address' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='Address', - ) - cutoff_time: 'WarehouseCutoffTime' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='WarehouseCutoffTime', - ) - handling_days: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - business_day_config: 'BusinessDayConfig' = proto.Field( - proto.MESSAGE, - number=5, - optional=True, - message='BusinessDayConfig', - ) - - -class WarehouseCutoffTime(proto.Message): - r"""The latest time of day that an order can be accepted and - begin processing. Later orders will be processed in the next - day. The time is based on the warehouse postal code. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - hour (int): - Required. Hour of the cutoff time until which - an order has to be placed to be processed in the - same day by the warehouse. Hour is based on the - timezone of warehouse. - - This field is a member of `oneof`_ ``_hour``. - minute (int): - Required. Minute of the cutoff time until - which an order has to be placed to be processed - in the same day by the warehouse. Minute is - based on the timezone of warehouse. - - This field is a member of `oneof`_ ``_minute``. - """ - - hour: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - minute: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - -class Address(proto.Message): - r"""Shipping address of the warehouse. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - street_address (str): - Street-level part of the address. For example: - ``111w 31st Street``. - - This field is a member of `oneof`_ ``_street_address``. - city (str): - Required. City, town or commune. May also - include dependent localities or sublocalities - (For example neighborhoods or suburbs). - - This field is a member of `oneof`_ ``_city``. - administrative_area (str): - Required. Top-level administrative - subdivision of the country. For example, a state - like California ("CA") or a province like Quebec - ("QC"). - - This field is a member of `oneof`_ ``_administrative_area``. - postal_code (str): - Required. Postal code or ZIP (For example - "94043"). - - This field is a member of `oneof`_ ``_postal_code``. - region_code (str): - Required. `CLDR country - code `__ - (For example "US"). - - This field is a member of `oneof`_ ``_region_code``. - """ - - street_address: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - city: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - administrative_area: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - postal_code: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - region_code: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - - -class DeliveryTime(proto.Message): - r"""Time spent in various aspects from order to the delivery of - the product. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - min_transit_days (int): - Minimum number of business days that is spent in transit. 0 - means same day delivery, 1 means next day delivery. Either - ``min_transit_days``, ``max_transit_days`` or - ``transit_time_table`` must be set, but not both. - - This field is a member of `oneof`_ ``_min_transit_days``. - max_transit_days (int): - Maximum number of business days that is spent in transit. 0 - means same day delivery, 1 means next day delivery. Must be - greater than or equal to ``min_transit_days``. - - This field is a member of `oneof`_ ``_max_transit_days``. - cutoff_time (google.shopping.merchant_accounts_v1beta.types.CutoffTime): - Business days cutoff time definition. - If not configured the cutoff time will be - defaulted to 8AM PST. - - This field is a member of `oneof`_ ``_cutoff_time``. - min_handling_days (int): - Minimum number of business days spent before an order is - shipped. 0 means same day shipped, 1 means next day shipped. - 'min_handling_days' and 'max_handling_days' should be either - set or not set at the same time. - - This field is a member of `oneof`_ ``_min_handling_days``. - max_handling_days (int): - Maximum number of business days spent before an order is - shipped. 0 means same day shipped, 1 means next day shipped. - Must be greater than or equal to ``min_handling_days``. - 'min_handling_days' and 'max_handling_days' should be either - set or not set at the same time. - - This field is a member of `oneof`_ ``_max_handling_days``. - transit_time_table (google.shopping.merchant_accounts_v1beta.types.TransitTable): - Transit time table, number of business days spent in transit - based on row and column dimensions. Either - ``min_transit_days``, ``max_transit_days`` or - ``transit_time_table`` can be set, but not both. - - This field is a member of `oneof`_ ``_transit_time_table``. - handling_business_day_config (google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig): - The business days during which orders can be - handled. If not provided, Monday to Friday - business days will be assumed. - - This field is a member of `oneof`_ ``_handling_business_day_config``. - transit_business_day_config (google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig): - The business days during which orders can be - in-transit. If not provided, Monday to Friday - business days will be assumed. - - This field is a member of `oneof`_ ``_transit_business_day_config``. - warehouse_based_delivery_times (MutableSequence[google.shopping.merchant_accounts_v1beta.types.WarehouseBasedDeliveryTime]): - Optional. Indicates that the delivery time should be - calculated per warehouse (shipping origin location) based on - the settings of the selected carrier. When set, no other - transit time related field in [delivery - time][[google.shopping.content.bundles.ShippingSetting.DeliveryTime] - should be set. - """ - - min_transit_days: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - max_transit_days: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - cutoff_time: 'CutoffTime' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='CutoffTime', - ) - min_handling_days: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - max_handling_days: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - transit_time_table: 'TransitTable' = proto.Field( - proto.MESSAGE, - number=6, - optional=True, - message='TransitTable', - ) - handling_business_day_config: 'BusinessDayConfig' = proto.Field( - proto.MESSAGE, - number=7, - optional=True, - message='BusinessDayConfig', - ) - transit_business_day_config: 'BusinessDayConfig' = proto.Field( - proto.MESSAGE, - number=8, - optional=True, - message='BusinessDayConfig', - ) - warehouse_based_delivery_times: MutableSequence['WarehouseBasedDeliveryTime'] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message='WarehouseBasedDeliveryTime', - ) - - -class CutoffTime(proto.Message): - r"""Business days cutoff time definition. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - hour (int): - Required. Hour of the cutoff time until which - an order has to be placed to be processed in the - same day. - - This field is a member of `oneof`_ ``_hour``. - minute (int): - Required. Minute of the cutoff time until - which an order has to be placed to be processed - in the same day. - - This field is a member of `oneof`_ ``_minute``. - time_zone (str): - Required. `Timezone - identifier `__ - For example "Europe/Zurich". - - This field is a member of `oneof`_ ``_time_zone``. - """ - - hour: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - minute: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - time_zone: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - - -class BusinessDayConfig(proto.Message): - r"""Business days of the warehouse. - - Attributes: - business_days (MutableSequence[google.shopping.merchant_accounts_v1beta.types.BusinessDayConfig.Weekday]): - Required. Regular business days. - May not be empty. - """ - class Weekday(proto.Enum): - r""" - - Values: - WEEKDAY_UNSPECIFIED (0): - No description available. - MONDAY (1): - No description available. - TUESDAY (2): - No description available. - WEDNESDAY (3): - No description available. - THURSDAY (4): - No description available. - FRIDAY (5): - No description available. - SATURDAY (6): - No description available. - SUNDAY (7): - No description available. - """ - WEEKDAY_UNSPECIFIED = 0 - MONDAY = 1 - TUESDAY = 2 - WEDNESDAY = 3 - THURSDAY = 4 - FRIDAY = 5 - SATURDAY = 6 - SUNDAY = 7 - - business_days: MutableSequence[Weekday] = proto.RepeatedField( - proto.ENUM, - number=1, - enum=Weekday, - ) - - -class WarehouseBasedDeliveryTime(proto.Message): - r"""Indicates that the delivery time should be calculated per warehouse - (shipping origin location) based on the settings of the selected - carrier. When set, no other transit time related field in - ``delivery_time`` should be set. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - carrier (str): - Required. Carrier, such as ``"UPS"`` or ``"Fedex"``. - - This field is a member of `oneof`_ ``_carrier``. - carrier_service (str): - Required. Carrier service, such as ``"ground"`` or - ``"2 days"``. The name of the service must be in the - eddSupportedServices list. - - This field is a member of `oneof`_ ``_carrier_service``. - warehouse (str): - Required. Warehouse name. This should match - [warehouse][ShippingSetting.warehouses.name] - - This field is a member of `oneof`_ ``_warehouse``. - """ - - carrier: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - carrier_service: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - warehouse: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - - -class RateGroup(proto.Message): - r"""Shipping rate group definitions. Only the last one is allowed to - have an empty ``applicable_shipping_labels``, which means - "everything else". The other ``applicable_shipping_labels`` must not - overlap. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - applicable_shipping_labels (MutableSequence[str]): - Required. A list of `shipping - labels `__ - defining the products to which this rate group applies to. - This is a disjunction: only one of the labels has to match - for the rate group to apply. May only be empty for the last - rate group of a service. - single_value (google.shopping.merchant_accounts_v1beta.types.Value): - The value of the rate group (For example flat rate $10). Can - only be set if ``main_table`` and ``subtables`` are not set. - - This field is a member of `oneof`_ ``_single_value``. - main_table (google.shopping.merchant_accounts_v1beta.types.Table): - A table defining the rate group, when ``single_value`` is - not expressive enough. Can only be set if ``single_value`` - is not set. - - This field is a member of `oneof`_ ``_main_table``. - subtables (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Table]): - Optional. A list of subtables referred to by ``main_table``. - Can only be set if ``main_table`` is set. - carrier_rates (MutableSequence[google.shopping.merchant_accounts_v1beta.types.CarrierRate]): - Optional. A list of carrier rates that can be referred to by - ``main_table`` or ``single_value``. - name (str): - Optional. Name of the rate group. - If set has to be unique within shipping service. - - This field is a member of `oneof`_ ``_name``. - """ - - applicable_shipping_labels: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - single_value: 'Value' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='Value', - ) - main_table: 'Table' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='Table', - ) - subtables: MutableSequence['Table'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Table', - ) - carrier_rates: MutableSequence['CarrierRate'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='CarrierRate', - ) - name: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - - -class Table(proto.Message): - r"""A table defining the rate group, when ``single_value`` is not - expressive enough. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Name of the table. Required for subtables, - ignored for the main table. - - This field is a member of `oneof`_ ``_name``. - row_headers (google.shopping.merchant_accounts_v1beta.types.Headers): - Required. Headers of the table's rows. - - This field is a member of `oneof`_ ``_row_headers``. - column_headers (google.shopping.merchant_accounts_v1beta.types.Headers): - Headers of the table's columns. Optional: if - not set then the table has only one dimension. - - This field is a member of `oneof`_ ``_column_headers``. - rows (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Row]): - Required. The list of rows that constitute the table. Must - have the same length as ``row_headers``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - row_headers: 'Headers' = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message='Headers', - ) - column_headers: 'Headers' = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message='Headers', - ) - rows: MutableSequence['Row'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Row', - ) - - -class TransitTable(proto.Message): - r"""Transit time table, number of business days spent in transit based - on row and column dimensions. Either ``min_transit_days``, - ``max_transit_days`` or ``transit_time_table`` can be set, but not - both. - - Attributes: - postal_code_group_names (MutableSequence[str]): - Required. A list of region names - [Region.name][google.shopping.merchant.accounts.v1beta.Region.name] - . The last value can be ``"all other locations"``. Example: - ``["zone 1", "zone 2", "all other locations"]``. The - referred postal code groups must match the delivery country - of the service. - transit_time_labels (MutableSequence[str]): - Required. A list of transit time labels. The last value can - be ``"all other labels"``. Example: - ``["food", "electronics", "all other labels"]``. - rows (MutableSequence[google.shopping.merchant_accounts_v1beta.types.TransitTable.TransitTimeRow]): - Required. If there's only one dimension set of - ``postal_code_group_names`` or ``transit_time_labels``, - there are multiple rows each with one value for that - dimension. If there are two dimensions, each row corresponds - to a ``postal_code_group_names``, and columns (values) to a - ``transit_time_labels``. - """ - - class TransitTimeRow(proto.Message): - r"""If there's only one dimension set of ``postal_code_group_names`` or - ``transit_time_labels``, there are multiple rows each with one value - for that dimension. If there are two dimensions, each row - corresponds to a ``postal_code_group_names``, and columns (values) - to a ``transit_time_labels``. - - Attributes: - values (MutableSequence[google.shopping.merchant_accounts_v1beta.types.TransitTable.TransitTimeRow.TransitTimeValue]): - Required. Transit time range (min-max) in - business days. - """ - - class TransitTimeValue(proto.Message): - r"""Transit time range (min-max) in business days. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - min_transit_days (int): - Minimum transit time range in business days. - 0 means same day delivery, 1 means next day - delivery. - - This field is a member of `oneof`_ ``_min_transit_days``. - max_transit_days (int): - Must be greater than or equal to ``min_transit_days``. - - This field is a member of `oneof`_ ``_max_transit_days``. - """ - - min_transit_days: int = proto.Field( - proto.INT32, - number=1, - optional=True, - ) - max_transit_days: int = proto.Field( - proto.INT32, - number=2, - optional=True, - ) - - values: MutableSequence['TransitTable.TransitTimeRow.TransitTimeValue'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TransitTable.TransitTimeRow.TransitTimeValue', - ) - - postal_code_group_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - transit_time_labels: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - rows: MutableSequence[TransitTimeRow] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=TransitTimeRow, - ) - - -class MinimumOrderValueTable(proto.Message): - r"""Table of per store minimum order values for the pickup - fulfillment type. - - Attributes: - store_code_set_with_movs (MutableSequence[google.shopping.merchant_accounts_v1beta.types.MinimumOrderValueTable.StoreCodeSetWithMov]): - Required. A list of store code sets sharing - the same minimum order value (MOV). At least two - sets are required and the last one must be - empty, which signifies 'MOV for all other - stores'. Each store code can only appear once - across all the sets. All prices within a service - must have the same currency. - """ - - class StoreCodeSetWithMov(proto.Message): - r"""A list of store code sets sharing the same minimum order - value. At least two sets are required and the last one must be - empty, which signifies 'MOV for all other stores'. - Each store code can only appear once across all the sets. All - prices within a service must have the same currency. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - store_codes (MutableSequence[str]): - Optional. A list of unique store codes or - empty for the catch all. - value (google.shopping.type.types.Price): - The minimum order value for the given stores. - - This field is a member of `oneof`_ ``_value``. - """ - - store_codes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - value: types.Price = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=types.Price, - ) - - store_code_set_with_movs: MutableSequence[StoreCodeSetWithMov] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=StoreCodeSetWithMov, - ) - - -class Headers(proto.Message): - r"""A non-empty list of row or column headers for a table. Exactly one - of ``prices``, ``weights``, ``num_items``, - ``postal_code_group_names``, or ``location`` must be set. - - Attributes: - prices (MutableSequence[google.shopping.type.types.Price]): - Required. A list of inclusive order price upper bounds. The - last price's value can be infinity by setting price - amount_micros = -1. For example - ``[{"amount_micros": 10000000, "currency_code": "USD"}, {"amount_micros": 500000000, "currency_code": "USD"}, {"amount_micros": -1, "currency_code": "USD"}]`` - represents the headers "<= $10", "<= $500", and "> $500". - All prices within a service must have the same currency. - Must be non-empty. Must be positive except -1. Can only be - set if all other fields are not set. - weights (MutableSequence[google.shopping.type.types.Weight]): - Required. A list of inclusive order weight upper bounds. The - last weight's value can be infinity by setting price - amount_micros = -1. For example - ``[{"amount_micros": 10000000, "unit": "kg"}, {"amount_micros": 50000000, "unit": "kg"}, {"amount_micros": -1, "unit": "kg"}]`` - represents the headers "<= 10kg", "<= 50kg", and "> 50kg". - All weights within a service must have the same unit. Must - be non-empty. Must be positive except -1. Can only be set if - all other fields are not set. - number_of_items (MutableSequence[str]): - Required. A list of inclusive number of items upper bounds. - The last value can be ``"infinity"``. For example - ``["10", "50", "infinity"]`` represents the headers "<= 10 - items", "<= 50 items", and "> 50 items". Must be non-empty. - Can only be set if all other fields are not set. - postal_code_group_names (MutableSequence[str]): - Required. A list of postal group names. The last value can - be ``"all other locations"``. Example: - ``["zone 1", "zone 2", "all other locations"]``. The - referred postal code groups must match the delivery country - of the service. Must be non-empty. Can only be set if all - other fields are not set. - locations (MutableSequence[google.shopping.merchant_accounts_v1beta.types.LocationIdSet]): - Required. A list of location ID sets. Must be - non-empty. Can only be set if all other fields - are not set. - """ - - prices: MutableSequence[types.Price] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=types.Price, - ) - weights: MutableSequence[types.Weight] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=types.Weight, - ) - number_of_items: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - postal_code_group_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - locations: MutableSequence['LocationIdSet'] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message='LocationIdSet', - ) - - -class LocationIdSet(proto.Message): - r"""A list of location ID sets. Must be non-empty. Can only be - set if all other fields are not set. - - Attributes: - location_ids (MutableSequence[str]): - Required. A non-empty list of `location - IDs `__. - They must all be of the same location type (For example, - state). - """ - - location_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class Row(proto.Message): - r"""Include a list of cells. - - Attributes: - cells (MutableSequence[google.shopping.merchant_accounts_v1beta.types.Value]): - Required. The list of cells that constitute the row. Must - have the same length as ``columnHeaders`` for - two-dimensional tables, a length of 1 for one-dimensional - tables. - """ - - cells: MutableSequence['Value'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Value', - ) - - -class Value(proto.Message): - r"""The single value of a rate group or the value of a rate group - table's cell. Exactly one of ``no_shipping``, ``flat_rate``, - ``price_percentage``, ``carrier_rateName``, ``subtable_name`` must - be set. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - no_shipping (bool): - If true, then the product can't be shipped. - Must be true when set, can only be set if all - other fields are not set. - - This field is a member of `oneof`_ ``_no_shipping``. - flat_rate (google.shopping.type.types.Price): - A flat rate. Can only be set if all other - fields are not set. - - This field is a member of `oneof`_ ``_flat_rate``. - price_percentage (str): - A percentage of the price represented as a number in decimal - notation (For example, ``"5.4"``). Can only be set if all - other fields are not set. - - This field is a member of `oneof`_ ``_price_percentage``. - carrier_rate (str): - The name of a carrier rate referring to a - carrier rate defined in the same rate group. Can - only be set if all other fields are not set. - - This field is a member of `oneof`_ ``_carrier_rate``. - subtable (str): - The name of a subtable. Can only be set in - table cells (For example, not for single - values), and only if all other fields are not - set. - - This field is a member of `oneof`_ ``_subtable``. - """ - - no_shipping: bool = proto.Field( - proto.BOOL, - number=1, - optional=True, - ) - flat_rate: types.Price = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=types.Price, - ) - price_percentage: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - carrier_rate: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - subtable: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - - -class CarrierRate(proto.Message): - r"""A list of carrier rates that can be referred to by ``main_table`` or - ``single_value``. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Required. Name of the carrier rate. Must be - unique per rate group. - - This field is a member of `oneof`_ ``_name``. - carrier (str): - Required. Carrier service, such as ``"UPS"`` or ``"Fedex"``. - - This field is a member of `oneof`_ ``_carrier``. - carrier_service (str): - Required. Carrier service, such as ``"ground"`` or - ``"2 days"``. - - This field is a member of `oneof`_ ``_carrier_service``. - origin_postal_code (str): - Required. Shipping origin for this carrier - rate. - - This field is a member of `oneof`_ ``_origin_postal_code``. - percentage_adjustment (str): - Optional. Multiplicative shipping rate modifier as a number - in decimal notation. Can be negative. For example ``"5.4"`` - increases the rate by 5.4%, ``"-3"`` decreases the rate by - 3%. - - This field is a member of `oneof`_ ``_percentage_adjustment``. - flat_adjustment (google.shopping.type.types.Price): - Optional. Additive shipping rate modifier. Can be negative. - For example - ``{ "amount_micros": 1, "currency_code" : "USD" }`` adds $1 - to the rate, - ``{ "amount_micros": -3, "currency_code" : "USD" }`` removes - $3 from the rate. - - This field is a member of `oneof`_ ``_flat_adjustment``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - carrier: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - carrier_service: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - origin_postal_code: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - percentage_adjustment: str = proto.Field( - proto.STRING, - number=5, - optional=True, - ) - flat_adjustment: types.Price = proto.Field( - proto.MESSAGE, - number=6, - optional=True, - message=types.Price, - ) - - -class GetShippingSettingsRequest(proto.Message): - r"""Request message for the ``GetShippingSetting`` method. - - Attributes: - name (str): - Required. The name of the shipping setting to retrieve. - Format: ``accounts/{account}/shippingsetting`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class InsertShippingSettingsRequest(proto.Message): - r"""Request message for the ``InsertShippingSetting`` method. - - Attributes: - parent (str): - Required. The account where this product will - be inserted. Format: accounts/{account} - shipping_setting (google.shopping.merchant_accounts_v1beta.types.ShippingSettings): - Required. The new version of the account. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - shipping_setting: 'ShippingSettings' = proto.Field( - proto.MESSAGE, - number=2, - message='ShippingSettings', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py deleted file mode 100644 index e6c4397d8032..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/tax_rule.py +++ /dev/null @@ -1,149 +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.type import interval_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'TaxRule', - }, -) - - -class TaxRule(proto.Message): - r"""Primary type convension - - percent micro : 100% = 1 000 000 and 1% = 10 000 - cannot be negative. - - Information about tax nexus and related parameters applicable to - orders delivered to the area covered by a single tax admin. - Nexus is created when a merchant is doing business in an area - administered by tax admin (only US states are supported for - nexus configuration). If merchant has nexus in a US state, - merchant needs to pay tax to all tax authorities associated with - the shipping destination. - Next Id : 8 - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - location_id (int): - The admin_id or criteria_id of the region in which this rule - is applicable. - - This field is a member of `oneof`_ ``location``. - post_code_range (google.shopping.merchant_accounts_v1beta.types.TaxRule.TaxPostalCodeRange): - The range of postal codes in which this rule - is applicable. - - This field is a member of `oneof`_ ``location``. - use_google_rate (bool): - Rate that depends on delivery location: if - merchant has a nexus in corresponding US state, - rates from authorities with jurisdiction over - delivery area are added up. - - This field is a member of `oneof`_ ``rate_calculation``. - self_specified_rate_micros (int): - A fixed rate specified in micros, where 100% = 1_000_000. - Suitable for origin-based states. - - This field is a member of `oneof`_ ``rate_calculation``. - region_code (str): - Region code in which this rule is applicable - shipping_taxed (bool): - If set, shipping charge is taxed (at the same - rate as product) when delivering to this admin's - area. Can only be set on US states without - category. - effective_time_period (google.type.interval_pb2.Interval): - Required. Time period when this rule is effective. If the - duration is missing from effective_time listed, then it is - open ended to the future. The start of this time period is - inclusive, and the end is exclusive. - """ - - class TaxPostalCodeRange(proto.Message): - r"""A range of postal codes that defines the area. - - Attributes: - start (str): - Required. The start of the postal code range, - which is also the smallest in the range. - end (str): - The end of the postal code range. Will be the - same as start if not specified. - """ - - start: str = proto.Field( - proto.STRING, - number=1, - ) - end: str = proto.Field( - proto.STRING, - number=2, - ) - - location_id: int = proto.Field( - proto.INT64, - number=2, - oneof='location', - ) - post_code_range: TaxPostalCodeRange = proto.Field( - proto.MESSAGE, - number=3, - oneof='location', - message=TaxPostalCodeRange, - ) - use_google_rate: bool = proto.Field( - proto.BOOL, - number=4, - oneof='rate_calculation', - ) - self_specified_rate_micros: int = proto.Field( - proto.INT64, - number=5, - oneof='rate_calculation', - ) - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - shipping_taxed: bool = proto.Field( - proto.BOOL, - number=6, - ) - effective_time_period: interval_pb2.Interval = proto.Field( - proto.MESSAGE, - number=7, - message=interval_pb2.Interval, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py deleted file mode 100644 index 729b76843be8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservice.py +++ /dev/null @@ -1,164 +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.merchant_accounts_v1beta.types import termsofservicekind - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'TermsOfService', - 'GetTermsOfServiceRequest', - 'RetrieveLatestTermsOfServiceRequest', - 'AcceptTermsOfServiceRequest', - }, -) - - -class TermsOfService(proto.Message): - r"""A ``TermsOfService``. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the terms of service - version. Format: ``termsOfService/{version}`` - region_code (str): - Region code as defined by - `CLDR `__. This is either a - country where the ToS applies specifically to that country - or ``001`` when the same ``TermsOfService`` can be signed in - any country. However note that when signing a ToS that - applies globally we still expect that a specific country is - provided (this should be merchant business country or - program country of participation). - kind (google.shopping.merchant_accounts_v1beta.types.TermsOfServiceKind): - The Kind this terms of service version - applies to. - file_uri (str): - URI for terms of service file that needs to - be displayed to signing users. - - This field is a member of `oneof`_ ``_file_uri``. - external (bool): - Whether this terms of service version is - external. External terms of service versions can - only be agreed through external processes and - not directly by the merchant through UI or API. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - kind: termsofservicekind.TermsOfServiceKind = proto.Field( - proto.ENUM, - number=3, - enum=termsofservicekind.TermsOfServiceKind, - ) - file_uri: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - external: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class GetTermsOfServiceRequest(proto.Message): - r"""Request message for the ``GetTermsOfService`` method. - - Attributes: - name (str): - Required. The resource name of the terms of service version. - Format: ``termsOfService/{version}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RetrieveLatestTermsOfServiceRequest(proto.Message): - r"""Request message for the ``RetrieveLatestTermsOfService`` method. - - Attributes: - region_code (str): - Required. Region code as defined by - `CLDR `__. This is either a - country when the ToS applies specifically to that country or - 001 when it applies globally. - kind (google.shopping.merchant_accounts_v1beta.types.TermsOfServiceKind): - Required. The Kind this terms of service - version applies to. - """ - - region_code: str = proto.Field( - proto.STRING, - number=1, - ) - kind: termsofservicekind.TermsOfServiceKind = proto.Field( - proto.ENUM, - number=2, - enum=termsofservicekind.TermsOfServiceKind, - ) - - -class AcceptTermsOfServiceRequest(proto.Message): - r"""Request message for the ``AcceptTermsOfService`` method. - - Attributes: - name (str): - Required. The resource name of the terms of service version. - Format: ``termsOfService/{version}`` - account (str): - Required. The account for which to accept the - ToS. - region_code (str): - Required. Region code as defined by - `CLDR `__. This is either a - country when the ToS applies specifically to that country or - 001 when it applies globally. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - account: str = proto.Field( - proto.STRING, - number=2, - ) - region_code: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py deleted file mode 100644 index 236621a96424..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofserviceagreementstate.py +++ /dev/null @@ -1,217 +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.merchant_accounts_v1beta.types import termsofservicekind -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'TermsOfServiceAgreementState', - 'Accepted', - 'Required', - 'GetTermsOfServiceAgreementStateRequest', - 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', - }, -) - - -class TermsOfServiceAgreementState(proto.Message): - r"""This resource represents the agreement state for a given account and - terms of service kind. The state is as follows: - - - If the merchant has accepted a terms of service: - `accepted `__ will be - populated, otherwise it will be empty - - If the merchant must sign a terms of service: - `required `__ will be - populated, otherwise it will be empty. - - Note that both `required `__ - and `accepted `__ can be - present. In this case the ``accepted`` terms of services will have - an expiration date set in the `valid_until `__ - field. The ``required`` terms of services need to be accepted before - ``valid_until`` in order for the account to continue having a valid - agreement. When accepting new terms of services we expect 3Ps to - display the text associated with the given terms of service - agreement (the url to the file containing the text is added in the - Required message below as `tos_file_uri `__. - The actual acceptance of the terms of service is done by calling - accept on the `TermsOfService `__ resource. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The resource name of the terms of service - version. Format: - ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` - The identifier format is: ``{TermsOfServiceKind}-{country}`` - For example, an identifier could be: ``MERCHANT_CENTER-US`` - region_code (str): - Region code as defined by - https://cldr.unicode.org/. This is the country - the current state applies to. - terms_of_service_kind (google.shopping.merchant_accounts_v1beta.types.TermsOfServiceKind): - Terms of Service kind associated with the - particular version. - accepted (google.shopping.merchant_accounts_v1beta.types.Accepted): - The accepted terms of service of this kind and for the - associated region_code - - This field is a member of `oneof`_ ``_accepted``. - required (google.shopping.merchant_accounts_v1beta.types.Required): - The required terms of service - - This field is a member of `oneof`_ ``_required``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - region_code: str = proto.Field( - proto.STRING, - number=2, - ) - terms_of_service_kind: termsofservicekind.TermsOfServiceKind = proto.Field( - proto.ENUM, - number=3, - enum=termsofservicekind.TermsOfServiceKind, - ) - accepted: 'Accepted' = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message='Accepted', - ) - required: 'Required' = proto.Field( - proto.MESSAGE, - number=5, - optional=True, - message='Required', - ) - - -class Accepted(proto.Message): - r"""Describes the accepted terms of service. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - terms_of_service (str): - The accepted - `termsOfService `__. - accepted_by (str): - The account where the acceptance was - recorded. This can be the account itself or, in - the case of subaccounts, the MCA account. - valid_until (google.type.date_pb2.Date): - When set, it states that the accepted - `TermsOfService `__ - is only valid until the end of this date (in UTC). A new one - must be accepted before then. The information of the - required - `TermsOfService `__ - is found in the `Required `__ message. - - This field is a member of `oneof`_ ``_valid_until``. - """ - - terms_of_service: str = proto.Field( - proto.STRING, - number=1, - ) - accepted_by: str = proto.Field( - proto.STRING, - number=2, - ) - valid_until: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=3, - optional=True, - message=date_pb2.Date, - ) - - -class Required(proto.Message): - r"""Describes the terms of service which are required to be - accepted. - - Attributes: - terms_of_service (str): - The - `termsOfService `__ - that need to be accepted. - tos_file_uri (str): - Full URL to the terms of service file. This field is the - same as - `TermsOfService.file_uri `__, it is - added here for convenience only. - """ - - terms_of_service: str = proto.Field( - proto.STRING, - number=1, - ) - tos_file_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTermsOfServiceAgreementStateRequest(proto.Message): - r"""Request message for the ``GetTermsOfServiceAgreementState`` method. - - Attributes: - name (str): - Required. The resource name of the terms of service version. - Format: - ``accounts/{account}/termsOfServiceAgreementState/{identifier}`` - The identifier format is: ``{TermsOfServiceKind}-{country}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RetrieveForApplicationTermsOfServiceAgreementStateRequest(proto.Message): - r"""Request message for the - ``RetrieveForApplicationTermsOfServiceAgreementState`` method. - - Attributes: - parent (str): - Required. The account for which to get a - TermsOfServiceAgreementState Format: ``accounts/{account}`` - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py deleted file mode 100644 index 3a69671fc592..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/termsofservicekind.py +++ /dev/null @@ -1,44 +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 - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'TermsOfServiceKind', - }, -) - - -class TermsOfServiceKind(proto.Enum): - r"""The TermsOfService Kind. - - Values: - TERMS_OF_SERVICE_KIND_UNSPECIFIED (0): - Default value. This value is unused. - MERCHANT_CENTER (1): - Merchant Center application. - """ - TERMS_OF_SERVICE_KIND_UNSPECIFIED = 0 - MERCHANT_CENTER = 1 - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py deleted file mode 100644 index f291bde9bd29..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/types/user.py +++ /dev/null @@ -1,246 +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.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.types import accessright - - -__protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1beta', - manifest={ - 'User', - 'GetUserRequest', - 'CreateUserRequest', - 'DeleteUserRequest', - 'UpdateUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - }, -) - - -class User(proto.Message): - r"""A `user `__. - - Attributes: - name (str): - Identifier. The resource name of the user. Format: - ``accounts/{account}/user/{email}`` - - Use ``me`` to refer to your own email address, for example - ``accounts/{account}/users/me``. - state (google.shopping.merchant_accounts_v1beta.types.User.State): - Output only. The state of the user. - access_rights (MutableSequence[google.shopping.merchant_accounts_v1beta.types.AccessRight]): - Optional. The `access - rights `__ - the user has. - """ - class State(proto.Enum): - r"""The possible states of a user. - - Values: - STATE_UNSPECIFIED (0): - Default value. This value is unused. - PENDING (1): - The user is pending confirmation. In this - state, the user first needs to accept the - invitation before performing other actions. - VERIFIED (2): - The user is verified. - """ - STATE_UNSPECIFIED = 0 - PENDING = 1 - VERIFIED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - access_rights: MutableSequence[accessright.AccessRight] = proto.RepeatedField( - proto.ENUM, - number=4, - enum=accessright.AccessRight, - ) - - -class GetUserRequest(proto.Message): - r"""Request message for the ``GetUser`` method. - - Attributes: - name (str): - Required. The name of the user to retrieve. Format: - ``accounts/{account}/users/{email}`` - - It is also possible to retrieve the user corresponding to - the caller by using ``me`` rather than an email address as - in ``accounts/{account}/users/me``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateUserRequest(proto.Message): - r"""Request message for the ``CreateUser`` method. - - Attributes: - parent (str): - Required. The resource name of the account for which a user - will be created. Format: ``accounts/{account}`` - user_id (str): - Required. The email address of the user (for example, - ``john.doe@gmail.com``). - user (google.shopping.merchant_accounts_v1beta.types.User): - Required. The user to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_id: str = proto.Field( - proto.STRING, - number=2, - ) - user: 'User' = proto.Field( - proto.MESSAGE, - number=3, - message='User', - ) - - -class DeleteUserRequest(proto.Message): - r"""Request message for the ``DeleteUser`` method. - - Attributes: - name (str): - Required. The name of the user to delete. Format: - ``accounts/{account}/users/{email}`` - - It is also possible to delete the user corresponding to the - caller by using ``me`` rather than an email address as in - ``accounts/{account}/users/me``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateUserRequest(proto.Message): - r"""Request message for the ``UpdateUser`` method. - - Attributes: - user (google.shopping.merchant_accounts_v1beta.types.User): - Required. The new version of the user. - - Use ``me`` to refer to your own email address, for example - ``accounts/{account}/users/me``. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields being updated. - """ - - user: 'User' = proto.Field( - proto.MESSAGE, - number=1, - message='User', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class ListUsersRequest(proto.Message): - r"""Request message for the ``ListUsers`` method. - - Attributes: - parent (str): - Required. The parent, which owns this collection of users. - Format: ``accounts/{account}`` - page_size (int): - Optional. The maximum number of users to - return. The service may return fewer than this - value. If unspecified, at most 50 users will be - returned. The maximum value is 100; values above - 100 will be coerced to 100 - page_token (str): - Optional. A page token, received from a previous - ``ListUsers`` call. Provide this to retrieve the subsequent - page. - - When paginating, all other parameters provided to - ``ListUsers`` must match the call that provided the page - token. - """ - - 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 ListUsersResponse(proto.Message): - r"""Response message for the ``ListUsers`` method. - - Attributes: - users (MutableSequence[google.shopping.merchant_accounts_v1beta.types.User]): - The users from the specified account. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - users: MutableSequence['User'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='User', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/noxfile.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/noxfile.py deleted file mode 100644 index cc47a9500d4c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts" - -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-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py deleted file mode 100644 index 5ea1b7df8abb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_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 ListAccountIssues -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_accounts_v1beta - - -async def sample_list_account_issues(): - # Create a client - client = merchant_accounts_v1beta.AccountIssueServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountIssuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_issues(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py deleted file mode 100644 index 739c8d0391ad..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_issue_service_list_account_issues_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 ListAccountIssues -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_accounts_v1beta - - -def sample_list_account_issues(): - # Create a client - client = merchant_accounts_v1beta.AccountIssueServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountIssuesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_issues(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py deleted file mode 100644 index 2662cf461666..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAccountTax -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_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_accounts_v1beta - - -async def sample_get_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountTaxRequest( - name="name_value", - ) - - # Make the request - response = await client.get_account_tax(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py deleted file mode 100644 index b6096fa0a5d5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAccountTax -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_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_accounts_v1beta - - -def sample_get_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountTaxRequest( - name="name_value", - ) - - # Make the request - response = client.get_account_tax(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py deleted file mode 100644 index f97f38ee917e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_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 ListAccountTax -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_accounts_v1beta - - -async def sample_list_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountTaxRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_tax(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py deleted file mode 100644 index 97b36a68f990..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_list_account_tax_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 ListAccountTax -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_accounts_v1beta - - -def sample_list_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountTaxRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_account_tax(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py deleted file mode 100644 index a9ceabeaaf9b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAccountTax -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_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_accounts_v1beta - - -async def sample_update_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAccountTaxRequest( - ) - - # Make the request - response = await client.update_account_tax(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py deleted file mode 100644 index 0b93d3fd84ac..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAccountTax -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_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_accounts_v1beta - - -def sample_update_account_tax(): - # Create a client - client = merchant_accounts_v1beta.AccountTaxServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAccountTaxRequest( - ) - - # Make the request - response = client.update_account_tax(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py deleted file mode 100644 index 524357227830..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_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 CreateAndConfigureAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_v1beta - - -async def sample_create_and_configure_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( - account=account, - ) - - # Make the request - response = await client.create_and_configure_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py deleted file mode 100644 index eb1ec2212f92..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_create_and_configure_account_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 CreateAndConfigureAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_v1beta - - -def sample_create_and_configure_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.CreateAndConfigureAccountRequest( - account=account, - ) - - # Make the request - response = client.create_and_configure_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_async.py deleted file mode 100644 index c5fd09662410..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_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 DeleteAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_v1beta - - -async def sample_delete_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteAccountRequest( - name="name_value", - ) - - # Make the request - await client.delete_account(request=request) - - -# [END merchantapi_v1beta_generated_AccountsService_DeleteAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_sync.py deleted file mode 100644 index d57059d3101d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_delete_account_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 DeleteAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_v1beta - - -def sample_delete_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteAccountRequest( - name="name_value", - ) - - # Make the request - client.delete_account(request=request) - - -# [END merchantapi_v1beta_generated_AccountsService_DeleteAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.py deleted file mode 100644 index ccb025b6469a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_GetAccount_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_accounts_v1beta - - -async def sample_get_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountRequest( - name="name_value", - ) - - # Make the request - response = await client.get_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_GetAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.py deleted file mode 100644 index 683f29580390..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_get_account_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_GetAccount_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_accounts_v1beta - - -def sample_get_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAccountRequest( - name="name_value", - ) - - # Make the request - response = client.get_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_GetAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.py deleted file mode 100644 index 295ac6219ea6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAccounts -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_ListAccounts_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_accounts_v1beta - - -async def sample_list_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountsRequest( - ) - - # Make the request - page_result = client.list_accounts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_ListAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py deleted file mode 100644 index efbf4429fd18..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_accounts_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAccounts -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_ListAccounts_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_accounts_v1beta - - -def sample_list_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListAccountsRequest( - ) - - # Make the request - page_result = client.list_accounts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_ListAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py deleted file mode 100644 index 7310b1ccc6bb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_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 ListSubAccounts -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_v1beta - - -async def sample_list_sub_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListSubAccountsRequest( - provider="provider_value", - ) - - # Make the request - page_result = client.list_sub_accounts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_ListSubAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py deleted file mode 100644 index 0fd54afc2a11..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_list_sub_accounts_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 ListSubAccounts -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_v1beta - - -def sample_list_sub_accounts(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListSubAccountsRequest( - provider="provider_value", - ) - - # Make the request - page_result = client.list_sub_accounts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_ListSubAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_async.py deleted file mode 100644 index c4daae8aecfa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_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 UpdateAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_v1beta - - -async def sample_update_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceAsyncClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.UpdateAccountRequest( - account=account, - ) - - # Make the request - response = await client.update_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_UpdateAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_sync.py deleted file mode 100644 index b218b58166f5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_accounts_service_update_account_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 UpdateAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_v1beta - - -def sample_update_account(): - # Create a client - client = merchant_accounts_v1beta.AccountsServiceClient() - - # Initialize request argument(s) - account = merchant_accounts_v1beta.Account() - account.account_name = "account_name_value" - account.language_code = "language_code_value" - - request = merchant_accounts_v1beta.UpdateAccountRequest( - account=account, - ) - - # Make the request - response = client.update_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AccountsService_UpdateAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py deleted file mode 100644 index 3a477d5ec29a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAutofeedSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_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_accounts_v1beta - - -async def sample_get_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_autofeed_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py deleted file mode 100644 index 57b46e0531a5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAutofeedSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_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_accounts_v1beta - - -def sample_get_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutofeedSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_autofeed_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py deleted file mode 100644 index 6c4f2b643787..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAutofeedSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_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_accounts_v1beta - - -async def sample_update_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient() - - # Initialize request argument(s) - autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() - autofeed_settings.enable_products = True - - request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( - autofeed_settings=autofeed_settings, - ) - - # Make the request - response = await client.update_autofeed_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py deleted file mode 100644 index 58e602d06f98..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAutofeedSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_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_accounts_v1beta - - -def sample_update_autofeed_settings(): - # Create a client - client = merchant_accounts_v1beta.AutofeedSettingsServiceClient() - - # Initialize request argument(s) - autofeed_settings = merchant_accounts_v1beta.AutofeedSettings() - autofeed_settings.enable_products = True - - request = merchant_accounts_v1beta.UpdateAutofeedSettingsRequest( - autofeed_settings=autofeed_settings, - ) - - # Make the request - response = client.update_autofeed_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py deleted file mode 100644 index c87df778f553..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAutomaticImprovements -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_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_accounts_v1beta - - -async def sample_get_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_automatic_improvements(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py deleted file mode 100644 index 853d693b8371..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAutomaticImprovements -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_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_accounts_v1beta - - -def sample_get_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetAutomaticImprovementsRequest( - name="name_value", - ) - - # Make the request - response = client.get_automatic_improvements(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py deleted file mode 100644 index 75bde8f2d529..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAutomaticImprovements -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_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_accounts_v1beta - - -async def sample_update_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( - ) - - # Make the request - response = await client.update_automatic_improvements(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py deleted file mode 100644 index ec9c3fbf4e48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAutomaticImprovements -# 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-accounts - - -# [START merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_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_accounts_v1beta - - -def sample_update_automatic_improvements(): - # Create a client - client = merchant_accounts_v1beta.AutomaticImprovementsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateAutomaticImprovementsRequest( - ) - - # Make the request - response = client.update_automatic_improvements(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py deleted file mode 100644 index 9fc9a1b3d682..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetBusinessIdentity -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_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_accounts_v1beta - - -async def sample_get_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessIdentityRequest( - name="name_value", - ) - - # Make the request - response = await client.get_business_identity(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py deleted file mode 100644 index 4d4cd1ebdf0c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetBusinessIdentity -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_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_accounts_v1beta - - -def sample_get_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessIdentityRequest( - name="name_value", - ) - - # Make the request - response = client.get_business_identity(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py deleted file mode 100644 index ff68aacc2ec1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateBusinessIdentity -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_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_accounts_v1beta - - -async def sample_update_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( - ) - - # Make the request - response = await client.update_business_identity(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py deleted file mode 100644 index a0f345b233a9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateBusinessIdentity -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_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_accounts_v1beta - - -def sample_update_business_identity(): - # Create a client - client = merchant_accounts_v1beta.BusinessIdentityServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessIdentityRequest( - ) - - # Make the request - response = client.update_business_identity(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.py deleted file mode 100644 index b1f8ef39945c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetBusinessInfo -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_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_accounts_v1beta - - -async def sample_get_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.get_business_info(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py deleted file mode 100644 index 1e9c258b7ba2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_get_business_info_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetBusinessInfo -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_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_accounts_v1beta - - -def sample_get_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetBusinessInfoRequest( - name="name_value", - ) - - # Make the request - response = client.get_business_info(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.py deleted file mode 100644 index ff4add791367..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateBusinessInfo -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_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_accounts_v1beta - - -async def sample_update_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( - ) - - # Make the request - response = await client.update_business_info(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py deleted file mode 100644 index 757ae6ca4bb7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_business_info_service_update_business_info_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateBusinessInfo -# 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-accounts - - -# [START merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_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_accounts_v1beta - - -def sample_update_business_info(): - # Create a client - client = merchant_accounts_v1beta.BusinessInfoServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateBusinessInfoRequest( - ) - - # Make the request - response = client.update_business_info(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py deleted file mode 100644 index 28e4bb99f04a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_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_accounts_v1beta - - -async def sample_create_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_checkout_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py deleted file mode 100644 index 878e17cad080..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_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_accounts_v1beta - - -def sample_create_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateCheckoutSettingsRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_checkout_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py deleted file mode 100644 index 72c9127845e9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_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 DeleteCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_accounts_v1beta - - -async def sample_delete_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - await client.delete_checkout_settings(request=request) - - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py deleted file mode 100644 index b4475c2cf898..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_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 DeleteCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_accounts_v1beta - - -def sample_delete_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - client.delete_checkout_settings(request=request) - - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py deleted file mode 100644 index 11ff8acc9dfa..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_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_accounts_v1beta - - -async def sample_get_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_checkout_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py deleted file mode 100644 index 50b282ea7ce8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_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_accounts_v1beta - - -def sample_get_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetCheckoutSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_checkout_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py deleted file mode 100644 index 5ffcb28a76ef..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_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_accounts_v1beta - - -async def sample_update_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( - ) - - # Make the request - response = await client.update_checkout_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py deleted file mode 100644 index 22842b5365e3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCheckoutSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_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_accounts_v1beta - - -def sample_update_checkout_settings(): - # Create a client - client = merchant_accounts_v1beta.CheckoutSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateCheckoutSettingsRequest( - ) - - # Make the request - response = client.update_checkout_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py deleted file mode 100644 index 8bd2011f1ecd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEmailPreferences -# 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-accounts - - -# [START merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_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_accounts_v1beta - - -async def sample_get_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetEmailPreferencesRequest( - name="name_value", - ) - - # Make the request - response = await client.get_email_preferences(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py deleted file mode 100644 index a255955c9efe..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEmailPreferences -# 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-accounts - - -# [START merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_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_accounts_v1beta - - -def sample_get_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetEmailPreferencesRequest( - name="name_value", - ) - - # Make the request - response = client.get_email_preferences(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py deleted file mode 100644 index d9006e7658b5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEmailPreferences -# 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-accounts - - -# [START merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_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_accounts_v1beta - - -async def sample_update_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( - ) - - # Make the request - response = await client.update_email_preferences(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py deleted file mode 100644 index f31e1b2eb8ea..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEmailPreferences -# 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-accounts - - -# [START merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_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_accounts_v1beta - - -def sample_update_email_preferences(): - # Create a client - client = merchant_accounts_v1beta.EmailPreferencesServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateEmailPreferencesRequest( - ) - - # Make the request - response = client.update_email_preferences(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py deleted file mode 100644 index eecf278345da..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_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 LinkGbpAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_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_accounts_v1beta - - -async def sample_link_gbp_account(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkGbpAccountRequest( - parent="parent_value", - gbp_email="gbp_email_value", - ) - - # Make the request - response = await client.link_gbp_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py deleted file mode 100644 index f006819a7953..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_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 LinkGbpAccount -# 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-accounts - - -# [START merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_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_accounts_v1beta - - -def sample_link_gbp_account(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkGbpAccountRequest( - parent="parent_value", - gbp_email="gbp_email_value", - ) - - # Make the request - response = client.link_gbp_account(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py deleted file mode 100644 index 7d57d61ec1bb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_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 ListGbpAccounts -# 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-accounts - - -# [START merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_accounts_v1beta - - -async def sample_list_gbp_accounts(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListGbpAccountsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gbp_accounts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py deleted file mode 100644 index 1a542285bb4d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_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 ListGbpAccounts -# 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-accounts - - -# [START merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_accounts_v1beta - - -def sample_list_gbp_accounts(): - # Create a client - client = merchant_accounts_v1beta.GbpAccountsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListGbpAccountsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_gbp_accounts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py deleted file mode 100644 index 47084883b718..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClaimHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_ClaimHomepage_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_accounts_v1beta - - -async def sample_claim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ClaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = await client.claim_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_ClaimHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py deleted file mode 100644 index d4c0253ec7a2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ClaimHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_ClaimHomepage_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_accounts_v1beta - - -def sample_claim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ClaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = client.claim_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_ClaimHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.py deleted file mode 100644 index f7b6ea4eda79..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_GetHomepage_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_accounts_v1beta - - -async def sample_get_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetHomepageRequest( - name="name_value", - ) - - # Make the request - response = await client.get_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_GetHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py deleted file mode 100644 index 4c187f50e991..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_get_homepage_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_GetHomepage_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_accounts_v1beta - - -def sample_get_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetHomepageRequest( - name="name_value", - ) - - # Make the request - response = client.get_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_GetHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py deleted file mode 100644 index 6466c1c9a80c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UnclaimHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_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_accounts_v1beta - - -async def sample_unclaim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UnclaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = await client.unclaim_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py deleted file mode 100644 index 0504a1783151..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UnclaimHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_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_accounts_v1beta - - -def sample_unclaim_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UnclaimHomepageRequest( - name="name_value", - ) - - # Make the request - response = client.unclaim_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.py deleted file mode 100644 index 5c13393f78e8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_UpdateHomepage_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_accounts_v1beta - - -async def sample_update_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateHomepageRequest( - ) - - # Make the request - response = await client.update_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_UpdateHomepage_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py deleted file mode 100644 index f442ce3d814f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_homepage_service_update_homepage_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateHomepage -# 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-accounts - - -# [START merchantapi_v1beta_generated_HomepageService_UpdateHomepage_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_accounts_v1beta - - -def sample_update_homepage(): - # Create a client - client = merchant_accounts_v1beta.HomepageServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateHomepageRequest( - ) - - # Make the request - response = client.update_homepage(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_HomepageService_UpdateHomepage_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py deleted file mode 100644 index a12e25483799..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_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 FindLfpProviders -# 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-accounts - - -# [START merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_accounts_v1beta - - -async def sample_find_lfp_providers(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.FindLfpProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.find_lfp_providers(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py deleted file mode 100644 index 8bf78a657d87..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_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 FindLfpProviders -# 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-accounts - - -# [START merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_accounts_v1beta - - -def sample_find_lfp_providers(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.FindLfpProvidersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.find_lfp_providers(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py deleted file mode 100644 index f587f5c30f63..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_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 LinkLfpProvider -# 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-accounts - - -# [START merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_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_accounts_v1beta - - -async def sample_link_lfp_provider(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkLfpProviderRequest( - name="name_value", - external_account_id="external_account_id_value", - ) - - # Make the request - response = await client.link_lfp_provider(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py deleted file mode 100644 index b239c070f95e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_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 LinkLfpProvider -# 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-accounts - - -# [START merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_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_accounts_v1beta - - -def sample_link_lfp_provider(): - # Create a client - client = merchant_accounts_v1beta.LfpProvidersServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.LinkLfpProviderRequest( - name="name_value", - external_account_id="external_account_id_value", - ) - - # Make the request - response = client.link_lfp_provider(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py deleted file mode 100644 index 706c449172d5..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py +++ /dev/null @@ -1,57 +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 CreateOmnichannelSetting -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_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_accounts_v1beta - - -async def sample_create_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( - parent="parent_value", - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = await client.create_omnichannel_setting(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py deleted file mode 100644 index a7f32f69d2be..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py +++ /dev/null @@ -1,57 +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 CreateOmnichannelSetting -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_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_accounts_v1beta - - -def sample_create_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.CreateOmnichannelSettingRequest( - parent="parent_value", - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = client.create_omnichannel_setting(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py deleted file mode 100644 index bfe1ccd11d64..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOmnichannelSetting -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_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_accounts_v1beta - - -async def sample_get_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_omnichannel_setting(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py deleted file mode 100644 index 033e27b3fc48..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOmnichannelSetting -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_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_accounts_v1beta - - -def sample_get_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOmnichannelSettingRequest( - name="name_value", - ) - - # Make the request - response = client.get_omnichannel_setting(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py deleted file mode 100644 index 9b0867ed5318..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_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 ListOmnichannelSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_accounts_v1beta - - -async def sample_list_omnichannel_settings(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_omnichannel_settings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py deleted file mode 100644 index 6115d5a97488..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_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 ListOmnichannelSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_accounts_v1beta - - -def sample_list_omnichannel_settings(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOmnichannelSettingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_omnichannel_settings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py deleted file mode 100644 index 7d0336409326..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RequestInventoryVerification -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_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_accounts_v1beta - - -async def sample_request_inventory_verification(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( - name="name_value", - ) - - # Make the request - response = await client.request_inventory_verification(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py deleted file mode 100644 index 2b46b003b68f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RequestInventoryVerification -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_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_accounts_v1beta - - -def sample_request_inventory_verification(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RequestInventoryVerificationRequest( - name="name_value", - ) - - # Make the request - response = client.request_inventory_verification(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py deleted file mode 100644 index 1525ff8561bb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_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 UpdateOmnichannelSetting -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_accounts_v1beta - - -async def sample_update_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = await client.update_omnichannel_setting(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py deleted file mode 100644 index 0c5da4398674..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_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 UpdateOmnichannelSetting -# 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-accounts - - -# [START merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_accounts_v1beta - - -def sample_update_omnichannel_setting(): - # Create a client - client = merchant_accounts_v1beta.OmnichannelSettingsServiceClient() - - # Initialize request argument(s) - omnichannel_setting = merchant_accounts_v1beta.OmnichannelSetting() - omnichannel_setting.region_code = "region_code_value" - omnichannel_setting.lsf_type = "MHLSF_FULL" - - request = merchant_accounts_v1beta.UpdateOmnichannelSettingRequest( - omnichannel_setting=omnichannel_setting, - ) - - # Make the request - response = client.update_omnichannel_setting(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py deleted file mode 100644 index 7405774b5722..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py +++ /dev/null @@ -1,58 +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 CreateOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_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_accounts_v1beta - - -async def sample_create_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( - parent="parent_value", - online_return_policy=online_return_policy, - ) - - # Make the request - response = await client.create_online_return_policy(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py deleted file mode 100644 index d66ca038b30d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py +++ /dev/null @@ -1,58 +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 CreateOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_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_accounts_v1beta - - -def sample_create_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.CreateOnlineReturnPolicyRequest( - parent="parent_value", - online_return_policy=online_return_policy, - ) - - # Make the request - response = client.create_online_return_policy(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py deleted file mode 100644 index a4b12a0aaa87..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_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 DeleteOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_accounts_v1beta - - -async def sample_delete_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - await client.delete_online_return_policy(request=request) - - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py deleted file mode 100644 index a4825bcfce55..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_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 DeleteOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_accounts_v1beta - - -def sample_delete_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - client.delete_online_return_policy(request=request) - - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py deleted file mode 100644 index d1de7bf6b60e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_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_accounts_v1beta - - -async def sample_get_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_online_return_policy(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py deleted file mode 100644 index 36882cfc09ef..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_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_accounts_v1beta - - -def sample_get_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetOnlineReturnPolicyRequest( - name="name_value", - ) - - # Make the request - response = client.get_online_return_policy(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py deleted file mode 100644 index 66d247a87dd2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_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 ListOnlineReturnPolicies -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_accounts_v1beta - - -async def sample_list_online_return_policies(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_online_return_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py deleted file mode 100644 index 12c5a18b044e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_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 ListOnlineReturnPolicies -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_accounts_v1beta - - -def sample_list_online_return_policies(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListOnlineReturnPoliciesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_online_return_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py deleted file mode 100644 index 0681372595cc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py +++ /dev/null @@ -1,57 +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 UpdateOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_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_accounts_v1beta - - -async def sample_update_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( - online_return_policy=online_return_policy, - ) - - # Make the request - response = await client.update_online_return_policy(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py deleted file mode 100644 index c49e13300805..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py +++ /dev/null @@ -1,57 +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 UpdateOnlineReturnPolicy -# 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-accounts - - -# [START merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_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_accounts_v1beta - - -def sample_update_online_return_policy(): - # Create a client - client = merchant_accounts_v1beta.OnlineReturnPolicyServiceClient() - - # Initialize request argument(s) - online_return_policy = merchant_accounts_v1beta.OnlineReturnPolicy() - online_return_policy.label = "label_value" - online_return_policy.countries = ['countries_value1', 'countries_value2'] - online_return_policy.return_policy_uri = "return_policy_uri_value" - - request = merchant_accounts_v1beta.UpdateOnlineReturnPolicyRequest( - online_return_policy=online_return_policy, - ) - - # Make the request - response = client.update_online_return_policy(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.py deleted file mode 100644 index 2e7d9113e35c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DisableProgram -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_DisableProgram_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_accounts_v1beta - - -async def sample_disable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DisableProgramRequest( - name="name_value", - ) - - # Make the request - response = await client.disable_program(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_DisableProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.py deleted file mode 100644 index 725616f474bf..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_disable_program_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DisableProgram -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_DisableProgram_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_accounts_v1beta - - -def sample_disable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DisableProgramRequest( - name="name_value", - ) - - # Make the request - response = client.disable_program(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_DisableProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.py deleted file mode 100644 index f3d12b6b5f39..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EnableProgram -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_EnableProgram_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_accounts_v1beta - - -async def sample_enable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.EnableProgramRequest( - name="name_value", - ) - - # Make the request - response = await client.enable_program(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_EnableProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.py deleted file mode 100644 index 3dd0e3ab6043..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_enable_program_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for EnableProgram -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_EnableProgram_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_accounts_v1beta - - -def sample_enable_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.EnableProgramRequest( - name="name_value", - ) - - # Make the request - response = client.enable_program(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_EnableProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.py deleted file mode 100644 index 94b8bc9539e9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProgram -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_GetProgram_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_accounts_v1beta - - -async def sample_get_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetProgramRequest( - name="name_value", - ) - - # Make the request - response = await client.get_program(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_GetProgram_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.py deleted file mode 100644 index 19a37108cc6c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_get_program_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetProgram -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_GetProgram_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_accounts_v1beta - - -def sample_get_program(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetProgramRequest( - name="name_value", - ) - - # Make the request - response = client.get_program(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_GetProgram_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_async.py deleted file mode 100644 index 37e62d581817..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_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 ListPrograms -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_accounts_v1beta - - -async def sample_list_programs(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListProgramsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_programs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_ListPrograms_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_sync.py deleted file mode 100644 index 05d0c02972d1..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_programs_service_list_programs_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 ListPrograms -# 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-accounts - - -# [START merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_accounts_v1beta - - -def sample_list_programs(): - # Create a client - client = merchant_accounts_v1beta.ProgramsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListProgramsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_programs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_ProgramsService_ListPrograms_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_async.py deleted file mode 100644 index 37b7945cd1a3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_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 CreateRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_CreateRegion_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_accounts_v1beta - - -async def sample_create_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateRegionRequest( - parent="parent_value", - region_id="region_id_value", - ) - - # Make the request - response = await client.create_region(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_CreateRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_sync.py deleted file mode 100644 index a217601a8724..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_create_region_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 CreateRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_CreateRegion_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_accounts_v1beta - - -def sample_create_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateRegionRequest( - parent="parent_value", - region_id="region_id_value", - ) - - # Make the request - response = client.create_region(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_CreateRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_async.py deleted file mode 100644 index 6237e626537d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_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 DeleteRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_accounts_v1beta - - -async def sample_delete_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteRegionRequest( - name="name_value", - ) - - # Make the request - await client.delete_region(request=request) - - -# [END merchantapi_v1beta_generated_RegionsService_DeleteRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_sync.py deleted file mode 100644 index 7a62517691d6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_delete_region_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 DeleteRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_accounts_v1beta - - -def sample_delete_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteRegionRequest( - name="name_value", - ) - - # Make the request - client.delete_region(request=request) - - -# [END merchantapi_v1beta_generated_RegionsService_DeleteRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.py deleted file mode 100644 index 6e421a6a23fd..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_GetRegion_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_accounts_v1beta - - -async def sample_get_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetRegionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_region(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_GetRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.py deleted file mode 100644 index cf0d010b865e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_get_region_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_GetRegion_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_accounts_v1beta - - -def sample_get_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetRegionRequest( - name="name_value", - ) - - # Make the request - response = client.get_region(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_GetRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_async.py deleted file mode 100644 index c726eac7e898..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_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 ListRegions -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_ListRegions_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_accounts_v1beta - - -async def sample_list_regions(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListRegionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_ListRegions_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_sync.py deleted file mode 100644 index a8805b8fe32a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_list_regions_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 ListRegions -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_ListRegions_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_accounts_v1beta - - -def sample_list_regions(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListRegionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_regions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_ListRegions_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.py deleted file mode 100644 index 08d6a255a2af..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_UpdateRegion_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_accounts_v1beta - - -async def sample_update_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateRegionRequest( - ) - - # Make the request - response = await client.update_region(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_UpdateRegion_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.py deleted file mode 100644 index 6a00cfe1fc80..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_regions_service_update_region_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateRegion -# 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-accounts - - -# [START merchantapi_v1beta_generated_RegionsService_UpdateRegion_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_accounts_v1beta - - -def sample_update_region(): - # Create a client - client = merchant_accounts_v1beta.RegionsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateRegionRequest( - ) - - # Make the request - response = client.update_region(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_RegionsService_UpdateRegion_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py deleted file mode 100644 index 4323f9346b15..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetShippingSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_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_accounts_v1beta - - -async def sample_get_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetShippingSettingsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_shipping_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py deleted file mode 100644 index fee404678476..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetShippingSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_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_accounts_v1beta - - -def sample_get_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetShippingSettingsRequest( - name="name_value", - ) - - # Make the request - response = client.get_shipping_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py deleted file mode 100644 index da31f8338dd9..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_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 InsertShippingSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_accounts_v1beta - - -async def sample_insert_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient() - - # Initialize request argument(s) - shipping_setting = merchant_accounts_v1beta.ShippingSettings() - shipping_setting.etag = "etag_value" - - request = merchant_accounts_v1beta.InsertShippingSettingsRequest( - parent="parent_value", - shipping_setting=shipping_setting, - ) - - # Make the request - response = await client.insert_shipping_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py deleted file mode 100644 index d8e4f2b2bfdc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_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 InsertShippingSettings -# 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-accounts - - -# [START merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_accounts_v1beta - - -def sample_insert_shipping_settings(): - # Create a client - client = merchant_accounts_v1beta.ShippingSettingsServiceClient() - - # Initialize request argument(s) - shipping_setting = merchant_accounts_v1beta.ShippingSettings() - shipping_setting.etag = "etag_value" - - request = merchant_accounts_v1beta.InsertShippingSettingsRequest( - parent="parent_value", - shipping_setting=shipping_setting, - ) - - # Make the request - response = client.insert_shipping_settings(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py deleted file mode 100644 index 0f464690997a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTermsOfServiceAgreementState -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_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_accounts_v1beta - - -async def sample_get_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( - name="name_value", - ) - - # Make the request - response = await client.get_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py deleted file mode 100644 index 9c656bb9d8c7..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTermsOfServiceAgreementState -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_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_accounts_v1beta - - -def sample_get_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceAgreementStateRequest( - name="name_value", - ) - - # Make the request - response = client.get_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py deleted file mode 100644 index 2d22c2e0d3fe..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RetrieveForApplicationTermsOfServiceAgreementState -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_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_accounts_v1beta - - -async def sample_retrieve_for_application_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent="parent_value", - ) - - # Make the request - response = await client.retrieve_for_application_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py deleted file mode 100644 index 5c6186ae2016..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RetrieveForApplicationTermsOfServiceAgreementState -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_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_accounts_v1beta - - -def sample_retrieve_for_application_terms_of_service_agreement_state(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent="parent_value", - ) - - # Make the request - response = client.retrieve_for_application_terms_of_service_agreement_state(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py deleted file mode 100644 index 97be366b0de4..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AcceptTermsOfService -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_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_accounts_v1beta - - -async def sample_accept_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( - name="name_value", - account="account_value", - region_code="region_code_value", - ) - - # Make the request - await client.accept_terms_of_service(request=request) - - -# [END merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py deleted file mode 100644 index 31dda0c65fe0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AcceptTermsOfService -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_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_accounts_v1beta - - -def sample_accept_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.AcceptTermsOfServiceRequest( - name="name_value", - account="account_value", - region_code="region_code_value", - ) - - # Make the request - client.accept_terms_of_service(request=request) - - -# [END merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py deleted file mode 100644 index 322da3d5840c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTermsOfService -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_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_accounts_v1beta - - -async def sample_get_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_terms_of_service(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py deleted file mode 100644 index 5210b6498a73..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetTermsOfService -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_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_accounts_v1beta - - -def sample_get_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetTermsOfServiceRequest( - name="name_value", - ) - - # Make the request - response = client.get_terms_of_service(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py deleted file mode 100644 index 974535b17974..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_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 RetrieveLatestTermsOfService -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_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_accounts_v1beta - - -async def sample_retrieve_latest_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( - region_code="region_code_value", - kind="MERCHANT_CENTER", - ) - - # Make the request - response = await client.retrieve_latest_terms_of_service(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py deleted file mode 100644 index 7b020bb5ac91..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_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 RetrieveLatestTermsOfService -# 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-accounts - - -# [START merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_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_accounts_v1beta - - -def sample_retrieve_latest_terms_of_service(): - # Create a client - client = merchant_accounts_v1beta.TermsOfServiceServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.RetrieveLatestTermsOfServiceRequest( - region_code="region_code_value", - kind="MERCHANT_CENTER", - ) - - # Make the request - response = client.retrieve_latest_terms_of_service(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_async.py deleted file mode 100644 index 4abcac2f7919..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_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 CreateUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_CreateUser_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_accounts_v1beta - - -async def sample_create_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateUserRequest( - parent="parent_value", - user_id="user_id_value", - ) - - # Make the request - response = await client.create_user(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_UserService_CreateUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_sync.py deleted file mode 100644 index f36b4ebd09b0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_create_user_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 CreateUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_CreateUser_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_accounts_v1beta - - -def sample_create_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.CreateUserRequest( - parent="parent_value", - user_id="user_id_value", - ) - - # Make the request - response = client.create_user(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_UserService_CreateUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_async.py deleted file mode 100644 index 38af498e1287..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_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 DeleteUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_DeleteUser_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_accounts_v1beta - - -async def sample_delete_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteUserRequest( - name="name_value", - ) - - # Make the request - await client.delete_user(request=request) - - -# [END merchantapi_v1beta_generated_UserService_DeleteUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_sync.py deleted file mode 100644 index 48128db84c71..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_delete_user_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 DeleteUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_DeleteUser_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_accounts_v1beta - - -def sample_delete_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.DeleteUserRequest( - name="name_value", - ) - - # Make the request - client.delete_user(request=request) - - -# [END merchantapi_v1beta_generated_UserService_DeleteUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.py deleted file mode 100644 index 051bd2395c71..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_GetUser_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_accounts_v1beta - - -async def sample_get_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetUserRequest( - name="name_value", - ) - - # Make the request - response = await client.get_user(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_UserService_GetUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.py deleted file mode 100644 index d14d8c6ddc63..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_get_user_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_GetUser_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_accounts_v1beta - - -def sample_get_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.GetUserRequest( - name="name_value", - ) - - # Make the request - response = client.get_user(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_UserService_GetUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_async.py deleted file mode 100644 index ff5126147ce3..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_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 ListUsers -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_ListUsers_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_accounts_v1beta - - -async def sample_list_users(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListUsersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_UserService_ListUsers_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_sync.py deleted file mode 100644 index 52b2f13b83d2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_list_users_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 ListUsers -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_ListUsers_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_accounts_v1beta - - -def sample_list_users(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.ListUsersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_users(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END merchantapi_v1beta_generated_UserService_ListUsers_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.py deleted file mode 100644 index 8f8af4c92fda..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_async.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_UpdateUser_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_accounts_v1beta - - -async def sample_update_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceAsyncClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateUserRequest( - ) - - # Make the request - response = await client.update_user(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_UserService_UpdateUser_async] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.py deleted file mode 100644 index 5d2013ba3077..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/merchantapi_v1beta_generated_user_service_update_user_sync.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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateUser -# 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-accounts - - -# [START merchantapi_v1beta_generated_UserService_UpdateUser_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_accounts_v1beta - - -def sample_update_user(): - # Create a client - client = merchant_accounts_v1beta.UserServiceClient() - - # Initialize request argument(s) - request = merchant_accounts_v1beta.UpdateUserRequest( - ) - - # Make the request - response = client.update_user(request=request) - - # Handle the response - print(response) - -# [END merchantapi_v1beta_generated_UserService_UpdateUser_sync] diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json deleted file mode 100644 index 006404653801..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json +++ /dev/null @@ -1,10226 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.shopping.merchant.accounts.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-shopping-merchant-accounts", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceAsyncClient", - "shortName": "AccountIssueServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceAsyncClient.list_account_issues", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService.ListAccountIssues", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", - "shortName": "AccountIssueService" - }, - "shortName": "ListAccountIssues" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest" - }, - { - "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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesAsyncPager", - "shortName": "list_account_issues" - }, - "description": "Sample for ListAccountIssues", - "file": "merchantapi_v1beta_generated_account_issue_service_list_account_issues_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_account_issue_service_list_account_issues_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceClient", - "shortName": "AccountIssueServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountIssueServiceClient.list_account_issues", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService.ListAccountIssues", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountIssueService", - "shortName": "AccountIssueService" - }, - "shortName": "ListAccountIssues" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountIssuesRequest" - }, - { - "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_accounts_v1beta.services.account_issue_service.pagers.ListAccountIssuesPager", - "shortName": "list_account_issues" - }, - "description": "Sample for ListAccountIssues", - "file": "merchantapi_v1beta_generated_account_issue_service_list_account_issues_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountIssueService_ListAccountIssues_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_account_issue_service_list_account_issues_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient", - "shortName": "AccountTaxServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient.get_account_tax", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.GetAccountTax", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "shortName": "AccountTaxService" - }, - "shortName": "GetAccountTax" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", - "shortName": "get_account_tax" - }, - "description": "Sample for GetAccountTax", - "file": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient", - "shortName": "AccountTaxServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient.get_account_tax", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.GetAccountTax", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "shortName": "AccountTaxService" - }, - "shortName": "GetAccountTax" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountTaxRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.AccountTax", - "shortName": "get_account_tax" - }, - "description": "Sample for GetAccountTax", - "file": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountTaxService_GetAccountTax_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_account_tax_service_get_account_tax_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient", - "shortName": "AccountTaxServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient.list_account_tax", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.ListAccountTax", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "shortName": "AccountTaxService" - }, - "shortName": "ListAccountTax" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest" - }, - { - "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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxAsyncPager", - "shortName": "list_account_tax" - }, - "description": "Sample for ListAccountTax", - "file": "merchantapi_v1beta_generated_account_tax_service_list_account_tax_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_account_tax_service_list_account_tax_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient", - "shortName": "AccountTaxServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient.list_account_tax", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.ListAccountTax", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "shortName": "AccountTaxService" - }, - "shortName": "ListAccountTax" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountTaxRequest" - }, - { - "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_accounts_v1beta.services.account_tax_service.pagers.ListAccountTaxPager", - "shortName": "list_account_tax" - }, - "description": "Sample for ListAccountTax", - "file": "merchantapi_v1beta_generated_account_tax_service_list_account_tax_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountTaxService_ListAccountTax_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_account_tax_service_list_account_tax_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient", - "shortName": "AccountTaxServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceAsyncClient.update_account_tax", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.UpdateAccountTax", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "shortName": "AccountTaxService" - }, - "shortName": "UpdateAccountTax" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest" - }, - { - "name": "account_tax", - "type": "google.shopping.merchant_accounts_v1beta.types.AccountTax" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.AccountTax", - "shortName": "update_account_tax" - }, - "description": "Sample for UpdateAccountTax", - "file": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient", - "shortName": "AccountTaxServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountTaxServiceClient.update_account_tax", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService.UpdateAccountTax", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountTaxService", - "shortName": "AccountTaxService" - }, - "shortName": "UpdateAccountTax" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountTaxRequest" - }, - { - "name": "account_tax", - "type": "google.shopping.merchant_accounts_v1beta.types.AccountTax" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.AccountTax", - "shortName": "update_account_tax" - }, - "description": "Sample for UpdateAccountTax", - "file": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountTaxService_UpdateAccountTax_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_account_tax_service_update_account_tax_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", - "shortName": "AccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.create_and_configure_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.CreateAndConfigureAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "CreateAndConfigureAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest" - }, - { - "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_accounts_v1beta.types.Account", - "shortName": "create_and_configure_account" - }, - "description": "Sample for CreateAndConfigureAccount", - "file": "merchantapi_v1beta_generated_accounts_service_create_and_configure_account_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_service_create_and_configure_account_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", - "shortName": "AccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.create_and_configure_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.CreateAndConfigureAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "CreateAndConfigureAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateAndConfigureAccountRequest" - }, - { - "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_accounts_v1beta.types.Account", - "shortName": "create_and_configure_account" - }, - "description": "Sample for CreateAndConfigureAccount", - "file": "merchantapi_v1beta_generated_accounts_service_create_and_configure_account_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_CreateAndConfigureAccount_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_accounts_service_create_and_configure_account_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", - "shortName": "AccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.delete_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.DeleteAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "DeleteAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest" - }, - { - "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_account" - }, - "description": "Sample for DeleteAccount", - "file": "merchantapi_v1beta_generated_accounts_service_delete_account_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_service_delete_account_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", - "shortName": "AccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.delete_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.DeleteAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "DeleteAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteAccountRequest" - }, - { - "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_account" - }, - "description": "Sample for DeleteAccount", - "file": "merchantapi_v1beta_generated_accounts_service_delete_account_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_DeleteAccount_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_accounts_service_delete_account_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", - "shortName": "AccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.get_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.GetAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "GetAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", - "shortName": "get_account" - }, - "description": "Sample for GetAccount", - "file": "merchantapi_v1beta_generated_accounts_service_get_account_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_GetAccount_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_accounts_service_get_account_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", - "shortName": "AccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.get_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.GetAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "GetAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAccountRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Account", - "shortName": "get_account" - }, - "description": "Sample for GetAccount", - "file": "merchantapi_v1beta_generated_accounts_service_get_account_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_GetAccount_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_accounts_service_get_account_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", - "shortName": "AccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.list_accounts", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListAccounts", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "ListAccounts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest" - }, - { - "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_accounts_v1beta.services.accounts_service.pagers.ListAccountsAsyncPager", - "shortName": "list_accounts" - }, - "description": "Sample for ListAccounts", - "file": "merchantapi_v1beta_generated_accounts_service_list_accounts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_ListAccounts_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_accounts_service_list_accounts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", - "shortName": "AccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.list_accounts", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListAccounts", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "ListAccounts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListAccountsRequest" - }, - { - "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_accounts_v1beta.services.accounts_service.pagers.ListAccountsPager", - "shortName": "list_accounts" - }, - "description": "Sample for ListAccounts", - "file": "merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_ListAccounts_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_accounts_service_list_accounts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", - "shortName": "AccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.list_sub_accounts", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListSubAccounts", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "ListSubAccounts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest" - }, - { - "name": "provider", - "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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsAsyncPager", - "shortName": "list_sub_accounts" - }, - "description": "Sample for ListSubAccounts", - "file": "merchantapi_v1beta_generated_accounts_service_list_sub_accounts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_service_list_sub_accounts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", - "shortName": "AccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.list_sub_accounts", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.ListSubAccounts", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "ListSubAccounts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListSubAccountsRequest" - }, - { - "name": "provider", - "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_accounts_v1beta.services.accounts_service.pagers.ListSubAccountsPager", - "shortName": "list_sub_accounts" - }, - "description": "Sample for ListSubAccounts", - "file": "merchantapi_v1beta_generated_accounts_service_list_sub_accounts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_ListSubAccounts_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_accounts_service_list_sub_accounts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient", - "shortName": "AccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceAsyncClient.update_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.UpdateAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "UpdateAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest" - }, - { - "name": "account", - "type": "google.shopping.merchant_accounts_v1beta.types.Account" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.Account", - "shortName": "update_account" - }, - "description": "Sample for UpdateAccount", - "file": "merchantapi_v1beta_generated_accounts_service_update_account_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_service_update_account_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient", - "shortName": "AccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AccountsServiceClient.update_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService.UpdateAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AccountsService", - "shortName": "AccountsService" - }, - "shortName": "UpdateAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAccountRequest" - }, - { - "name": "account", - "type": "google.shopping.merchant_accounts_v1beta.types.Account" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.Account", - "shortName": "update_account" - }, - "description": "Sample for UpdateAccount", - "file": "merchantapi_v1beta_generated_accounts_service_update_account_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AccountsService_UpdateAccount_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_accounts_service_update_account_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient", - "shortName": "AutofeedSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient.get_autofeed_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.GetAutofeedSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "shortName": "AutofeedSettingsService" - }, - "shortName": "GetAutofeedSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", - "shortName": "get_autofeed_settings" - }, - "description": "Sample for GetAutofeedSettings", - "file": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient", - "shortName": "AutofeedSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient.get_autofeed_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.GetAutofeedSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "shortName": "AutofeedSettingsService" - }, - "shortName": "GetAutofeedSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAutofeedSettingsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings", - "shortName": "get_autofeed_settings" - }, - "description": "Sample for GetAutofeedSettings", - "file": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_GetAutofeedSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_autofeed_settings_service_get_autofeed_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient", - "shortName": "AutofeedSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceAsyncClient.update_autofeed_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.UpdateAutofeedSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "shortName": "AutofeedSettingsService" - }, - "shortName": "UpdateAutofeedSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest" - }, - { - "name": "autofeed_settings", - "type": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.AutofeedSettings", - "shortName": "update_autofeed_settings" - }, - "description": "Sample for UpdateAutofeedSettings", - "file": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient", - "shortName": "AutofeedSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutofeedSettingsServiceClient.update_autofeed_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService.UpdateAutofeedSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutofeedSettingsService", - "shortName": "AutofeedSettingsService" - }, - "shortName": "UpdateAutofeedSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutofeedSettingsRequest" - }, - { - "name": "autofeed_settings", - "type": "google.shopping.merchant_accounts_v1beta.types.AutofeedSettings" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.AutofeedSettings", - "shortName": "update_autofeed_settings" - }, - "description": "Sample for UpdateAutofeedSettings", - "file": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutofeedSettingsService_UpdateAutofeedSettings_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_autofeed_settings_service_update_autofeed_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient", - "shortName": "AutomaticImprovementsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient.get_automatic_improvements", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.GetAutomaticImprovements", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "shortName": "AutomaticImprovementsService" - }, - "shortName": "GetAutomaticImprovements" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements", - "shortName": "get_automatic_improvements" - }, - "description": "Sample for GetAutomaticImprovements", - "file": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient", - "shortName": "AutomaticImprovementsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient.get_automatic_improvements", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.GetAutomaticImprovements", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "shortName": "AutomaticImprovementsService" - }, - "shortName": "GetAutomaticImprovements" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetAutomaticImprovementsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements", - "shortName": "get_automatic_improvements" - }, - "description": "Sample for GetAutomaticImprovements", - "file": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_GetAutomaticImprovements_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_automatic_improvements_service_get_automatic_improvements_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient", - "shortName": "AutomaticImprovementsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceAsyncClient.update_automatic_improvements", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.UpdateAutomaticImprovements", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "shortName": "AutomaticImprovementsService" - }, - "shortName": "UpdateAutomaticImprovements" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest" - }, - { - "name": "automatic_improvements", - "type": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.AutomaticImprovements", - "shortName": "update_automatic_improvements" - }, - "description": "Sample for UpdateAutomaticImprovements", - "file": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient", - "shortName": "AutomaticImprovementsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.AutomaticImprovementsServiceClient.update_automatic_improvements", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService.UpdateAutomaticImprovements", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.AutomaticImprovementsService", - "shortName": "AutomaticImprovementsService" - }, - "shortName": "UpdateAutomaticImprovements" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateAutomaticImprovementsRequest" - }, - { - "name": "automatic_improvements", - "type": "google.shopping.merchant_accounts_v1beta.types.AutomaticImprovements" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.AutomaticImprovements", - "shortName": "update_automatic_improvements" - }, - "description": "Sample for UpdateAutomaticImprovements", - "file": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_AutomaticImprovementsService_UpdateAutomaticImprovements_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_automatic_improvements_service_update_automatic_improvements_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient", - "shortName": "BusinessIdentityServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient.get_business_identity", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.GetBusinessIdentity", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "shortName": "BusinessIdentityService" - }, - "shortName": "GetBusinessIdentity" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", - "shortName": "get_business_identity" - }, - "description": "Sample for GetBusinessIdentity", - "file": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient", - "shortName": "BusinessIdentityServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient.get_business_identity", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.GetBusinessIdentity", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "shortName": "BusinessIdentityService" - }, - "shortName": "GetBusinessIdentity" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessIdentityRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity", - "shortName": "get_business_identity" - }, - "description": "Sample for GetBusinessIdentity", - "file": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_GetBusinessIdentity_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_identity_service_get_business_identity_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient", - "shortName": "BusinessIdentityServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceAsyncClient.update_business_identity", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.UpdateBusinessIdentity", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "shortName": "BusinessIdentityService" - }, - "shortName": "UpdateBusinessIdentity" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest" - }, - { - "name": "business_identity", - "type": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.BusinessIdentity", - "shortName": "update_business_identity" - }, - "description": "Sample for UpdateBusinessIdentity", - "file": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient", - "shortName": "BusinessIdentityServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessIdentityServiceClient.update_business_identity", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService.UpdateBusinessIdentity", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessIdentityService", - "shortName": "BusinessIdentityService" - }, - "shortName": "UpdateBusinessIdentity" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessIdentityRequest" - }, - { - "name": "business_identity", - "type": "google.shopping.merchant_accounts_v1beta.types.BusinessIdentity" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.BusinessIdentity", - "shortName": "update_business_identity" - }, - "description": "Sample for UpdateBusinessIdentity", - "file": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessIdentityService_UpdateBusinessIdentity_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_identity_service_update_business_identity_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient", - "shortName": "BusinessInfoServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient.get_business_info", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.GetBusinessInfo", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "shortName": "BusinessInfoService" - }, - "shortName": "GetBusinessInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", - "shortName": "get_business_info" - }, - "description": "Sample for GetBusinessInfo", - "file": "merchantapi_v1beta_generated_business_info_service_get_business_info_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_info_service_get_business_info_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient", - "shortName": "BusinessInfoServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient.get_business_info", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.GetBusinessInfo", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "shortName": "BusinessInfoService" - }, - "shortName": "GetBusinessInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetBusinessInfoRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo", - "shortName": "get_business_info" - }, - "description": "Sample for GetBusinessInfo", - "file": "merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_GetBusinessInfo_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_info_service_get_business_info_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient", - "shortName": "BusinessInfoServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceAsyncClient.update_business_info", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.UpdateBusinessInfo", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "shortName": "BusinessInfoService" - }, - "shortName": "UpdateBusinessInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest" - }, - { - "name": "business_info", - "type": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.BusinessInfo", - "shortName": "update_business_info" - }, - "description": "Sample for UpdateBusinessInfo", - "file": "merchantapi_v1beta_generated_business_info_service_update_business_info_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_info_service_update_business_info_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient", - "shortName": "BusinessInfoServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.BusinessInfoServiceClient.update_business_info", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService.UpdateBusinessInfo", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.BusinessInfoService", - "shortName": "BusinessInfoService" - }, - "shortName": "UpdateBusinessInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateBusinessInfoRequest" - }, - { - "name": "business_info", - "type": "google.shopping.merchant_accounts_v1beta.types.BusinessInfo" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.BusinessInfo", - "shortName": "update_business_info" - }, - "description": "Sample for UpdateBusinessInfo", - "file": "merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_BusinessInfoService_UpdateBusinessInfo_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_business_info_service_update_business_info_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", - "shortName": "CheckoutSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.create_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.CreateCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "CreateCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "checkout_settings", - "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" - }, - { - "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_accounts_v1beta.types.CheckoutSettings", - "shortName": "create_checkout_settings" - }, - "description": "Sample for CreateCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", - "shortName": "CheckoutSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.create_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.CreateCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "CreateCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateCheckoutSettingsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "checkout_settings", - "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" - }, - { - "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_accounts_v1beta.types.CheckoutSettings", - "shortName": "create_checkout_settings" - }, - "description": "Sample for CreateCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_CreateCheckoutSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_checkout_settings_service_create_checkout_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", - "shortName": "CheckoutSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.delete_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.DeleteCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "DeleteCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest" - }, - { - "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_checkout_settings" - }, - "description": "Sample for DeleteCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_checkout_settings_service_delete_checkout_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", - "shortName": "CheckoutSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.delete_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.DeleteCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "DeleteCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteCheckoutSettingsRequest" - }, - { - "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_checkout_settings" - }, - "description": "Sample for DeleteCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_delete_checkout_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_DeleteCheckoutSettings_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_checkout_settings_service_delete_checkout_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", - "shortName": "CheckoutSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.get_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.GetCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "GetCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings", - "shortName": "get_checkout_settings" - }, - "description": "Sample for GetCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", - "shortName": "CheckoutSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.get_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.GetCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "GetCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetCheckoutSettingsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings", - "shortName": "get_checkout_settings" - }, - "description": "Sample for GetCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_GetCheckoutSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_checkout_settings_service_get_checkout_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient", - "shortName": "CheckoutSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceAsyncClient.update_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.UpdateCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "UpdateCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest" - }, - { - "name": "checkout_settings", - "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.CheckoutSettings", - "shortName": "update_checkout_settings" - }, - "description": "Sample for UpdateCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient", - "shortName": "CheckoutSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.CheckoutSettingsServiceClient.update_checkout_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService.UpdateCheckoutSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.CheckoutSettingsService", - "shortName": "CheckoutSettingsService" - }, - "shortName": "UpdateCheckoutSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateCheckoutSettingsRequest" - }, - { - "name": "checkout_settings", - "type": "google.shopping.merchant_accounts_v1beta.types.CheckoutSettings" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.CheckoutSettings", - "shortName": "update_checkout_settings" - }, - "description": "Sample for UpdateCheckoutSettings", - "file": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_CheckoutSettingsService_UpdateCheckoutSettings_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_checkout_settings_service_update_checkout_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient", - "shortName": "EmailPreferencesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient.get_email_preferences", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.GetEmailPreferences", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "shortName": "EmailPreferencesService" - }, - "shortName": "GetEmailPreferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", - "shortName": "get_email_preferences" - }, - "description": "Sample for GetEmailPreferences", - "file": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient", - "shortName": "EmailPreferencesServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient.get_email_preferences", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.GetEmailPreferences", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "shortName": "EmailPreferencesService" - }, - "shortName": "GetEmailPreferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetEmailPreferencesRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences", - "shortName": "get_email_preferences" - }, - "description": "Sample for GetEmailPreferences", - "file": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_GetEmailPreferences_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_email_preferences_service_get_email_preferences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient", - "shortName": "EmailPreferencesServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceAsyncClient.update_email_preferences", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.UpdateEmailPreferences", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "shortName": "EmailPreferencesService" - }, - "shortName": "UpdateEmailPreferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest" - }, - { - "name": "email_preferences", - "type": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.EmailPreferences", - "shortName": "update_email_preferences" - }, - "description": "Sample for UpdateEmailPreferences", - "file": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient", - "shortName": "EmailPreferencesServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.EmailPreferencesServiceClient.update_email_preferences", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService.UpdateEmailPreferences", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.EmailPreferencesService", - "shortName": "EmailPreferencesService" - }, - "shortName": "UpdateEmailPreferences" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateEmailPreferencesRequest" - }, - { - "name": "email_preferences", - "type": "google.shopping.merchant_accounts_v1beta.types.EmailPreferences" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.EmailPreferences", - "shortName": "update_email_preferences" - }, - "description": "Sample for UpdateEmailPreferences", - "file": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_EmailPreferencesService_UpdateEmailPreferences_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_email_preferences_service_update_email_preferences_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient", - "shortName": "GbpAccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient.link_gbp_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.LinkGbpAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "shortName": "GbpAccountsService" - }, - "shortName": "LinkGbpAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest" - }, - { - "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_accounts_v1beta.types.LinkGbpAccountResponse", - "shortName": "link_gbp_account" - }, - "description": "Sample for LinkGbpAccount", - "file": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient", - "shortName": "GbpAccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient.link_gbp_account", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.LinkGbpAccount", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "shortName": "GbpAccountsService" - }, - "shortName": "LinkGbpAccount" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.LinkGbpAccountRequest" - }, - { - "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_accounts_v1beta.types.LinkGbpAccountResponse", - "shortName": "link_gbp_account" - }, - "description": "Sample for LinkGbpAccount", - "file": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_LinkGbpAccount_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_gbp_accounts_service_link_gbp_account_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient", - "shortName": "GbpAccountsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceAsyncClient.list_gbp_accounts", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.ListGbpAccounts", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "shortName": "GbpAccountsService" - }, - "shortName": "ListGbpAccounts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest" - }, - { - "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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsAsyncPager", - "shortName": "list_gbp_accounts" - }, - "description": "Sample for ListGbpAccounts", - "file": "merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_gbp_accounts_service_list_gbp_accounts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient", - "shortName": "GbpAccountsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.GbpAccountsServiceClient.list_gbp_accounts", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService.ListGbpAccounts", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.GbpAccountsService", - "shortName": "GbpAccountsService" - }, - "shortName": "ListGbpAccounts" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListGbpAccountsRequest" - }, - { - "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_accounts_v1beta.services.gbp_accounts_service.pagers.ListGbpAccountsPager", - "shortName": "list_gbp_accounts" - }, - "description": "Sample for ListGbpAccounts", - "file": "merchantapi_v1beta_generated_gbp_accounts_service_list_gbp_accounts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_GbpAccountsService_ListGbpAccounts_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_gbp_accounts_service_list_gbp_accounts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", - "shortName": "HomepageServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.claim_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.ClaimHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "ClaimHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest" - }, - { - "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_accounts_v1beta.types.Homepage", - "shortName": "claim_homepage" - }, - "description": "Sample for ClaimHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_ClaimHomepage_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_claim_homepage_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", - "shortName": "HomepageServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.claim_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.ClaimHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "ClaimHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ClaimHomepageRequest" - }, - { - "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_accounts_v1beta.types.Homepage", - "shortName": "claim_homepage" - }, - "description": "Sample for ClaimHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_ClaimHomepage_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_claim_homepage_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", - "shortName": "HomepageServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.get_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.GetHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "GetHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", - "shortName": "get_homepage" - }, - "description": "Sample for GetHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_get_homepage_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_GetHomepage_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_get_homepage_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", - "shortName": "HomepageServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.get_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.GetHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "GetHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetHomepageRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Homepage", - "shortName": "get_homepage" - }, - "description": "Sample for GetHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_GetHomepage_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_get_homepage_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", - "shortName": "HomepageServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.unclaim_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UnclaimHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "UnclaimHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest" - }, - { - "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_accounts_v1beta.types.Homepage", - "shortName": "unclaim_homepage" - }, - "description": "Sample for UnclaimHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", - "shortName": "HomepageServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.unclaim_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UnclaimHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "UnclaimHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UnclaimHomepageRequest" - }, - { - "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_accounts_v1beta.types.Homepage", - "shortName": "unclaim_homepage" - }, - "description": "Sample for UnclaimHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_UnclaimHomepage_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_unclaim_homepage_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient", - "shortName": "HomepageServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceAsyncClient.update_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UpdateHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "UpdateHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest" - }, - { - "name": "homepage", - "type": "google.shopping.merchant_accounts_v1beta.types.Homepage" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.Homepage", - "shortName": "update_homepage" - }, - "description": "Sample for UpdateHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_update_homepage_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_UpdateHomepage_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_update_homepage_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient", - "shortName": "HomepageServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.HomepageServiceClient.update_homepage", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService.UpdateHomepage", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.HomepageService", - "shortName": "HomepageService" - }, - "shortName": "UpdateHomepage" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateHomepageRequest" - }, - { - "name": "homepage", - "type": "google.shopping.merchant_accounts_v1beta.types.Homepage" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.Homepage", - "shortName": "update_homepage" - }, - "description": "Sample for UpdateHomepage", - "file": "merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_HomepageService_UpdateHomepage_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_homepage_service_update_homepage_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient", - "shortName": "LfpProvidersServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient.find_lfp_providers", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.FindLfpProviders", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "shortName": "LfpProvidersService" - }, - "shortName": "FindLfpProviders" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest" - }, - { - "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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersAsyncPager", - "shortName": "find_lfp_providers" - }, - "description": "Sample for FindLfpProviders", - "file": "merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_lfp_providers_service_find_lfp_providers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient", - "shortName": "LfpProvidersServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient.find_lfp_providers", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.FindLfpProviders", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "shortName": "LfpProvidersService" - }, - "shortName": "FindLfpProviders" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.FindLfpProvidersRequest" - }, - { - "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_accounts_v1beta.services.lfp_providers_service.pagers.FindLfpProvidersPager", - "shortName": "find_lfp_providers" - }, - "description": "Sample for FindLfpProviders", - "file": "merchantapi_v1beta_generated_lfp_providers_service_find_lfp_providers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_FindLfpProviders_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_lfp_providers_service_find_lfp_providers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient", - "shortName": "LfpProvidersServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceAsyncClient.link_lfp_provider", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.LinkLfpProvider", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "shortName": "LfpProvidersService" - }, - "shortName": "LinkLfpProvider" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse", - "shortName": "link_lfp_provider" - }, - "description": "Sample for LinkLfpProvider", - "file": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient", - "shortName": "LfpProvidersServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.LfpProvidersServiceClient.link_lfp_provider", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService.LinkLfpProvider", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.LfpProvidersService", - "shortName": "LfpProvidersService" - }, - "shortName": "LinkLfpProvider" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.LinkLfpProviderResponse", - "shortName": "link_lfp_provider" - }, - "description": "Sample for LinkLfpProvider", - "file": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_LfpProvidersService_LinkLfpProvider_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_lfp_providers_service_link_lfp_provider_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", - "shortName": "OmnichannelSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.create_omnichannel_setting", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.CreateOmnichannelSetting", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "CreateOmnichannelSetting" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "omnichannel_setting", - "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" - }, - { - "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_accounts_v1beta.types.OmnichannelSetting", - "shortName": "create_omnichannel_setting" - }, - "description": "Sample for CreateOmnichannelSetting", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", - "shortName": "OmnichannelSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.create_omnichannel_setting", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.CreateOmnichannelSetting", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "CreateOmnichannelSetting" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateOmnichannelSettingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "omnichannel_setting", - "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" - }, - { - "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_accounts_v1beta.types.OmnichannelSetting", - "shortName": "create_omnichannel_setting" - }, - "description": "Sample for CreateOmnichannelSetting", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_CreateOmnichannelSetting_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", - "shortName": "OmnichannelSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.get_omnichannel_setting", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.GetOmnichannelSetting", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "GetOmnichannelSetting" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting", - "shortName": "get_omnichannel_setting" - }, - "description": "Sample for GetOmnichannelSetting", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", - "shortName": "OmnichannelSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.get_omnichannel_setting", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.GetOmnichannelSetting", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "GetOmnichannelSetting" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetOmnichannelSettingRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting", - "shortName": "get_omnichannel_setting" - }, - "description": "Sample for GetOmnichannelSetting", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_GetOmnichannelSetting_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", - "shortName": "OmnichannelSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.list_omnichannel_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.ListOmnichannelSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "ListOmnichannelSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest" - }, - { - "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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsAsyncPager", - "shortName": "list_omnichannel_settings" - }, - "description": "Sample for ListOmnichannelSettings", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_omnichannel_settings_service_list_omnichannel_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", - "shortName": "OmnichannelSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.list_omnichannel_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.ListOmnichannelSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "ListOmnichannelSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListOmnichannelSettingsRequest" - }, - { - "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_accounts_v1beta.services.omnichannel_settings_service.pagers.ListOmnichannelSettingsPager", - "shortName": "list_omnichannel_settings" - }, - "description": "Sample for ListOmnichannelSettings", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_ListOmnichannelSettings_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_omnichannel_settings_service_list_omnichannel_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", - "shortName": "OmnichannelSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.request_inventory_verification", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.RequestInventoryVerification", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "RequestInventoryVerification" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse", - "shortName": "request_inventory_verification" - }, - "description": "Sample for RequestInventoryVerification", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", - "shortName": "OmnichannelSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.request_inventory_verification", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.RequestInventoryVerification", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "RequestInventoryVerification" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.RequestInventoryVerificationResponse", - "shortName": "request_inventory_verification" - }, - "description": "Sample for RequestInventoryVerification", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_RequestInventoryVerification_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_omnichannel_settings_service_request_inventory_verification_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient", - "shortName": "OmnichannelSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceAsyncClient.update_omnichannel_setting", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.UpdateOmnichannelSetting", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "UpdateOmnichannelSetting" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest" - }, - { - "name": "omnichannel_setting", - "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.OmnichannelSetting", - "shortName": "update_omnichannel_setting" - }, - "description": "Sample for UpdateOmnichannelSetting", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_omnichannel_settings_service_update_omnichannel_setting_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient", - "shortName": "OmnichannelSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OmnichannelSettingsServiceClient.update_omnichannel_setting", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService.UpdateOmnichannelSetting", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OmnichannelSettingsService", - "shortName": "OmnichannelSettingsService" - }, - "shortName": "UpdateOmnichannelSetting" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOmnichannelSettingRequest" - }, - { - "name": "omnichannel_setting", - "type": "google.shopping.merchant_accounts_v1beta.types.OmnichannelSetting" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.OmnichannelSetting", - "shortName": "update_omnichannel_setting" - }, - "description": "Sample for UpdateOmnichannelSetting", - "file": "merchantapi_v1beta_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OmnichannelSettingsService_UpdateOmnichannelSetting_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_omnichannel_settings_service_update_omnichannel_setting_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", - "shortName": "OnlineReturnPolicyServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.create_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.CreateOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "CreateOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "online_return_policy", - "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" - }, - { - "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_accounts_v1beta.types.OnlineReturnPolicy", - "shortName": "create_online_return_policy" - }, - "description": "Sample for CreateOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", - "shortName": "OnlineReturnPolicyServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.create_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.CreateOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "CreateOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateOnlineReturnPolicyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "online_return_policy", - "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" - }, - { - "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_accounts_v1beta.types.OnlineReturnPolicy", - "shortName": "create_online_return_policy" - }, - "description": "Sample for CreateOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_CreateOnlineReturnPolicy_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_online_return_policy_service_create_online_return_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", - "shortName": "OnlineReturnPolicyServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.delete_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.DeleteOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "DeleteOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest" - }, - { - "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_online_return_policy" - }, - "description": "Sample for DeleteOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_online_return_policy_service_delete_online_return_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", - "shortName": "OnlineReturnPolicyServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.delete_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.DeleteOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "DeleteOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteOnlineReturnPolicyRequest" - }, - { - "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_online_return_policy" - }, - "description": "Sample for DeleteOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_delete_online_return_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_DeleteOnlineReturnPolicy_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_online_return_policy_service_delete_online_return_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", - "shortName": "OnlineReturnPolicyServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.get_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.GetOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "GetOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy", - "shortName": "get_online_return_policy" - }, - "description": "Sample for GetOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", - "shortName": "OnlineReturnPolicyServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.get_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.GetOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "GetOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetOnlineReturnPolicyRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy", - "shortName": "get_online_return_policy" - }, - "description": "Sample for GetOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_GetOnlineReturnPolicy_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_online_return_policy_service_get_online_return_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", - "shortName": "OnlineReturnPolicyServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.list_online_return_policies", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.ListOnlineReturnPolicies", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "ListOnlineReturnPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest" - }, - { - "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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesAsyncPager", - "shortName": "list_online_return_policies" - }, - "description": "Sample for ListOnlineReturnPolicies", - "file": "merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_online_return_policy_service_list_online_return_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", - "shortName": "OnlineReturnPolicyServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.list_online_return_policies", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.ListOnlineReturnPolicies", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "ListOnlineReturnPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListOnlineReturnPoliciesRequest" - }, - { - "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_accounts_v1beta.services.online_return_policy_service.pagers.ListOnlineReturnPoliciesPager", - "shortName": "list_online_return_policies" - }, - "description": "Sample for ListOnlineReturnPolicies", - "file": "merchantapi_v1beta_generated_online_return_policy_service_list_online_return_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_ListOnlineReturnPolicies_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_online_return_policy_service_list_online_return_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient", - "shortName": "OnlineReturnPolicyServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceAsyncClient.update_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.UpdateOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "UpdateOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest" - }, - { - "name": "online_return_policy", - "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.OnlineReturnPolicy", - "shortName": "update_online_return_policy" - }, - "description": "Sample for UpdateOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient", - "shortName": "OnlineReturnPolicyServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.OnlineReturnPolicyServiceClient.update_online_return_policy", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService.UpdateOnlineReturnPolicy", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.OnlineReturnPolicyService", - "shortName": "OnlineReturnPolicyService" - }, - "shortName": "UpdateOnlineReturnPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateOnlineReturnPolicyRequest" - }, - { - "name": "online_return_policy", - "type": "google.shopping.merchant_accounts_v1beta.types.OnlineReturnPolicy" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.OnlineReturnPolicy", - "shortName": "update_online_return_policy" - }, - "description": "Sample for UpdateOnlineReturnPolicy", - "file": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_OnlineReturnPolicyService_UpdateOnlineReturnPolicy_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_online_return_policy_service_update_online_return_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", - "shortName": "ProgramsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.disable_program", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.DisableProgram", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "DisableProgram" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", - "shortName": "disable_program" - }, - "description": "Sample for DisableProgram", - "file": "merchantapi_v1beta_generated_programs_service_disable_program_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_DisableProgram_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_programs_service_disable_program_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", - "shortName": "ProgramsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.disable_program", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.DisableProgram", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "DisableProgram" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DisableProgramRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", - "shortName": "disable_program" - }, - "description": "Sample for DisableProgram", - "file": "merchantapi_v1beta_generated_programs_service_disable_program_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_DisableProgram_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_programs_service_disable_program_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", - "shortName": "ProgramsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.enable_program", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.EnableProgram", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "EnableProgram" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", - "shortName": "enable_program" - }, - "description": "Sample for EnableProgram", - "file": "merchantapi_v1beta_generated_programs_service_enable_program_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_EnableProgram_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_programs_service_enable_program_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", - "shortName": "ProgramsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.enable_program", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.EnableProgram", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "EnableProgram" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.EnableProgramRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", - "shortName": "enable_program" - }, - "description": "Sample for EnableProgram", - "file": "merchantapi_v1beta_generated_programs_service_enable_program_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_EnableProgram_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_programs_service_enable_program_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", - "shortName": "ProgramsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.get_program", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.GetProgram", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "GetProgram" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetProgramRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", - "shortName": "get_program" - }, - "description": "Sample for GetProgram", - "file": "merchantapi_v1beta_generated_programs_service_get_program_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_GetProgram_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_programs_service_get_program_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", - "shortName": "ProgramsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.get_program", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.GetProgram", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "GetProgram" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetProgramRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Program", - "shortName": "get_program" - }, - "description": "Sample for GetProgram", - "file": "merchantapi_v1beta_generated_programs_service_get_program_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_GetProgram_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_programs_service_get_program_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient", - "shortName": "ProgramsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceAsyncClient.list_programs", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.ListPrograms", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "ListPrograms" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest" - }, - { - "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_accounts_v1beta.services.programs_service.pagers.ListProgramsAsyncPager", - "shortName": "list_programs" - }, - "description": "Sample for ListPrograms", - "file": "merchantapi_v1beta_generated_programs_service_list_programs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_programs_service_list_programs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient", - "shortName": "ProgramsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ProgramsServiceClient.list_programs", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService.ListPrograms", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ProgramsService", - "shortName": "ProgramsService" - }, - "shortName": "ListPrograms" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListProgramsRequest" - }, - { - "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_accounts_v1beta.services.programs_service.pagers.ListProgramsPager", - "shortName": "list_programs" - }, - "description": "Sample for ListPrograms", - "file": "merchantapi_v1beta_generated_programs_service_list_programs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ProgramsService_ListPrograms_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_programs_service_list_programs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", - "shortName": "RegionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.create_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.CreateRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "CreateRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "region", - "type": "google.shopping.merchant_accounts_v1beta.types.Region" - }, - { - "name": "region_id", - "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_accounts_v1beta.types.Region", - "shortName": "create_region" - }, - "description": "Sample for CreateRegion", - "file": "merchantapi_v1beta_generated_regions_service_create_region_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_CreateRegion_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regions_service_create_region_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", - "shortName": "RegionsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.create_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.CreateRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "CreateRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateRegionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "region", - "type": "google.shopping.merchant_accounts_v1beta.types.Region" - }, - { - "name": "region_id", - "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_accounts_v1beta.types.Region", - "shortName": "create_region" - }, - "description": "Sample for CreateRegion", - "file": "merchantapi_v1beta_generated_regions_service_create_region_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_CreateRegion_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regions_service_create_region_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", - "shortName": "RegionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.delete_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.DeleteRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "DeleteRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest" - }, - { - "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_region" - }, - "description": "Sample for DeleteRegion", - "file": "merchantapi_v1beta_generated_regions_service_delete_region_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_regions_service_delete_region_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", - "shortName": "RegionsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.delete_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.DeleteRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "DeleteRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteRegionRequest" - }, - { - "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_region" - }, - "description": "Sample for DeleteRegion", - "file": "merchantapi_v1beta_generated_regions_service_delete_region_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_DeleteRegion_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_regions_service_delete_region_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", - "shortName": "RegionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.get_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.GetRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "GetRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetRegionRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", - "shortName": "get_region" - }, - "description": "Sample for GetRegion", - "file": "merchantapi_v1beta_generated_regions_service_get_region_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_GetRegion_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regions_service_get_region_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", - "shortName": "RegionsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.get_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.GetRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "GetRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetRegionRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.Region", - "shortName": "get_region" - }, - "description": "Sample for GetRegion", - "file": "merchantapi_v1beta_generated_regions_service_get_region_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_GetRegion_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regions_service_get_region_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", - "shortName": "RegionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.list_regions", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.ListRegions", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "ListRegions" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest" - }, - { - "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_accounts_v1beta.services.regions_service.pagers.ListRegionsAsyncPager", - "shortName": "list_regions" - }, - "description": "Sample for ListRegions", - "file": "merchantapi_v1beta_generated_regions_service_list_regions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_ListRegions_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_regions_service_list_regions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", - "shortName": "RegionsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.list_regions", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.ListRegions", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "ListRegions" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListRegionsRequest" - }, - { - "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_accounts_v1beta.services.regions_service.pagers.ListRegionsPager", - "shortName": "list_regions" - }, - "description": "Sample for ListRegions", - "file": "merchantapi_v1beta_generated_regions_service_list_regions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_ListRegions_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_regions_service_list_regions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient", - "shortName": "RegionsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceAsyncClient.update_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.UpdateRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "UpdateRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest" - }, - { - "name": "region", - "type": "google.shopping.merchant_accounts_v1beta.types.Region" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.Region", - "shortName": "update_region" - }, - "description": "Sample for UpdateRegion", - "file": "merchantapi_v1beta_generated_regions_service_update_region_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_UpdateRegion_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regions_service_update_region_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient", - "shortName": "RegionsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.RegionsServiceClient.update_region", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService.UpdateRegion", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.RegionsService", - "shortName": "RegionsService" - }, - "shortName": "UpdateRegion" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateRegionRequest" - }, - { - "name": "region", - "type": "google.shopping.merchant_accounts_v1beta.types.Region" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.Region", - "shortName": "update_region" - }, - "description": "Sample for UpdateRegion", - "file": "merchantapi_v1beta_generated_regions_service_update_region_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_RegionsService_UpdateRegion_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_regions_service_update_region_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient", - "shortName": "ShippingSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient.get_shipping_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.GetShippingSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "shortName": "ShippingSettingsService" - }, - "shortName": "GetShippingSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", - "shortName": "get_shipping_settings" - }, - "description": "Sample for GetShippingSettings", - "file": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient", - "shortName": "ShippingSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient.get_shipping_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.GetShippingSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "shortName": "ShippingSettingsService" - }, - "shortName": "GetShippingSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetShippingSettingsRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.ShippingSettings", - "shortName": "get_shipping_settings" - }, - "description": "Sample for GetShippingSettings", - "file": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_GetShippingSettings_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_shipping_settings_service_get_shipping_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient", - "shortName": "ShippingSettingsServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceAsyncClient.insert_shipping_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.InsertShippingSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "shortName": "ShippingSettingsService" - }, - "shortName": "InsertShippingSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest" - }, - { - "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_accounts_v1beta.types.ShippingSettings", - "shortName": "insert_shipping_settings" - }, - "description": "Sample for InsertShippingSettings", - "file": "merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_shipping_settings_service_insert_shipping_settings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient", - "shortName": "ShippingSettingsServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.ShippingSettingsServiceClient.insert_shipping_settings", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService.InsertShippingSettings", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.ShippingSettingsService", - "shortName": "ShippingSettingsService" - }, - "shortName": "InsertShippingSettings" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.InsertShippingSettingsRequest" - }, - { - "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_accounts_v1beta.types.ShippingSettings", - "shortName": "insert_shipping_settings" - }, - "description": "Sample for InsertShippingSettings", - "file": "merchantapi_v1beta_generated_shipping_settings_service_insert_shipping_settings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_ShippingSettingsService_InsertShippingSettings_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_shipping_settings_service_insert_shipping_settings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient", - "shortName": "TermsOfServiceAgreementStateServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient.get_terms_of_service_agreement_state", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.GetTermsOfServiceAgreementState", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "shortName": "TermsOfServiceAgreementStateService" - }, - "shortName": "GetTermsOfServiceAgreementState" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", - "shortName": "get_terms_of_service_agreement_state" - }, - "description": "Sample for GetTermsOfServiceAgreementState", - "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient", - "shortName": "TermsOfServiceAgreementStateServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.GetTermsOfServiceAgreementState", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "shortName": "TermsOfServiceAgreementStateService" - }, - "shortName": "GetTermsOfServiceAgreementState" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceAgreementStateRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfServiceAgreementState", - "shortName": "get_terms_of_service_agreement_state" - }, - "description": "Sample for GetTermsOfServiceAgreementState", - "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_GetTermsOfServiceAgreementState_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient", - "shortName": "TermsOfServiceAgreementStateServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceAsyncClient.retrieve_for_application_terms_of_service_agreement_state", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.RetrieveForApplicationTermsOfServiceAgreementState", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "shortName": "TermsOfServiceAgreementStateService" - }, - "shortName": "RetrieveForApplicationTermsOfServiceAgreementState" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest" - }, - { - "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_accounts_v1beta.types.TermsOfServiceAgreementState", - "shortName": "retrieve_for_application_terms_of_service_agreement_state" - }, - "description": "Sample for RetrieveForApplicationTermsOfServiceAgreementState", - "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient", - "shortName": "TermsOfServiceAgreementStateServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService.RetrieveForApplicationTermsOfServiceAgreementState", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceAgreementStateService", - "shortName": "TermsOfServiceAgreementStateService" - }, - "shortName": "RetrieveForApplicationTermsOfServiceAgreementState" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveForApplicationTermsOfServiceAgreementStateRequest" - }, - { - "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_accounts_v1beta.types.TermsOfServiceAgreementState", - "shortName": "retrieve_for_application_terms_of_service_agreement_state" - }, - "description": "Sample for RetrieveForApplicationTermsOfServiceAgreementState", - "file": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceAgreementStateService_RetrieveForApplicationTermsOfServiceAgreementState_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient", - "shortName": "TermsOfServiceServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient.accept_terms_of_service", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.AcceptTermsOfService", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "shortName": "TermsOfServiceService" - }, - "shortName": "AcceptTermsOfService" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest" - }, - { - "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": "accept_terms_of_service" - }, - "description": "Sample for AcceptTermsOfService", - "file": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient", - "shortName": "TermsOfServiceServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient.accept_terms_of_service", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.AcceptTermsOfService", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "shortName": "TermsOfServiceService" - }, - "shortName": "AcceptTermsOfService" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.AcceptTermsOfServiceRequest" - }, - { - "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": "accept_terms_of_service" - }, - "description": "Sample for AcceptTermsOfService", - "file": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_AcceptTermsOfService_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_service_accept_terms_of_service_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient", - "shortName": "TermsOfServiceServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient.get_terms_of_service", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.GetTermsOfService", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "shortName": "TermsOfServiceService" - }, - "shortName": "GetTermsOfService" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", - "shortName": "get_terms_of_service" - }, - "description": "Sample for GetTermsOfService", - "file": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient", - "shortName": "TermsOfServiceServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient.get_terms_of_service", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.GetTermsOfService", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "shortName": "TermsOfServiceService" - }, - "shortName": "GetTermsOfService" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetTermsOfServiceRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.TermsOfService", - "shortName": "get_terms_of_service" - }, - "description": "Sample for GetTermsOfService", - "file": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_GetTermsOfService_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_service_get_terms_of_service_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient", - "shortName": "TermsOfServiceServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceAsyncClient.retrieve_latest_terms_of_service", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.RetrieveLatestTermsOfService", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "shortName": "TermsOfServiceService" - }, - "shortName": "RetrieveLatestTermsOfService" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest" - }, - { - "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_accounts_v1beta.types.TermsOfService", - "shortName": "retrieve_latest_terms_of_service" - }, - "description": "Sample for RetrieveLatestTermsOfService", - "file": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient", - "shortName": "TermsOfServiceServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService.RetrieveLatestTermsOfService", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.TermsOfServiceService", - "shortName": "TermsOfServiceService" - }, - "shortName": "RetrieveLatestTermsOfService" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.RetrieveLatestTermsOfServiceRequest" - }, - { - "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_accounts_v1beta.types.TermsOfService", - "shortName": "retrieve_latest_terms_of_service" - }, - "description": "Sample for RetrieveLatestTermsOfService", - "file": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_TermsOfServiceService_RetrieveLatestTermsOfService_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", - "shortName": "UserServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.create_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.CreateUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "CreateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateUserRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user", - "type": "google.shopping.merchant_accounts_v1beta.types.User" - }, - { - "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_accounts_v1beta.types.User", - "shortName": "create_user" - }, - "description": "Sample for CreateUser", - "file": "merchantapi_v1beta_generated_user_service_create_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_CreateUser_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_user_service_create_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", - "shortName": "UserServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.create_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.CreateUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "CreateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.CreateUserRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "user", - "type": "google.shopping.merchant_accounts_v1beta.types.User" - }, - { - "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_accounts_v1beta.types.User", - "shortName": "create_user" - }, - "description": "Sample for CreateUser", - "file": "merchantapi_v1beta_generated_user_service_create_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_CreateUser_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_user_service_create_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", - "shortName": "UserServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.delete_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.DeleteUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "DeleteUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest" - }, - { - "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_user" - }, - "description": "Sample for DeleteUser", - "file": "merchantapi_v1beta_generated_user_service_delete_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_DeleteUser_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_user_service_delete_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", - "shortName": "UserServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.delete_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.DeleteUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "DeleteUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.DeleteUserRequest" - }, - { - "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_user" - }, - "description": "Sample for DeleteUser", - "file": "merchantapi_v1beta_generated_user_service_delete_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_DeleteUser_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_user_service_delete_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", - "shortName": "UserServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.get_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.GetUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "GetUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetUserRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.User", - "shortName": "get_user" - }, - "description": "Sample for GetUser", - "file": "merchantapi_v1beta_generated_user_service_get_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_GetUser_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_user_service_get_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", - "shortName": "UserServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.get_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.GetUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "GetUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.GetUserRequest" - }, - { - "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]]]" - } - ], - "resultType": "google.shopping.merchant_accounts_v1beta.types.User", - "shortName": "get_user" - }, - "description": "Sample for GetUser", - "file": "merchantapi_v1beta_generated_user_service_get_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_GetUser_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_user_service_get_user_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", - "shortName": "UserServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.list_users", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.ListUsers", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "ListUsers" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListUsersRequest" - }, - { - "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_accounts_v1beta.services.user_service.pagers.ListUsersAsyncPager", - "shortName": "list_users" - }, - "description": "Sample for ListUsers", - "file": "merchantapi_v1beta_generated_user_service_list_users_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_ListUsers_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_user_service_list_users_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", - "shortName": "UserServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.list_users", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.ListUsers", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "ListUsers" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.ListUsersRequest" - }, - { - "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_accounts_v1beta.services.user_service.pagers.ListUsersPager", - "shortName": "list_users" - }, - "description": "Sample for ListUsers", - "file": "merchantapi_v1beta_generated_user_service_list_users_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_ListUsers_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_user_service_list_users_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient", - "shortName": "UserServiceAsyncClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceAsyncClient.update_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.UpdateUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "UpdateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest" - }, - { - "name": "user", - "type": "google.shopping.merchant_accounts_v1beta.types.User" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.User", - "shortName": "update_user" - }, - "description": "Sample for UpdateUser", - "file": "merchantapi_v1beta_generated_user_service_update_user_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_UpdateUser_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_user_service_update_user_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient", - "shortName": "UserServiceClient" - }, - "fullName": "google.shopping.merchant_accounts_v1beta.UserServiceClient.update_user", - "method": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService.UpdateUser", - "service": { - "fullName": "google.shopping.merchant.accounts.v1beta.UserService", - "shortName": "UserService" - }, - "shortName": "UpdateUser" - }, - "parameters": [ - { - "name": "request", - "type": "google.shopping.merchant_accounts_v1beta.types.UpdateUserRequest" - }, - { - "name": "user", - "type": "google.shopping.merchant_accounts_v1beta.types.User" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "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_accounts_v1beta.types.User", - "shortName": "update_user" - }, - "description": "Sample for UpdateUser", - "file": "merchantapi_v1beta_generated_user_service_update_user_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "merchantapi_v1beta_generated_UserService_UpdateUser_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "merchantapi_v1beta_generated_user_service_update_user_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py deleted file mode 100644 index 3f1eb8528ccc..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/scripts/fixup_merchant_accounts_v1beta_keywords.py +++ /dev/null @@ -1,238 +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_accountsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'accept_terms_of_service': ('name', 'account', 'region_code', ), - 'claim_homepage': ('name', ), - 'create_and_configure_account': ('account', 'service', 'users', 'accept_terms_of_service', ), - 'create_checkout_settings': ('parent', 'checkout_settings', ), - 'create_omnichannel_setting': ('parent', 'omnichannel_setting', ), - 'create_online_return_policy': ('parent', 'online_return_policy', ), - 'create_region': ('parent', 'region_id', 'region', ), - 'create_user': ('parent', 'user_id', 'user', ), - 'delete_account': ('name', 'force', ), - 'delete_checkout_settings': ('name', ), - 'delete_online_return_policy': ('name', ), - 'delete_region': ('name', ), - 'delete_user': ('name', ), - 'disable_program': ('name', ), - 'enable_program': ('name', ), - 'find_lfp_providers': ('parent', 'page_size', 'page_token', ), - 'get_account': ('name', ), - 'get_account_tax': ('name', ), - 'get_autofeed_settings': ('name', ), - 'get_automatic_improvements': ('name', ), - 'get_business_identity': ('name', ), - 'get_business_info': ('name', ), - 'get_checkout_settings': ('name', ), - 'get_email_preferences': ('name', ), - 'get_homepage': ('name', ), - 'get_omnichannel_setting': ('name', ), - 'get_online_return_policy': ('name', ), - 'get_program': ('name', ), - 'get_region': ('name', ), - 'get_shipping_settings': ('name', ), - 'get_terms_of_service': ('name', ), - 'get_terms_of_service_agreement_state': ('name', ), - 'get_user': ('name', ), - 'insert_shipping_settings': ('parent', 'shipping_setting', ), - 'link_gbp_account': ('parent', 'gbp_email', ), - 'link_lfp_provider': ('name', 'external_account_id', ), - 'list_account_issues': ('parent', 'page_size', 'page_token', 'language_code', 'time_zone', ), - 'list_accounts': ('page_size', 'page_token', 'filter', ), - 'list_account_tax': ('parent', 'page_size', 'page_token', ), - 'list_gbp_accounts': ('parent', 'page_size', 'page_token', ), - 'list_omnichannel_settings': ('parent', 'page_size', 'page_token', ), - 'list_online_return_policies': ('parent', 'page_size', 'page_token', ), - 'list_programs': ('parent', 'page_size', 'page_token', ), - 'list_regions': ('parent', 'page_size', 'page_token', ), - 'list_sub_accounts': ('provider', 'page_size', 'page_token', ), - 'list_users': ('parent', 'page_size', 'page_token', ), - 'request_inventory_verification': ('name', ), - 'retrieve_for_application_terms_of_service_agreement_state': ('parent', ), - 'retrieve_latest_terms_of_service': ('region_code', 'kind', ), - 'unclaim_homepage': ('name', ), - 'update_account': ('account', 'update_mask', ), - 'update_account_tax': ('account_tax', 'update_mask', ), - 'update_autofeed_settings': ('autofeed_settings', 'update_mask', ), - 'update_automatic_improvements': ('automatic_improvements', 'update_mask', ), - 'update_business_identity': ('business_identity', 'update_mask', ), - 'update_business_info': ('business_info', 'update_mask', ), - 'update_checkout_settings': ('checkout_settings', 'update_mask', ), - 'update_email_preferences': ('email_preferences', 'update_mask', ), - 'update_homepage': ('homepage', 'update_mask', ), - 'update_omnichannel_setting': ('omnichannel_setting', 'update_mask', ), - 'update_online_return_policy': ('online_return_policy', 'update_mask', ), - 'update_region': ('region', 'update_mask', ), - 'update_user': ('user', 'update_mask', ), - } - - 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_accountsCallTransformer(), -): - """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_accounts 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-accounts/v1beta/setup.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/setup.py deleted file mode 100644 index 9c31c0f0922e..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts' - - -description = "Google Shopping Merchant Accounts API client library" - -version = None - -with open(os.path.join(package_root, 'google/shopping/merchant_accounts/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-accounts" - -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-accounts/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.13.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.13.txt deleted file mode 100644 index 0112695e5bbb..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 2af887ec8ba0..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index 4cae520d02b2..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/__init__.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py deleted file mode 100644 index b7516e226838..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_issue_service.py +++ /dev/null @@ -1,2418 +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.shopping.merchant_accounts_v1beta.services.account_issue_service import AccountIssueServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.account_issue_service import AccountIssueServiceClient -from google.shopping.merchant_accounts_v1beta.services.account_issue_service import pagers -from google.shopping.merchant_accounts_v1beta.services.account_issue_service import transports -from google.shopping.merchant_accounts_v1beta.types import accountissue -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 AccountIssueServiceClient._get_default_mtls_endpoint(None) is None - assert AccountIssueServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountIssueServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AccountIssueServiceClient._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 AccountIssueServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountIssueServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AccountIssueServiceClient._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 AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, False) is None - assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AccountIssueServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountIssueServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AccountIssueServiceClient._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 AccountIssueServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountIssueServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountIssueServiceClient._get_universe_domain(None, None) == AccountIssueServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AccountIssueServiceClient._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 = AccountIssueServiceClient(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 = AccountIssueServiceClient(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", [ - (AccountIssueServiceClient, "grpc"), - (AccountIssueServiceAsyncClient, "grpc_asyncio"), - (AccountIssueServiceClient, "rest"), -]) -def test_account_issue_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.AccountIssueServiceGrpcTransport, "grpc"), - (transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountIssueServiceRestTransport, "rest"), -]) -def test_account_issue_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", [ - (AccountIssueServiceClient, "grpc"), - (AccountIssueServiceAsyncClient, "grpc_asyncio"), - (AccountIssueServiceClient, "rest"), -]) -def test_account_issue_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_account_issue_service_client_get_transport_class(): - transport = AccountIssueServiceClient.get_transport_class() - available_transports = [ - transports.AccountIssueServiceGrpcTransport, - transports.AccountIssueServiceRestTransport, - ] - assert transport in available_transports - - transport = AccountIssueServiceClient.get_transport_class("grpc") - assert transport == transports.AccountIssueServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) -def test_account_issue_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(AccountIssueServiceClient, '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(AccountIssueServiceClient, '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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "true"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "false"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "true"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_account_issue_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", [ - AccountIssueServiceClient, AccountIssueServiceAsyncClient -]) -@mock.patch.object(AccountIssueServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceAsyncClient)) -def test_account_issue_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", [ - AccountIssueServiceClient, AccountIssueServiceAsyncClient -]) -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) -def test_account_issue_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AccountIssueServiceClient._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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), -]) -def test_account_issue_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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", None), -]) -def test_account_issue_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_account_issue_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AccountIssueServiceClient( - 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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_account_issue_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", [ - accountissue.ListAccountIssuesRequest, - dict, -]) -def test_list_account_issues(request_type, transport: str = 'grpc'): - client = AccountIssueServiceClient( - 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_account_issues), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_account_issues(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accountissue.ListAccountIssuesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountIssuesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_account_issues_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 = AccountIssueServiceClient( - 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 = accountissue.ListAccountIssuesRequest( - parent='parent_value', - page_token='page_token_value', - language_code='language_code_value', - time_zone='time_zone_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_account_issues(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accountissue.ListAccountIssuesRequest( - parent='parent_value', - page_token='page_token_value', - language_code='language_code_value', - time_zone='time_zone_value', - ) - -def test_list_account_issues_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 = AccountIssueServiceClient( - 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_account_issues in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_account_issues] = mock_rpc - request = {} - client.list_account_issues(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_account_issues(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_account_issues_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 = AccountIssueServiceAsyncClient( - 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_account_issues 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_account_issues] = mock_rpc - - request = {} - await client.list_account_issues(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_account_issues(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_account_issues_async(transport: str = 'grpc_asyncio', request_type=accountissue.ListAccountIssuesRequest): - client = AccountIssueServiceAsyncClient( - 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_account_issues), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_account_issues(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accountissue.ListAccountIssuesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountIssuesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_account_issues_async_from_dict(): - await test_list_account_issues_async(request_type=dict) - -def test_list_account_issues_field_headers(): - client = AccountIssueServiceClient( - 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 = accountissue.ListAccountIssuesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - call.return_value = accountissue.ListAccountIssuesResponse() - client.list_account_issues(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_account_issues_field_headers_async(): - client = AccountIssueServiceAsyncClient( - 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 = accountissue.ListAccountIssuesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) - await client.list_account_issues(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_account_issues_flattened(): - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accountissue.ListAccountIssuesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_account_issues( - 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_account_issues_flattened_error(): - client = AccountIssueServiceClient( - 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_account_issues( - accountissue.ListAccountIssuesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_account_issues_flattened_async(): - client = AccountIssueServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accountissue.ListAccountIssuesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_account_issues( - 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_account_issues_flattened_error_async(): - client = AccountIssueServiceAsyncClient( - 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_account_issues( - accountissue.ListAccountIssuesRequest(), - parent='parent_value', - ) - - -def test_list_account_issues_pager(transport_name: str = "grpc"): - client = AccountIssueServiceClient( - 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_account_issues), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - next_page_token='abc', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[], - next_page_token='def', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - ], - next_page_token='ghi', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_account_issues(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, accountissue.AccountIssue) - for i in results) -def test_list_account_issues_pages(transport_name: str = "grpc"): - client = AccountIssueServiceClient( - 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_account_issues), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - next_page_token='abc', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[], - next_page_token='def', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - ], - next_page_token='ghi', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - ), - RuntimeError, - ) - pages = list(client.list_account_issues(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_account_issues_async_pager(): - client = AccountIssueServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - next_page_token='abc', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[], - next_page_token='def', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - ], - next_page_token='ghi', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_account_issues(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, accountissue.AccountIssue) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_account_issues_async_pages(): - client = AccountIssueServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - next_page_token='abc', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[], - next_page_token='def', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - ], - next_page_token='ghi', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - ), - 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_account_issues(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_account_issues_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 = AccountIssueServiceClient( - 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_account_issues in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_account_issues] = mock_rpc - - request = {} - client.list_account_issues(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_account_issues(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_account_issues_rest_required_fields(request_type=accountissue.ListAccountIssuesRequest): - transport_class = transports.AccountIssueServiceRestTransport - - 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_account_issues._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_account_issues._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "page_size", "page_token", "time_zone", )) - 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 = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = accountissue.ListAccountIssuesResponse() - # 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 = accountissue.ListAccountIssuesResponse.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_account_issues(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_account_issues_rest_unset_required_fields(): - transport = transports.AccountIssueServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_account_issues._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "pageSize", "pageToken", "timeZone", )) & set(("parent", ))) - - -def test_list_account_issues_rest_flattened(): - client = AccountIssueServiceClient( - 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 = accountissue.ListAccountIssuesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = accountissue.ListAccountIssuesResponse.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_account_issues(**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/accounts/v1beta/{parent=accounts/*}/issues" % client.transport._host, args[1]) - - -def test_list_account_issues_rest_flattened_error(transport: str = 'rest'): - client = AccountIssueServiceClient( - 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_account_issues( - accountissue.ListAccountIssuesRequest(), - parent='parent_value', - ) - - -def test_list_account_issues_rest_pager(transport: str = 'rest'): - client = AccountIssueServiceClient( - 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 = ( - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - next_page_token='abc', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[], - next_page_token='def', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - ], - next_page_token='ghi', - ), - accountissue.ListAccountIssuesResponse( - account_issues=[ - accountissue.AccountIssue(), - accountissue.AccountIssue(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(accountissue.ListAccountIssuesResponse.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'} - - pager = client.list_account_issues(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, accountissue.AccountIssue) - for i in results) - - pages = list(client.list_account_issues(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AccountIssueServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AccountIssueServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountIssueServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AccountIssueServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AccountIssueServiceClient( - 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 = AccountIssueServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AccountIssueServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountIssueServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AccountIssueServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AccountIssueServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AccountIssueServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AccountIssueServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AccountIssueServiceGrpcTransport, - transports.AccountIssueServiceGrpcAsyncIOTransport, - transports.AccountIssueServiceRestTransport, -]) -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 = AccountIssueServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AccountIssueServiceClient( - 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_account_issues_empty_call_grpc(): - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - call.return_value = accountissue.ListAccountIssuesResponse() - client.list_account_issues(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accountissue.ListAccountIssuesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AccountIssueServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AccountIssueServiceAsyncClient( - 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_account_issues_empty_call_grpc_asyncio(): - client = AccountIssueServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', - )) - await client.list_account_issues(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accountissue.ListAccountIssuesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AccountIssueServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_account_issues_rest_bad_request(request_type=accountissue.ListAccountIssuesRequest): - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_account_issues(request) - - -@pytest.mark.parametrize("request_type", [ - accountissue.ListAccountIssuesRequest, - dict, -]) -def test_list_account_issues_rest_call_success(request_type): - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = accountissue.ListAccountIssuesResponse( - 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 = accountissue.ListAccountIssuesResponse.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_account_issues(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountIssuesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_account_issues_rest_interceptors(null_interceptor): - transport = transports.AccountIssueServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountIssueServiceRestInterceptor(), - ) - client = AccountIssueServiceClient(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.AccountIssueServiceRestInterceptor, "post_list_account_issues") as post, \ - mock.patch.object(transports.AccountIssueServiceRestInterceptor, "post_list_account_issues_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountIssueServiceRestInterceptor, "pre_list_account_issues") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = accountissue.ListAccountIssuesRequest.pb(accountissue.ListAccountIssuesRequest()) - 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 = accountissue.ListAccountIssuesResponse.to_json(accountissue.ListAccountIssuesResponse()) - req.return_value.content = return_value - - request = accountissue.ListAccountIssuesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = accountissue.ListAccountIssuesResponse() - post_with_metadata.return_value = accountissue.ListAccountIssuesResponse(), metadata - - client.list_account_issues(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = AccountIssueServiceClient( - 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_account_issues_empty_call_rest(): - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - client.list_account_issues(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accountissue.ListAccountIssuesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AccountIssueServiceGrpcTransport, - ) - -def test_account_issue_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AccountIssueServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_account_issue_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AccountIssueServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_account_issues', - ) - 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_account_issue_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_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AccountIssueServiceTransport( - 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_account_issue_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_accounts_v1beta.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AccountIssueServiceTransport() - adc.assert_called_once() - - -def test_account_issue_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) - AccountIssueServiceClient() - 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.AccountIssueServiceGrpcTransport, - transports.AccountIssueServiceGrpcAsyncIOTransport, - ], -) -def test_account_issue_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.AccountIssueServiceGrpcTransport, - transports.AccountIssueServiceGrpcAsyncIOTransport, - transports.AccountIssueServiceRestTransport, - ], -) -def test_account_issue_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.AccountIssueServiceGrpcTransport, grpc_helpers), - (transports.AccountIssueServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) -def test_account_issue_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_account_issue_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.AccountIssueServiceRestTransport ( - 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_account_issue_service_host_no_port(transport_name): - client = AccountIssueServiceClient( - 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_account_issue_service_host_with_port(transport_name): - client = AccountIssueServiceClient( - 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_account_issue_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AccountIssueServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AccountIssueServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_account_issues._session - session2 = client2.transport.list_account_issues._session - assert session1 != session2 -def test_account_issue_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AccountIssueServiceGrpcTransport( - 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_account_issue_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AccountIssueServiceGrpcAsyncIOTransport( - 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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) -def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) -def test_account_issue_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = AccountIssueServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = AccountIssueServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.parse_account_path(path) - assert expected == actual - -def test_account_issue_path(): - account = "whelk" - issue = "octopus" - expected = "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) - actual = AccountIssueServiceClient.account_issue_path(account, issue) - assert expected == actual - - -def test_parse_account_issue_path(): - expected = { - "account": "oyster", - "issue": "nudibranch", - } - path = AccountIssueServiceClient.account_issue_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.parse_account_issue_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AccountIssueServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = AccountIssueServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = AccountIssueServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = AccountIssueServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AccountIssueServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = AccountIssueServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = AccountIssueServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = AccountIssueServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = AccountIssueServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AccountIssueServiceClient.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.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: - client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AccountIssueServiceClient.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 = AccountIssueServiceClient( - 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 = AccountIssueServiceAsyncClient( - 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 = AccountIssueServiceClient( - 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 = AccountIssueServiceClient( - 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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py deleted file mode 100644 index 2cbf312aa0d8..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_account_tax_service.py +++ /dev/null @@ -1,3803 +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 field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.account_tax_service import AccountTaxServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.account_tax_service import AccountTaxServiceClient -from google.shopping.merchant_accounts_v1beta.services.account_tax_service import pagers -from google.shopping.merchant_accounts_v1beta.services.account_tax_service import transports -from google.shopping.merchant_accounts_v1beta.types import account_tax -from google.shopping.merchant_accounts_v1beta.types import account_tax as gsma_account_tax -from google.shopping.merchant_accounts_v1beta.types import tax_rule -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 AccountTaxServiceClient._get_default_mtls_endpoint(None) is None - assert AccountTaxServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountTaxServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountTaxServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountTaxServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountTaxServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AccountTaxServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountTaxServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountTaxServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AccountTaxServiceClient._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 AccountTaxServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountTaxServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountTaxServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AccountTaxServiceClient._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 AccountTaxServiceClient._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 AccountTaxServiceClient._get_client_cert_source(None, False) is None - assert AccountTaxServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountTaxServiceClient._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 AccountTaxServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountTaxServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) -@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AccountTaxServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AccountTaxServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountTaxServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountTaxServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountTaxServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountTaxServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountTaxServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountTaxServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountTaxServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AccountTaxServiceClient._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 AccountTaxServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountTaxServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountTaxServiceClient._get_universe_domain(None, None) == AccountTaxServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AccountTaxServiceClient._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 = AccountTaxServiceClient(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 = AccountTaxServiceClient(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", [ - (AccountTaxServiceClient, "grpc"), - (AccountTaxServiceAsyncClient, "grpc_asyncio"), - (AccountTaxServiceClient, "rest"), -]) -def test_account_tax_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.AccountTaxServiceGrpcTransport, "grpc"), - (transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountTaxServiceRestTransport, "rest"), -]) -def test_account_tax_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", [ - (AccountTaxServiceClient, "grpc"), - (AccountTaxServiceAsyncClient, "grpc_asyncio"), - (AccountTaxServiceClient, "rest"), -]) -def test_account_tax_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_account_tax_service_client_get_transport_class(): - transport = AccountTaxServiceClient.get_transport_class() - available_transports = [ - transports.AccountTaxServiceGrpcTransport, - transports.AccountTaxServiceRestTransport, - ] - assert transport in available_transports - - transport = AccountTaxServiceClient.get_transport_class("grpc") - assert transport == transports.AccountTaxServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc"), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) -@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) -def test_account_tax_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(AccountTaxServiceClient, '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(AccountTaxServiceClient, '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", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", "true"), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", "false"), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest", "true"), - (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) -@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_account_tax_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", [ - AccountTaxServiceClient, AccountTaxServiceAsyncClient -]) -@mock.patch.object(AccountTaxServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountTaxServiceClient)) -@mock.patch.object(AccountTaxServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountTaxServiceAsyncClient)) -def test_account_tax_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", [ - AccountTaxServiceClient, AccountTaxServiceAsyncClient -]) -@mock.patch.object(AccountTaxServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceClient)) -@mock.patch.object(AccountTaxServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountTaxServiceAsyncClient)) -def test_account_tax_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AccountTaxServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountTaxServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AccountTaxServiceClient._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", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc"), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest"), -]) -def test_account_tax_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", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", grpc_helpers), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountTaxServiceClient, transports.AccountTaxServiceRestTransport, "rest", None), -]) -def test_account_tax_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_account_tax_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AccountTaxServiceClient( - 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", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport, "grpc", grpc_helpers), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_account_tax_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", [ - account_tax.GetAccountTaxRequest, - dict, -]) -def test_get_account_tax(request_type, transport: str = 'grpc'): - client = AccountTaxServiceClient( - 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.get_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = account_tax.AccountTax( - name='name_value', - account=749, - ) - response = client.get_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = account_tax.GetAccountTaxRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, account_tax.AccountTax) - assert response.name == 'name_value' - assert response.account == 749 - - -def test_get_account_tax_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 = AccountTaxServiceClient( - 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 = account_tax.GetAccountTaxRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_account_tax(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == account_tax.GetAccountTaxRequest( - name='name_value', - ) - -def test_get_account_tax_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 = AccountTaxServiceClient( - 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.get_account_tax in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account_tax] = mock_rpc - request = {} - client.get_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_account_tax(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_get_account_tax_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 = AccountTaxServiceAsyncClient( - 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.get_account_tax in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_account_tax] = mock_rpc - - request = {} - await client.get_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_account_tax(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_get_account_tax_async(transport: str = 'grpc_asyncio', request_type=account_tax.GetAccountTaxRequest): - client = AccountTaxServiceAsyncClient( - 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.get_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax( - name='name_value', - account=749, - )) - response = await client.get_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = account_tax.GetAccountTaxRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, account_tax.AccountTax) - assert response.name == 'name_value' - assert response.account == 749 - - -@pytest.mark.asyncio -async def test_get_account_tax_async_from_dict(): - await test_get_account_tax_async(request_type=dict) - -def test_get_account_tax_field_headers(): - client = AccountTaxServiceClient( - 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 = account_tax.GetAccountTaxRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - call.return_value = account_tax.AccountTax() - client.get_account_tax(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_get_account_tax_field_headers_async(): - client = AccountTaxServiceAsyncClient( - 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 = account_tax.GetAccountTaxRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax()) - await client.get_account_tax(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_get_account_tax_flattened(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = account_tax.AccountTax() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_account_tax( - 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_get_account_tax_flattened_error(): - client = AccountTaxServiceClient( - 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.get_account_tax( - account_tax.GetAccountTaxRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_account_tax_flattened_async(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = account_tax.AccountTax() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_account_tax( - 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_get_account_tax_flattened_error_async(): - client = AccountTaxServiceAsyncClient( - 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.get_account_tax( - account_tax.GetAccountTaxRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - account_tax.ListAccountTaxRequest, - dict, -]) -def test_list_account_tax(request_type, transport: str = 'grpc'): - client = AccountTaxServiceClient( - 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_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = account_tax.ListAccountTaxResponse( - next_page_token='next_page_token_value', - ) - response = client.list_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = account_tax.ListAccountTaxRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountTaxPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_account_tax_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 = AccountTaxServiceClient( - 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 = account_tax.ListAccountTaxRequest( - 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_account_tax), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_account_tax(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == account_tax.ListAccountTaxRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_account_tax_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 = AccountTaxServiceClient( - 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_account_tax in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_account_tax] = mock_rpc - request = {} - client.list_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_account_tax(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_account_tax_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 = AccountTaxServiceAsyncClient( - 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_account_tax 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_account_tax] = mock_rpc - - request = {} - await client.list_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_account_tax(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_account_tax_async(transport: str = 'grpc_asyncio', request_type=account_tax.ListAccountTaxRequest): - client = AccountTaxServiceAsyncClient( - 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_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = account_tax.ListAccountTaxRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountTaxAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_account_tax_async_from_dict(): - await test_list_account_tax_async(request_type=dict) - -def test_list_account_tax_field_headers(): - client = AccountTaxServiceClient( - 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 = account_tax.ListAccountTaxRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - call.return_value = account_tax.ListAccountTaxResponse() - client.list_account_tax(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_account_tax_field_headers_async(): - client = AccountTaxServiceAsyncClient( - 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 = account_tax.ListAccountTaxRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse()) - await client.list_account_tax(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_account_tax_flattened(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = account_tax.ListAccountTaxResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_account_tax( - 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_account_tax_flattened_error(): - client = AccountTaxServiceClient( - 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_account_tax( - account_tax.ListAccountTaxRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_account_tax_flattened_async(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = account_tax.ListAccountTaxResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_account_tax( - 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_account_tax_flattened_error_async(): - client = AccountTaxServiceAsyncClient( - 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_account_tax( - account_tax.ListAccountTaxRequest(), - parent='parent_value', - ) - - -def test_list_account_tax_pager(transport_name: str = "grpc"): - client = AccountTaxServiceClient( - 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_account_tax), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - next_page_token='abc', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[], - next_page_token='def', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - ], - next_page_token='ghi', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_account_tax(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, account_tax.AccountTax) - for i in results) -def test_list_account_tax_pages(transport_name: str = "grpc"): - client = AccountTaxServiceClient( - 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_account_tax), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - next_page_token='abc', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[], - next_page_token='def', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - ], - next_page_token='ghi', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - ), - RuntimeError, - ) - pages = list(client.list_account_tax(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_account_tax_async_pager(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - next_page_token='abc', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[], - next_page_token='def', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - ], - next_page_token='ghi', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_account_tax(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, account_tax.AccountTax) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_account_tax_async_pages(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - next_page_token='abc', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[], - next_page_token='def', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - ], - next_page_token='ghi', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - ), - 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_account_tax(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", [ - gsma_account_tax.UpdateAccountTaxRequest, - dict, -]) -def test_update_account_tax(request_type, transport: str = 'grpc'): - client = AccountTaxServiceClient( - 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.update_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_account_tax.AccountTax( - name='name_value', - account=749, - ) - response = client.update_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gsma_account_tax.UpdateAccountTaxRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_account_tax.AccountTax) - assert response.name == 'name_value' - assert response.account == 749 - - -def test_update_account_tax_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 = AccountTaxServiceClient( - 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 = gsma_account_tax.UpdateAccountTaxRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_account_tax(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gsma_account_tax.UpdateAccountTaxRequest( - ) - -def test_update_account_tax_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 = AccountTaxServiceClient( - 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.update_account_tax in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_account_tax] = mock_rpc - request = {} - client.update_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_account_tax(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_update_account_tax_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 = AccountTaxServiceAsyncClient( - 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.update_account_tax in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_account_tax] = mock_rpc - - request = {} - await client.update_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_account_tax(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_update_account_tax_async(transport: str = 'grpc_asyncio', request_type=gsma_account_tax.UpdateAccountTaxRequest): - client = AccountTaxServiceAsyncClient( - 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.update_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax( - name='name_value', - account=749, - )) - response = await client.update_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gsma_account_tax.UpdateAccountTaxRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_account_tax.AccountTax) - assert response.name == 'name_value' - assert response.account == 749 - - -@pytest.mark.asyncio -async def test_update_account_tax_async_from_dict(): - await test_update_account_tax_async(request_type=dict) - -def test_update_account_tax_field_headers(): - client = AccountTaxServiceClient( - 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 = gsma_account_tax.UpdateAccountTaxRequest() - - request.account_tax.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - call.return_value = gsma_account_tax.AccountTax() - client.update_account_tax(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', - 'account_tax.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_account_tax_field_headers_async(): - client = AccountTaxServiceAsyncClient( - 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 = gsma_account_tax.UpdateAccountTaxRequest() - - request.account_tax.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax()) - await client.update_account_tax(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', - 'account_tax.name=name_value', - ) in kw['metadata'] - - -def test_update_account_tax_flattened(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_account_tax.AccountTax() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_account_tax( - account_tax=gsma_account_tax.AccountTax(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account_tax - mock_val = gsma_account_tax.AccountTax(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_account_tax_flattened_error(): - client = AccountTaxServiceClient( - 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.update_account_tax( - gsma_account_tax.UpdateAccountTaxRequest(), - account_tax=gsma_account_tax.AccountTax(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_account_tax_flattened_async(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_account_tax.AccountTax() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_account_tax( - account_tax=gsma_account_tax.AccountTax(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account_tax - mock_val = gsma_account_tax.AccountTax(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_account_tax_flattened_error_async(): - client = AccountTaxServiceAsyncClient( - 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.update_account_tax( - gsma_account_tax.UpdateAccountTaxRequest(), - account_tax=gsma_account_tax.AccountTax(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_account_tax_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 = AccountTaxServiceClient( - 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.get_account_tax in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account_tax] = mock_rpc - - request = {} - client.get_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_account_tax(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_get_account_tax_rest_required_fields(request_type=account_tax.GetAccountTaxRequest): - transport_class = transports.AccountTaxServiceRestTransport - - 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()).get_account_tax._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_tax._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 = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = account_tax.AccountTax() - # 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 = account_tax.AccountTax.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.get_account_tax(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_account_tax_rest_unset_required_fields(): - transport = transports.AccountTaxServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_account_tax._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_account_tax_rest_flattened(): - client = AccountTaxServiceClient( - 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 = account_tax.AccountTax() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/accounttax/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = account_tax.AccountTax.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.get_account_tax(**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/accounts/v1beta/{name=accounts/*/accounttax/*}" % client.transport._host, args[1]) - - -def test_get_account_tax_rest_flattened_error(transport: str = 'rest'): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_account_tax( - account_tax.GetAccountTaxRequest(), - name='name_value', - ) - - -def test_list_account_tax_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 = AccountTaxServiceClient( - 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_account_tax in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_account_tax] = mock_rpc - - request = {} - client.list_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_account_tax(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_account_tax_rest_required_fields(request_type=account_tax.ListAccountTaxRequest): - transport_class = transports.AccountTaxServiceRestTransport - - 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_account_tax._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_account_tax._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 = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = account_tax.ListAccountTaxResponse() - # 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 = account_tax.ListAccountTaxResponse.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_account_tax(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_account_tax_rest_unset_required_fields(): - transport = transports.AccountTaxServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_account_tax._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_account_tax_rest_flattened(): - client = AccountTaxServiceClient( - 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 = account_tax.ListAccountTaxResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = account_tax.ListAccountTaxResponse.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_account_tax(**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/accounts/v1beta/{parent=accounts/*}/accounttax" % client.transport._host, args[1]) - - -def test_list_account_tax_rest_flattened_error(transport: str = 'rest'): - client = AccountTaxServiceClient( - 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_account_tax( - account_tax.ListAccountTaxRequest(), - parent='parent_value', - ) - - -def test_list_account_tax_rest_pager(transport: str = 'rest'): - client = AccountTaxServiceClient( - 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 = ( - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - next_page_token='abc', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[], - next_page_token='def', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - ], - next_page_token='ghi', - ), - account_tax.ListAccountTaxResponse( - account_taxes=[ - account_tax.AccountTax(), - account_tax.AccountTax(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(account_tax.ListAccountTaxResponse.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'} - - pager = client.list_account_tax(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, account_tax.AccountTax) - for i in results) - - pages = list(client.list_account_tax(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_update_account_tax_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 = AccountTaxServiceClient( - 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.update_account_tax in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_account_tax] = mock_rpc - - request = {} - client.update_account_tax(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_account_tax(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_update_account_tax_rest_required_fields(request_type=gsma_account_tax.UpdateAccountTaxRequest): - transport_class = transports.AccountTaxServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_tax._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_tax._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gsma_account_tax.AccountTax() - # 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': "patch", - '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 = gsma_account_tax.AccountTax.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.update_account_tax(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_account_tax_rest_unset_required_fields(): - transport = transports.AccountTaxServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_account_tax._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("accountTax", ))) - - -def test_update_account_tax_rest_flattened(): - client = AccountTaxServiceClient( - 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 = gsma_account_tax.AccountTax() - - # get arguments that satisfy an http rule for this method - sample_request = {'account_tax': {'name': 'accounts/sample1/accounttax/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - account_tax=gsma_account_tax.AccountTax(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_account_tax.AccountTax.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.update_account_tax(**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/accounts/v1beta/{account_tax.name=accounts/*/accounttax/*}" % client.transport._host, args[1]) - - -def test_update_account_tax_rest_flattened_error(transport: str = 'rest'): - client = AccountTaxServiceClient( - 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.update_account_tax( - gsma_account_tax.UpdateAccountTaxRequest(), - account_tax=gsma_account_tax.AccountTax(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AccountTaxServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AccountTaxServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountTaxServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AccountTaxServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AccountTaxServiceClient( - 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 = AccountTaxServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AccountTaxServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountTaxServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AccountTaxServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AccountTaxServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AccountTaxServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AccountTaxServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AccountTaxServiceGrpcTransport, - transports.AccountTaxServiceGrpcAsyncIOTransport, - transports.AccountTaxServiceRestTransport, -]) -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 = AccountTaxServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AccountTaxServiceClient( - 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_get_account_tax_empty_call_grpc(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - call.return_value = account_tax.AccountTax() - client.get_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = account_tax.GetAccountTaxRequest() - - 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_list_account_tax_empty_call_grpc(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - call.return_value = account_tax.ListAccountTaxResponse() - client.list_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = account_tax.ListAccountTaxRequest() - - 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_update_account_tax_empty_call_grpc(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - call.return_value = gsma_account_tax.AccountTax() - client.update_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_account_tax.UpdateAccountTaxRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AccountTaxServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AccountTaxServiceAsyncClient( - 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_get_account_tax_empty_call_grpc_asyncio(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.AccountTax( - name='name_value', - account=749, - )) - await client.get_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = account_tax.GetAccountTaxRequest() - - 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_list_account_tax_empty_call_grpc_asyncio(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(account_tax.ListAccountTaxResponse( - next_page_token='next_page_token_value', - )) - await client.list_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = account_tax.ListAccountTaxRequest() - - 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_update_account_tax_empty_call_grpc_asyncio(): - client = AccountTaxServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_account_tax.AccountTax( - name='name_value', - account=749, - )) - await client.update_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_account_tax.UpdateAccountTaxRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AccountTaxServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_account_tax_rest_bad_request(request_type=account_tax.GetAccountTaxRequest): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/accounttax/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.get_account_tax(request) - - -@pytest.mark.parametrize("request_type", [ - account_tax.GetAccountTaxRequest, - dict, -]) -def test_get_account_tax_rest_call_success(request_type): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/accounttax/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 = account_tax.AccountTax( - name='name_value', - account=749, - ) - - # 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 = account_tax.AccountTax.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.get_account_tax(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, account_tax.AccountTax) - assert response.name == 'name_value' - assert response.account == 749 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_account_tax_rest_interceptors(null_interceptor): - transport = transports.AccountTaxServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountTaxServiceRestInterceptor(), - ) - client = AccountTaxServiceClient(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.AccountTaxServiceRestInterceptor, "post_get_account_tax") as post, \ - mock.patch.object(transports.AccountTaxServiceRestInterceptor, "post_get_account_tax_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountTaxServiceRestInterceptor, "pre_get_account_tax") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = account_tax.GetAccountTaxRequest.pb(account_tax.GetAccountTaxRequest()) - 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 = account_tax.AccountTax.to_json(account_tax.AccountTax()) - req.return_value.content = return_value - - request = account_tax.GetAccountTaxRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = account_tax.AccountTax() - post_with_metadata.return_value = account_tax.AccountTax(), metadata - - client.get_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_account_tax_rest_bad_request(request_type=account_tax.ListAccountTaxRequest): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_account_tax(request) - - -@pytest.mark.parametrize("request_type", [ - account_tax.ListAccountTaxRequest, - dict, -]) -def test_list_account_tax_rest_call_success(request_type): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = account_tax.ListAccountTaxResponse( - 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 = account_tax.ListAccountTaxResponse.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_account_tax(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountTaxPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_account_tax_rest_interceptors(null_interceptor): - transport = transports.AccountTaxServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountTaxServiceRestInterceptor(), - ) - client = AccountTaxServiceClient(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.AccountTaxServiceRestInterceptor, "post_list_account_tax") as post, \ - mock.patch.object(transports.AccountTaxServiceRestInterceptor, "post_list_account_tax_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountTaxServiceRestInterceptor, "pre_list_account_tax") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = account_tax.ListAccountTaxRequest.pb(account_tax.ListAccountTaxRequest()) - 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 = account_tax.ListAccountTaxResponse.to_json(account_tax.ListAccountTaxResponse()) - req.return_value.content = return_value - - request = account_tax.ListAccountTaxRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = account_tax.ListAccountTaxResponse() - post_with_metadata.return_value = account_tax.ListAccountTaxResponse(), metadata - - client.list_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_account_tax_rest_bad_request(request_type=gsma_account_tax.UpdateAccountTaxRequest): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'account_tax': {'name': 'accounts/sample1/accounttax/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.update_account_tax(request) - - -@pytest.mark.parametrize("request_type", [ - gsma_account_tax.UpdateAccountTaxRequest, - dict, -]) -def test_update_account_tax_rest_call_success(request_type): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'account_tax': {'name': 'accounts/sample1/accounttax/sample2'}} - request_init["account_tax"] = {'name': 'accounts/sample1/accounttax/sample2', 'account': 749, 'tax_rules': [{'location_id': 1157, 'post_code_range': {'start': 'start_value', 'end': 'end_value'}, 'use_google_rate': True, 'self_specified_rate_micros': 2732, 'region_code': 'region_code_value', 'shipping_taxed': True, 'effective_time_period': {'start_time': {'seconds': 751, 'nanos': 543}, 'end_time': {}}}]} - # 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 = gsma_account_tax.UpdateAccountTaxRequest.meta.fields["account_tax"] - - 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["account_tax"].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["account_tax"][field])): - del request_init["account_tax"][field][i][subfield] - else: - del request_init["account_tax"][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 = gsma_account_tax.AccountTax( - name='name_value', - account=749, - ) - - # 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 = gsma_account_tax.AccountTax.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.update_account_tax(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_account_tax.AccountTax) - assert response.name == 'name_value' - assert response.account == 749 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_account_tax_rest_interceptors(null_interceptor): - transport = transports.AccountTaxServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountTaxServiceRestInterceptor(), - ) - client = AccountTaxServiceClient(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.AccountTaxServiceRestInterceptor, "post_update_account_tax") as post, \ - mock.patch.object(transports.AccountTaxServiceRestInterceptor, "post_update_account_tax_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountTaxServiceRestInterceptor, "pre_update_account_tax") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gsma_account_tax.UpdateAccountTaxRequest.pb(gsma_account_tax.UpdateAccountTaxRequest()) - 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 = gsma_account_tax.AccountTax.to_json(gsma_account_tax.AccountTax()) - req.return_value.content = return_value - - request = gsma_account_tax.UpdateAccountTaxRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gsma_account_tax.AccountTax() - post_with_metadata.return_value = gsma_account_tax.AccountTax(), metadata - - client.update_account_tax(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = AccountTaxServiceClient( - 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_get_account_tax_empty_call_rest(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account_tax), - '__call__') as call: - client.get_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = account_tax.GetAccountTaxRequest() - - 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_list_account_tax_empty_call_rest(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_tax), - '__call__') as call: - client.list_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = account_tax.ListAccountTaxRequest() - - 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_update_account_tax_empty_call_rest(): - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account_tax), - '__call__') as call: - client.update_account_tax(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_account_tax.UpdateAccountTaxRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AccountTaxServiceGrpcTransport, - ) - -def test_account_tax_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AccountTaxServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_account_tax_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AccountTaxServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_account_tax', - 'list_account_tax', - 'update_account_tax', - ) - 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_account_tax_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_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AccountTaxServiceTransport( - 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_account_tax_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_accounts_v1beta.services.account_tax_service.transports.AccountTaxServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AccountTaxServiceTransport() - adc.assert_called_once() - - -def test_account_tax_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) - AccountTaxServiceClient() - 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.AccountTaxServiceGrpcTransport, - transports.AccountTaxServiceGrpcAsyncIOTransport, - ], -) -def test_account_tax_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.AccountTaxServiceGrpcTransport, - transports.AccountTaxServiceGrpcAsyncIOTransport, - transports.AccountTaxServiceRestTransport, - ], -) -def test_account_tax_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.AccountTaxServiceGrpcTransport, grpc_helpers), - (transports.AccountTaxServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_account_tax_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.AccountTaxServiceGrpcTransport, transports.AccountTaxServiceGrpcAsyncIOTransport]) -def test_account_tax_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_account_tax_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.AccountTaxServiceRestTransport ( - 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_account_tax_service_host_no_port(transport_name): - client = AccountTaxServiceClient( - 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_account_tax_service_host_with_port(transport_name): - client = AccountTaxServiceClient( - 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_account_tax_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AccountTaxServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AccountTaxServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_account_tax._session - session2 = client2.transport.get_account_tax._session - assert session1 != session2 - session1 = client1.transport.list_account_tax._session - session2 = client2.transport.list_account_tax._session - assert session1 != session2 - session1 = client1.transport.update_account_tax._session - session2 = client2.transport.update_account_tax._session - assert session1 != session2 -def test_account_tax_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AccountTaxServiceGrpcTransport( - 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_account_tax_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AccountTaxServiceGrpcAsyncIOTransport( - 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.AccountTaxServiceGrpcTransport, transports.AccountTaxServiceGrpcAsyncIOTransport]) -def test_account_tax_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.AccountTaxServiceGrpcTransport, transports.AccountTaxServiceGrpcAsyncIOTransport]) -def test_account_tax_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_account_tax_path(): - account = "squid" - tax = "clam" - expected = "accounts/{account}/accounttax/{tax}".format(account=account, tax=tax, ) - actual = AccountTaxServiceClient.account_tax_path(account, tax) - assert expected == actual - - -def test_parse_account_tax_path(): - expected = { - "account": "whelk", - "tax": "octopus", - } - path = AccountTaxServiceClient.account_tax_path(**expected) - - # Check that the path construction is reversible. - actual = AccountTaxServiceClient.parse_account_tax_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AccountTaxServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = AccountTaxServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AccountTaxServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = AccountTaxServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = AccountTaxServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AccountTaxServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AccountTaxServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = AccountTaxServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AccountTaxServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = AccountTaxServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = AccountTaxServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AccountTaxServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AccountTaxServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = AccountTaxServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AccountTaxServiceClient.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.AccountTaxServiceTransport, '_prep_wrapped_messages') as prep: - client = AccountTaxServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AccountTaxServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AccountTaxServiceClient.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 = AccountTaxServiceClient( - 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 = AccountTaxServiceAsyncClient( - 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 = AccountTaxServiceClient( - 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 = AccountTaxServiceClient( - 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", [ - (AccountTaxServiceClient, transports.AccountTaxServiceGrpcTransport), - (AccountTaxServiceAsyncClient, transports.AccountTaxServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py deleted file mode 100644 index add2c943db1c..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_accounts_service.py +++ /dev/null @@ -1,5650 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.accounts_service import AccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.accounts_service import AccountsServiceClient -from google.shopping.merchant_accounts_v1beta.services.accounts_service import pagers -from google.shopping.merchant_accounts_v1beta.services.accounts_service import transports -from google.shopping.merchant_accounts_v1beta.types import accessright -from google.shopping.merchant_accounts_v1beta.types import accounts -from google.shopping.merchant_accounts_v1beta.types import accountservices -from google.shopping.merchant_accounts_v1beta.types import user -from google.type import datetime_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 AccountsServiceClient._get_default_mtls_endpoint(None) is None - assert AccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AccountsServiceClient._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 AccountsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AccountsServiceClient._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 AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, False) is None - assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AccountsServiceClient._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 AccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountsServiceClient._get_universe_domain(None, None) == AccountsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AccountsServiceClient._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 = AccountsServiceClient(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 = AccountsServiceClient(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", [ - (AccountsServiceClient, "grpc"), - (AccountsServiceAsyncClient, "grpc_asyncio"), - (AccountsServiceClient, "rest"), -]) -def test_accounts_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.AccountsServiceGrpcTransport, "grpc"), - (transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountsServiceRestTransport, "rest"), -]) -def test_accounts_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", [ - (AccountsServiceClient, "grpc"), - (AccountsServiceAsyncClient, "grpc_asyncio"), - (AccountsServiceClient, "rest"), -]) -def test_accounts_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_accounts_service_client_get_transport_class(): - transport = AccountsServiceClient.get_transport_class() - available_transports = [ - transports.AccountsServiceGrpcTransport, - transports.AccountsServiceRestTransport, - ] - assert transport in available_transports - - transport = AccountsServiceClient.get_transport_class("grpc") - assert transport == transports.AccountsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) -def test_accounts_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(AccountsServiceClient, '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(AccountsServiceClient, '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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "true"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "false"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "true"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_accounts_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", [ - AccountsServiceClient, AccountsServiceAsyncClient -]) -@mock.patch.object(AccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceAsyncClient)) -def test_accounts_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", [ - AccountsServiceClient, AccountsServiceAsyncClient -]) -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) -def test_accounts_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AccountsServiceClient._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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), -]) -def test_accounts_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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", None), -]) -def test_accounts_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_accounts_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.accounts_service.transports.AccountsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AccountsServiceClient( - 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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_accounts_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", [ - accounts.GetAccountRequest, - dict, -]) -def test_get_account(request_type, transport: str = 'grpc'): - client = AccountsServiceClient( - 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.get_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - ) - response = client.get_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accounts.GetAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -def test_get_account_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 = AccountsServiceClient( - 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 = accounts.GetAccountRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_account(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accounts.GetAccountRequest( - name='name_value', - ) - -def test_get_account_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 = AccountsServiceClient( - 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.get_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account] = mock_rpc - request = {} - client.get_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_account(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_get_account_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 = AccountsServiceAsyncClient( - 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.get_account in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_account] = mock_rpc - - request = {} - await client.get_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_account(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_get_account_async(transport: str = 'grpc_asyncio', request_type=accounts.GetAccountRequest): - client = AccountsServiceAsyncClient( - 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.get_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) - response = await client.get_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accounts.GetAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_get_account_async_from_dict(): - await test_get_account_async(request_type=dict) - -def test_get_account_field_headers(): - client = AccountsServiceClient( - 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 = accounts.GetAccountRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - call.return_value = accounts.Account() - client.get_account(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_get_account_field_headers_async(): - client = AccountsServiceAsyncClient( - 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 = accounts.GetAccountRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) - await client.get_account(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_get_account_flattened(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_account( - 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_get_account_flattened_error(): - client = AccountsServiceClient( - 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.get_account( - accounts.GetAccountRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_account_flattened_async(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_account( - 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_get_account_flattened_error_async(): - client = AccountsServiceAsyncClient( - 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.get_account( - accounts.GetAccountRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - accounts.CreateAndConfigureAccountRequest, - dict, -]) -def test_create_and_configure_account(request_type, transport: str = 'grpc'): - client = AccountsServiceClient( - 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.create_and_configure_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - ) - response = client.create_and_configure_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accounts.CreateAndConfigureAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -def test_create_and_configure_account_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 = AccountsServiceClient( - 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 = accounts.CreateAndConfigureAccountRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_and_configure_account(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accounts.CreateAndConfigureAccountRequest( - ) - -def test_create_and_configure_account_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 = AccountsServiceClient( - 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.create_and_configure_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc - request = {} - client.create_and_configure_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_and_configure_account(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_create_and_configure_account_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 = AccountsServiceAsyncClient( - 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.create_and_configure_account in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_and_configure_account] = mock_rpc - - request = {} - await client.create_and_configure_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_and_configure_account(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_create_and_configure_account_async(transport: str = 'grpc_asyncio', request_type=accounts.CreateAndConfigureAccountRequest): - client = AccountsServiceAsyncClient( - 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.create_and_configure_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) - response = await client.create_and_configure_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accounts.CreateAndConfigureAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_create_and_configure_account_async_from_dict(): - await test_create_and_configure_account_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - accounts.DeleteAccountRequest, - dict, -]) -def test_delete_account(request_type, transport: str = 'grpc'): - client = AccountsServiceClient( - 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_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accounts.DeleteAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_account_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 = AccountsServiceClient( - 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 = accounts.DeleteAccountRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_account(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accounts.DeleteAccountRequest( - name='name_value', - ) - -def test_delete_account_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 = AccountsServiceClient( - 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_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_account] = mock_rpc - request = {} - client.delete_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_account(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_account_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 = AccountsServiceAsyncClient( - 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_account 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_account] = mock_rpc - - request = {} - await client.delete_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_account(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_account_async(transport: str = 'grpc_asyncio', request_type=accounts.DeleteAccountRequest): - client = AccountsServiceAsyncClient( - 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_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accounts.DeleteAccountRequest() - 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_account_async_from_dict(): - await test_delete_account_async(request_type=dict) - -def test_delete_account_field_headers(): - client = AccountsServiceClient( - 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 = accounts.DeleteAccountRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: - call.return_value = None - client.delete_account(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_account_field_headers_async(): - client = AccountsServiceAsyncClient( - 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 = accounts.DeleteAccountRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_account(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_account_flattened(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__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_account( - 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_account_flattened_error(): - client = AccountsServiceClient( - 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_account( - accounts.DeleteAccountRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_account_flattened_async(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__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_account( - 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_account_flattened_error_async(): - client = AccountsServiceAsyncClient( - 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_account( - accounts.DeleteAccountRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - accounts.UpdateAccountRequest, - dict, -]) -def test_update_account(request_type, transport: str = 'grpc'): - client = AccountsServiceClient( - 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.update_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - ) - response = client.update_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accounts.UpdateAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -def test_update_account_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 = AccountsServiceClient( - 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 = accounts.UpdateAccountRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_account(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accounts.UpdateAccountRequest( - ) - -def test_update_account_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 = AccountsServiceClient( - 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.update_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_account] = mock_rpc - request = {} - client.update_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_account(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_update_account_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 = AccountsServiceAsyncClient( - 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.update_account in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_account] = mock_rpc - - request = {} - await client.update_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_account(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_update_account_async(transport: str = 'grpc_asyncio', request_type=accounts.UpdateAccountRequest): - client = AccountsServiceAsyncClient( - 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.update_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) - response = await client.update_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accounts.UpdateAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -@pytest.mark.asyncio -async def test_update_account_async_from_dict(): - await test_update_account_async(request_type=dict) - -def test_update_account_field_headers(): - client = AccountsServiceClient( - 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 = accounts.UpdateAccountRequest() - - request.account.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - call.return_value = accounts.Account() - client.update_account(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', - 'account.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_account_field_headers_async(): - client = AccountsServiceAsyncClient( - 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 = accounts.UpdateAccountRequest() - - request.account.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) - await client.update_account(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', - 'account.name=name_value', - ) in kw['metadata'] - - -def test_update_account_flattened(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_account( - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account - mock_val = accounts.Account(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_account_flattened_error(): - client = AccountsServiceClient( - 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.update_account( - accounts.UpdateAccountRequest(), - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_account_flattened_async(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.Account() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_account( - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].account - mock_val = accounts.Account(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_account_flattened_error_async(): - client = AccountsServiceAsyncClient( - 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.update_account( - accounts.UpdateAccountRequest(), - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - accounts.ListAccountsRequest, - dict, -]) -def test_list_accounts(request_type, transport: str = 'grpc'): - client = AccountsServiceClient( - 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_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.ListAccountsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accounts.ListAccountsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_accounts_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 = AccountsServiceClient( - 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 = accounts.ListAccountsRequest( - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_accounts(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accounts.ListAccountsRequest( - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_accounts_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 = AccountsServiceClient( - 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_accounts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_accounts] = mock_rpc - request = {} - client.list_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_accounts(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_accounts_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 = AccountsServiceAsyncClient( - 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_accounts 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_accounts] = mock_rpc - - request = {} - await client.list_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_accounts(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_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListAccountsRequest): - client = AccountsServiceAsyncClient( - 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_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accounts.ListAccountsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_accounts_async_from_dict(): - await test_list_accounts_async(request_type=dict) - - -def test_list_accounts_pager(transport_name: str = "grpc"): - client = AccountsServiceClient( - 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_accounts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_accounts(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, accounts.Account) - for i in results) -def test_list_accounts_pages(transport_name: str = "grpc"): - client = AccountsServiceClient( - 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_accounts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - RuntimeError, - ) - pages = list(client.list_accounts(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_accounts_async_pager(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_accounts(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, accounts.Account) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_accounts_async_pages(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - 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_accounts(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", [ - accounts.ListSubAccountsRequest, - dict, -]) -def test_list_sub_accounts(request_type, transport: str = 'grpc'): - client = AccountsServiceClient( - 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_sub_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_sub_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = accounts.ListSubAccountsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubAccountsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_sub_accounts_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 = AccountsServiceClient( - 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 = accounts.ListSubAccountsRequest( - provider='provider_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_sub_accounts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_sub_accounts(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == accounts.ListSubAccountsRequest( - provider='provider_value', - page_token='page_token_value', - ) - -def test_list_sub_accounts_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 = AccountsServiceClient( - 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_sub_accounts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_sub_accounts] = mock_rpc - request = {} - client.list_sub_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_sub_accounts(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_sub_accounts_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 = AccountsServiceAsyncClient( - 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_sub_accounts 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_sub_accounts] = mock_rpc - - request = {} - await client.list_sub_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_sub_accounts(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_sub_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListSubAccountsRequest): - client = AccountsServiceAsyncClient( - 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_sub_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_sub_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = accounts.ListSubAccountsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubAccountsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_sub_accounts_async_from_dict(): - await test_list_sub_accounts_async(request_type=dict) - -def test_list_sub_accounts_field_headers(): - client = AccountsServiceClient( - 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 = accounts.ListSubAccountsRequest() - - request.provider = 'provider_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - call.return_value = accounts.ListSubAccountsResponse() - client.list_sub_accounts(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', - 'provider=provider_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_sub_accounts_field_headers_async(): - client = AccountsServiceAsyncClient( - 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 = accounts.ListSubAccountsRequest() - - request.provider = 'provider_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) - await client.list_sub_accounts(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', - 'provider=provider_value', - ) in kw['metadata'] - - -def test_list_sub_accounts_flattened(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.ListSubAccountsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_sub_accounts( - provider='provider_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].provider - mock_val = 'provider_value' - assert arg == mock_val - - -def test_list_sub_accounts_flattened_error(): - client = AccountsServiceClient( - 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_sub_accounts( - accounts.ListSubAccountsRequest(), - provider='provider_value', - ) - -@pytest.mark.asyncio -async def test_list_sub_accounts_flattened_async(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = accounts.ListSubAccountsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_sub_accounts( - provider='provider_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].provider - mock_val = 'provider_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_sub_accounts_flattened_error_async(): - client = AccountsServiceAsyncClient( - 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_sub_accounts( - accounts.ListSubAccountsRequest(), - provider='provider_value', - ) - - -def test_list_sub_accounts_pager(transport_name: str = "grpc"): - client = AccountsServiceClient( - 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_sub_accounts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListSubAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('provider', ''), - )), - ) - pager = client.list_sub_accounts(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, accounts.Account) - for i in results) -def test_list_sub_accounts_pages(transport_name: str = "grpc"): - client = AccountsServiceClient( - 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_sub_accounts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListSubAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - RuntimeError, - ) - pages = list(client.list_sub_accounts(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_sub_accounts_async_pager(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListSubAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_sub_accounts(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, accounts.Account) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_sub_accounts_async_pages(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListSubAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - 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_sub_accounts(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_account_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 = AccountsServiceClient( - 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.get_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account] = mock_rpc - - request = {} - client.get_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_account(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_get_account_rest_required_fields(request_type=accounts.GetAccountRequest): - transport_class = transports.AccountsServiceRestTransport - - 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()).get_account._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account._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 = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = accounts.Account() - # 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 = accounts.Account.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.get_account(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_account_rest_flattened(): - client = AccountsServiceClient( - 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 = accounts.Account() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1'} - - # 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 - # Convert return value to protobuf type - return_value = accounts.Account.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.get_account(**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/accounts/v1beta/{name=accounts/*}" % client.transport._host, args[1]) - - -def test_get_account_rest_flattened_error(transport: str = 'rest'): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_account( - accounts.GetAccountRequest(), - name='name_value', - ) - - -def test_create_and_configure_account_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 = AccountsServiceClient( - 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.create_and_configure_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc - - request = {} - client.create_and_configure_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_and_configure_account(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_create_and_configure_account_rest_required_fields(request_type=accounts.CreateAndConfigureAccountRequest): - transport_class = transports.AccountsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = accounts.Account() - # 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 = accounts.Account.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.create_and_configure_account(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_and_configure_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_and_configure_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("account", "service", ))) - - -def test_delete_account_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 = AccountsServiceClient( - 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_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_account] = mock_rpc - - request = {} - client.delete_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_account(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_account_rest_required_fields(request_type=accounts.DeleteAccountRequest): - transport_class = transports.AccountsServiceRestTransport - - 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_account._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_account._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - 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 = AccountsServiceClient( - 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_account(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -def test_delete_account_rest_flattened(): - client = AccountsServiceClient( - 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'} - - # 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_account(**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/accounts/v1beta/{name=accounts/*}" % client.transport._host, args[1]) - - -def test_delete_account_rest_flattened_error(transport: str = 'rest'): - client = AccountsServiceClient( - 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_account( - accounts.DeleteAccountRequest(), - name='name_value', - ) - - -def test_update_account_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 = AccountsServiceClient( - 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.update_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_account] = mock_rpc - - request = {} - client.update_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_account(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_update_account_rest_required_fields(request_type=accounts.UpdateAccountRequest): - transport_class = transports.AccountsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = accounts.Account() - # 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': "patch", - '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 = accounts.Account.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.update_account(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("account", "updateMask", ))) - - -def test_update_account_rest_flattened(): - client = AccountsServiceClient( - 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 = accounts.Account() - - # get arguments that satisfy an http rule for this method - sample_request = {'account': {'name': 'accounts/sample1'}} - - # get truthy value for each flattened field - mock_args = dict( - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = accounts.Account.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.update_account(**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/accounts/v1beta/{account.name=accounts/*}" % client.transport._host, args[1]) - - -def test_update_account_rest_flattened_error(transport: str = 'rest'): - client = AccountsServiceClient( - 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.update_account( - accounts.UpdateAccountRequest(), - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_accounts_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 = AccountsServiceClient( - 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_accounts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_accounts] = mock_rpc - - request = {} - client.list_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_accounts(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_accounts_rest_pager(transport: str = 'rest'): - client = AccountsServiceClient( - 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 = ( - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(accounts.ListAccountsResponse.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 = {} - - pager = client.list_accounts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, accounts.Account) - for i in results) - - pages = list(client.list_accounts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_sub_accounts_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 = AccountsServiceClient( - 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_sub_accounts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_sub_accounts] = mock_rpc - - request = {} - client.list_sub_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_sub_accounts(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_sub_accounts_rest_required_fields(request_type=accounts.ListSubAccountsRequest): - transport_class = transports.AccountsServiceRestTransport - - request_init = {} - request_init["provider"] = "" - 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_sub_accounts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["provider"] = 'provider_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_sub_accounts._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 "provider" in jsonified_request - assert jsonified_request["provider"] == 'provider_value' - - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = accounts.ListSubAccountsResponse() - # 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 = accounts.ListSubAccountsResponse.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_sub_accounts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_sub_accounts_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_sub_accounts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("provider", ))) - - -def test_list_sub_accounts_rest_flattened(): - client = AccountsServiceClient( - 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 = accounts.ListSubAccountsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'provider': 'accounts/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - provider='provider_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 = accounts.ListSubAccountsResponse.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_sub_accounts(**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/accounts/v1beta/{provider=accounts/*}:listSubaccounts" % client.transport._host, args[1]) - - -def test_list_sub_accounts_rest_flattened_error(transport: str = 'rest'): - client = AccountsServiceClient( - 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_sub_accounts( - accounts.ListSubAccountsRequest(), - provider='provider_value', - ) - - -def test_list_sub_accounts_rest_pager(transport: str = 'rest'): - client = AccountsServiceClient( - 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 = ( - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - accounts.Account(), - ], - next_page_token='abc', - ), - accounts.ListSubAccountsResponse( - accounts=[], - next_page_token='def', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - ], - next_page_token='ghi', - ), - accounts.ListSubAccountsResponse( - accounts=[ - accounts.Account(), - accounts.Account(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(accounts.ListSubAccountsResponse.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 = {'provider': 'accounts/sample1'} - - pager = client.list_sub_accounts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, accounts.Account) - for i in results) - - pages = list(client.list_sub_accounts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AccountsServiceClient( - 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 = AccountsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AccountsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AccountsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AccountsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AccountsServiceGrpcTransport, - transports.AccountsServiceGrpcAsyncIOTransport, - transports.AccountsServiceRestTransport, -]) -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 = AccountsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AccountsServiceClient( - 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_get_account_empty_call_grpc(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - call.return_value = accounts.Account() - client.get_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.GetAccountRequest() - - 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_create_and_configure_account_empty_call_grpc(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: - call.return_value = accounts.Account() - client.create_and_configure_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.CreateAndConfigureAccountRequest() - - 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_account_empty_call_grpc(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: - call.return_value = None - client.delete_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.DeleteAccountRequest() - - 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_update_account_empty_call_grpc(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - call.return_value = accounts.Account() - client.update_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.UpdateAccountRequest() - - 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_list_accounts_empty_call_grpc(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: - call.return_value = accounts.ListAccountsResponse() - client.list_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.ListAccountsRequest() - - 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_list_sub_accounts_empty_call_grpc(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - call.return_value = accounts.ListSubAccountsResponse() - client.list_sub_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.ListSubAccountsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AccountsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AccountsServiceAsyncClient( - 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_get_account_empty_call_grpc_asyncio(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) - await client.get_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.GetAccountRequest() - - 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_create_and_configure_account_empty_call_grpc_asyncio(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) - await client.create_and_configure_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.CreateAndConfigureAccountRequest() - - 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_account_empty_call_grpc_asyncio(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.DeleteAccountRequest() - - 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_update_account_empty_call_grpc_asyncio(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) - await client.update_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.UpdateAccountRequest() - - 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_list_accounts_empty_call_grpc_asyncio(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( - next_page_token='next_page_token_value', - )) - await client.list_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.ListAccountsRequest() - - 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_list_sub_accounts_empty_call_grpc_asyncio(): - client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', - )) - await client.list_sub_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.ListSubAccountsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AccountsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_account_rest_bad_request(request_type=accounts.GetAccountRequest): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} - 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.get_account(request) - - -@pytest.mark.parametrize("request_type", [ - accounts.GetAccountRequest, - dict, -]) -def test_get_account_rest_call_success(request_type): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_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 = accounts.Account.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.get_account(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_account_rest_interceptors(null_interceptor): - transport = transports.AccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) - client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_get_account") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_get_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_get_account") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = accounts.GetAccountRequest.pb(accounts.GetAccountRequest()) - 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 = accounts.Account.to_json(accounts.Account()) - req.return_value.content = return_value - - request = accounts.GetAccountRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = accounts.Account() - post_with_metadata.return_value = accounts.Account(), metadata - - client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_and_configure_account_rest_bad_request(request_type=accounts.CreateAndConfigureAccountRequest): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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.create_and_configure_account(request) - - -@pytest.mark.parametrize("request_type", [ - accounts.CreateAndConfigureAccountRequest, - dict, -]) -def test_create_and_configure_account_rest_call_success(request_type): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_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 = accounts.Account.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.create_and_configure_account(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_and_configure_account_rest_interceptors(null_interceptor): - transport = transports.AccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) - client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_create_and_configure_account") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_create_and_configure_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_create_and_configure_account") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = accounts.CreateAndConfigureAccountRequest.pb(accounts.CreateAndConfigureAccountRequest()) - 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 = accounts.Account.to_json(accounts.Account()) - req.return_value.content = return_value - - request = accounts.CreateAndConfigureAccountRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = accounts.Account() - post_with_metadata.return_value = accounts.Account(), metadata - - client.create_and_configure_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_account_rest_bad_request(request_type=accounts.DeleteAccountRequest): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} - 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_account(request) - - -@pytest.mark.parametrize("request_type", [ - accounts.DeleteAccountRequest, - dict, -]) -def test_delete_account_rest_call_success(request_type): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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_account(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_account_rest_interceptors(null_interceptor): - transport = transports.AccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) - client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "pre_delete_account") as pre: - pre.assert_not_called() - pb_message = accounts.DeleteAccountRequest.pb(accounts.DeleteAccountRequest()) - 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 = accounts.DeleteAccountRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_update_account_rest_bad_request(request_type=accounts.UpdateAccountRequest): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'account': {'name': 'accounts/sample1'}} - 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.update_account(request) - - -@pytest.mark.parametrize("request_type", [ - accounts.UpdateAccountRequest, - dict, -]) -def test_update_account_rest_call_success(request_type): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'account': {'name': 'accounts/sample1'}} - request_init["account"] = {'name': 'accounts/sample1', 'account_id': 1049, 'account_name': 'account_name_value', 'adult_content': True, 'test_account': True, 'time_zone': {'id': 'id_value', 'version': 'version_value'}, 'language_code': 'language_code_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 = accounts.UpdateAccountRequest.meta.fields["account"] - - 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["account"].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["account"][field])): - del request_init["account"][field][i][subfield] - else: - del request_init["account"][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 = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_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 = accounts.Account.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.update_account(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, accounts.Account) - assert response.name == 'name_value' - assert response.account_id == 1049 - assert response.account_name == 'account_name_value' - assert response.adult_content is True - assert response.test_account is True - assert response.language_code == 'language_code_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_account_rest_interceptors(null_interceptor): - transport = transports.AccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) - client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_update_account") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_update_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_update_account") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = accounts.UpdateAccountRequest.pb(accounts.UpdateAccountRequest()) - 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 = accounts.Account.to_json(accounts.Account()) - req.return_value.content = return_value - - request = accounts.UpdateAccountRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = accounts.Account() - post_with_metadata.return_value = accounts.Account(), metadata - - client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_accounts_rest_bad_request(request_type=accounts.ListAccountsRequest): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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_accounts(request) - - -@pytest.mark.parametrize("request_type", [ - accounts.ListAccountsRequest, - dict, -]) -def test_list_accounts_rest_call_success(request_type): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = accounts.ListAccountsResponse( - 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 = accounts.ListAccountsResponse.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_accounts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_accounts_rest_interceptors(null_interceptor): - transport = transports.AccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) - client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_accounts") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_accounts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_accounts") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = accounts.ListAccountsRequest.pb(accounts.ListAccountsRequest()) - 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 = accounts.ListAccountsResponse.to_json(accounts.ListAccountsResponse()) - req.return_value.content = return_value - - request = accounts.ListAccountsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = accounts.ListAccountsResponse() - post_with_metadata.return_value = accounts.ListAccountsResponse(), metadata - - client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_sub_accounts_rest_bad_request(request_type=accounts.ListSubAccountsRequest): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'provider': 'accounts/sample1'} - 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_sub_accounts(request) - - -@pytest.mark.parametrize("request_type", [ - accounts.ListSubAccountsRequest, - dict, -]) -def test_list_sub_accounts_rest_call_success(request_type): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'provider': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = accounts.ListSubAccountsResponse( - 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 = accounts.ListSubAccountsResponse.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_sub_accounts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSubAccountsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_sub_accounts_rest_interceptors(null_interceptor): - transport = transports.AccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) - client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_sub_accounts") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_sub_accounts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_sub_accounts") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = accounts.ListSubAccountsRequest.pb(accounts.ListSubAccountsRequest()) - 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 = accounts.ListSubAccountsResponse.to_json(accounts.ListSubAccountsResponse()) - req.return_value.content = return_value - - request = accounts.ListSubAccountsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = accounts.ListSubAccountsResponse() - post_with_metadata.return_value = accounts.ListSubAccountsResponse(), metadata - - client.list_sub_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = AccountsServiceClient( - 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_get_account_empty_call_rest(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - client.get_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.GetAccountRequest() - - 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_create_and_configure_account_empty_call_rest(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: - client.create_and_configure_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.CreateAndConfigureAccountRequest() - - 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_account_empty_call_rest(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: - client.delete_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.DeleteAccountRequest() - - 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_update_account_empty_call_rest(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - client.update_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.UpdateAccountRequest() - - 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_list_accounts_empty_call_rest(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: - client.list_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.ListAccountsRequest() - - 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_list_sub_accounts_empty_call_rest(): - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - client.list_sub_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = accounts.ListSubAccountsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AccountsServiceGrpcTransport, - ) - -def test_accounts_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AccountsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_accounts_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.accounts_service.transports.AccountsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AccountsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_account', - 'create_and_configure_account', - 'delete_account', - 'update_account', - 'list_accounts', - 'list_sub_accounts', - ) - 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_accounts_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_accounts_v1beta.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AccountsServiceTransport( - 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_accounts_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_accounts_v1beta.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AccountsServiceTransport() - adc.assert_called_once() - - -def test_accounts_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) - AccountsServiceClient() - 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.AccountsServiceGrpcTransport, - transports.AccountsServiceGrpcAsyncIOTransport, - ], -) -def test_accounts_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.AccountsServiceGrpcTransport, - transports.AccountsServiceGrpcAsyncIOTransport, - transports.AccountsServiceRestTransport, - ], -) -def test_accounts_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.AccountsServiceGrpcTransport, grpc_helpers), - (transports.AccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) -def test_accounts_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_accounts_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.AccountsServiceRestTransport ( - 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_accounts_service_host_no_port(transport_name): - client = AccountsServiceClient( - 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_accounts_service_host_with_port(transport_name): - client = AccountsServiceClient( - 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_accounts_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AccountsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AccountsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_account._session - session2 = client2.transport.get_account._session - assert session1 != session2 - session1 = client1.transport.create_and_configure_account._session - session2 = client2.transport.create_and_configure_account._session - assert session1 != session2 - session1 = client1.transport.delete_account._session - session2 = client2.transport.delete_account._session - assert session1 != session2 - session1 = client1.transport.update_account._session - session2 = client2.transport.update_account._session - assert session1 != session2 - session1 = client1.transport.list_accounts._session - session2 = client2.transport.list_accounts._session - assert session1 != session2 - session1 = client1.transport.list_sub_accounts._session - session2 = client2.transport.list_sub_accounts._session - assert session1 != session2 -def test_accounts_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AccountsServiceGrpcTransport( - 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_accounts_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AccountsServiceGrpcAsyncIOTransport( - 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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) -def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) -def test_accounts_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = AccountsServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = AccountsServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_account_path(path) - assert expected == actual - -def test_terms_of_service_path(): - version = "whelk" - expected = "termsOfService/{version}".format(version=version, ) - actual = AccountsServiceClient.terms_of_service_path(version) - assert expected == actual - - -def test_parse_terms_of_service_path(): - expected = { - "version": "octopus", - } - path = AccountsServiceClient.terms_of_service_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_terms_of_service_path(path) - assert expected == actual - -def test_user_path(): - account = "oyster" - email = "nudibranch" - expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) - actual = AccountsServiceClient.user_path(account, email) - assert expected == actual - - -def test_parse_user_path(): - expected = { - "account": "cuttlefish", - "email": "mussel", - } - path = AccountsServiceClient.user_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_user_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AccountsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = AccountsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = AccountsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = AccountsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AccountsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = AccountsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = AccountsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = AccountsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AccountsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = AccountsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AccountsServiceClient.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.AccountsServiceTransport, '_prep_wrapped_messages') as prep: - client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AccountsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AccountsServiceClient.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 = AccountsServiceClient( - 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 = AccountsServiceAsyncClient( - 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 = AccountsServiceClient( - 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 = AccountsServiceClient( - 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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py deleted file mode 100644 index e0498b775e93..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_autofeed_settings_service.py +++ /dev/null @@ -1,2890 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service import AutofeedSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service import transports -from google.shopping.merchant_accounts_v1beta.types import autofeedsettings -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 AutofeedSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, False) is None - assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AutofeedSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AutofeedSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AutofeedSettingsServiceClient._get_universe_domain(None, None) == AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient(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 = AutofeedSettingsServiceClient(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", [ - (AutofeedSettingsServiceClient, "grpc"), - (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), - (AutofeedSettingsServiceClient, "rest"), -]) -def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, "grpc"), - (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -def test_autofeed_settings_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", [ - (AutofeedSettingsServiceClient, "grpc"), - (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), - (AutofeedSettingsServiceClient, "rest"), -]) -def test_autofeed_settings_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_autofeed_settings_service_client_get_transport_class(): - transport = AutofeedSettingsServiceClient.get_transport_class() - available_transports = [ - transports.AutofeedSettingsServiceGrpcTransport, - transports.AutofeedSettingsServiceRestTransport, - ] - assert transport in available_transports - - transport = AutofeedSettingsServiceClient.get_transport_class("grpc") - assert transport == transports.AutofeedSettingsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) -def test_autofeed_settings_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(AutofeedSettingsServiceClient, '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(AutofeedSettingsServiceClient, '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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "true"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "false"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "true"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_autofeed_settings_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", [ - AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient -]) -@mock.patch.object(AutofeedSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceAsyncClient)) -def test_autofeed_settings_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", [ - AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient -]) -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) -def test_autofeed_settings_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutofeedSettingsServiceClient._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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -def test_autofeed_settings_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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", None), -]) -def test_autofeed_settings_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_autofeed_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AutofeedSettingsServiceClient( - 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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_autofeed_settings_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", [ - autofeedsettings.GetAutofeedSettingsRequest, - dict, -]) -def test_get_autofeed_settings(request_type, transport: str = 'grpc'): - client = AutofeedSettingsServiceClient( - 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.get_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - ) - response = client.get_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autofeedsettings.GetAutofeedSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' - assert response.enable_products is True - assert response.eligible is True - - -def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( - 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 = autofeedsettings.GetAutofeedSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_autofeed_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autofeedsettings.GetAutofeedSettingsRequest( - name='name_value', - ) - -def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( - 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.get_autofeed_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc - request = {} - client.get_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_autofeed_settings(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_get_autofeed_settings_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 = AutofeedSettingsServiceAsyncClient( - 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.get_autofeed_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_autofeed_settings] = mock_rpc - - request = {} - await client.get_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_autofeed_settings(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_get_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.GetAutofeedSettingsRequest): - client = AutofeedSettingsServiceAsyncClient( - 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.get_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) - response = await client.get_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autofeedsettings.GetAutofeedSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' - assert response.enable_products is True - assert response.eligible is True - - -@pytest.mark.asyncio -async def test_get_autofeed_settings_async_from_dict(): - await test_get_autofeed_settings_async(request_type=dict) - -def test_get_autofeed_settings_field_headers(): - client = AutofeedSettingsServiceClient( - 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 = autofeedsettings.GetAutofeedSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - call.return_value = autofeedsettings.AutofeedSettings() - client.get_autofeed_settings(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_get_autofeed_settings_field_headers_async(): - client = AutofeedSettingsServiceAsyncClient( - 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 = autofeedsettings.GetAutofeedSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) - await client.get_autofeed_settings(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_get_autofeed_settings_flattened(): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autofeedsettings.AutofeedSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_autofeed_settings( - 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_get_autofeed_settings_flattened_error(): - client = AutofeedSettingsServiceClient( - 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.get_autofeed_settings( - autofeedsettings.GetAutofeedSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_autofeed_settings_flattened_async(): - client = AutofeedSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autofeedsettings.AutofeedSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_autofeed_settings( - 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_get_autofeed_settings_flattened_error_async(): - client = AutofeedSettingsServiceAsyncClient( - 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.get_autofeed_settings( - autofeedsettings.GetAutofeedSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - autofeedsettings.UpdateAutofeedSettingsRequest, - dict, -]) -def test_update_autofeed_settings(request_type, transport: str = 'grpc'): - client = AutofeedSettingsServiceClient( - 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.update_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - ) - response = client.update_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autofeedsettings.UpdateAutofeedSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' - assert response.enable_products is True - assert response.eligible is True - - -def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( - 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 = autofeedsettings.UpdateAutofeedSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_autofeed_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autofeedsettings.UpdateAutofeedSettingsRequest( - ) - -def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( - 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.update_autofeed_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc - request = {} - client.update_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_autofeed_settings(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_update_autofeed_settings_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 = AutofeedSettingsServiceAsyncClient( - 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.update_autofeed_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_autofeed_settings] = mock_rpc - - request = {} - await client.update_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_autofeed_settings(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_update_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.UpdateAutofeedSettingsRequest): - client = AutofeedSettingsServiceAsyncClient( - 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.update_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) - response = await client.update_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autofeedsettings.UpdateAutofeedSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' - assert response.enable_products is True - assert response.eligible is True - - -@pytest.mark.asyncio -async def test_update_autofeed_settings_async_from_dict(): - await test_update_autofeed_settings_async(request_type=dict) - -def test_update_autofeed_settings_field_headers(): - client = AutofeedSettingsServiceClient( - 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 = autofeedsettings.UpdateAutofeedSettingsRequest() - - request.autofeed_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - call.return_value = autofeedsettings.AutofeedSettings() - client.update_autofeed_settings(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', - 'autofeed_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_autofeed_settings_field_headers_async(): - client = AutofeedSettingsServiceAsyncClient( - 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 = autofeedsettings.UpdateAutofeedSettingsRequest() - - request.autofeed_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) - await client.update_autofeed_settings(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', - 'autofeed_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_autofeed_settings_flattened(): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autofeedsettings.AutofeedSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_autofeed_settings( - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].autofeed_settings - mock_val = autofeedsettings.AutofeedSettings(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_autofeed_settings_flattened_error(): - client = AutofeedSettingsServiceClient( - 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.update_autofeed_settings( - autofeedsettings.UpdateAutofeedSettingsRequest(), - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_autofeed_settings_flattened_async(): - client = AutofeedSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autofeedsettings.AutofeedSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_autofeed_settings( - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].autofeed_settings - mock_val = autofeedsettings.AutofeedSettings(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_autofeed_settings_flattened_error_async(): - client = AutofeedSettingsServiceAsyncClient( - 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.update_autofeed_settings( - autofeedsettings.UpdateAutofeedSettingsRequest(), - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_autofeed_settings_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 = AutofeedSettingsServiceClient( - 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.get_autofeed_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc - - request = {} - client.get_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_autofeed_settings(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_get_autofeed_settings_rest_required_fields(request_type=autofeedsettings.GetAutofeedSettingsRequest): - transport_class = transports.AutofeedSettingsServiceRestTransport - - 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()).get_autofeed_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autofeed_settings._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 = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autofeedsettings.AutofeedSettings() - # 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 = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_autofeed_settings_rest_unset_required_fields(): - transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_autofeed_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_autofeed_settings_rest_flattened(): - client = AutofeedSettingsServiceClient( - 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 = autofeedsettings.AutofeedSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/autofeedSettings'} - - # 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 - # Convert return value to protobuf type - return_value = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(**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/accounts/v1beta/{name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) - - -def test_get_autofeed_settings_rest_flattened_error(transport: str = 'rest'): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_autofeed_settings( - autofeedsettings.GetAutofeedSettingsRequest(), - name='name_value', - ) - - -def test_update_autofeed_settings_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 = AutofeedSettingsServiceClient( - 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.update_autofeed_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc - - request = {} - client.update_autofeed_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_autofeed_settings(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_update_autofeed_settings_rest_required_fields(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): - transport_class = transports.AutofeedSettingsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autofeedsettings.AutofeedSettings() - # 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': "patch", - '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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_autofeed_settings_rest_unset_required_fields(): - transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_autofeed_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("autofeedSettings", "updateMask", ))) - - -def test_update_autofeed_settings_rest_flattened(): - client = AutofeedSettingsServiceClient( - 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 = autofeedsettings.AutofeedSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(**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/accounts/v1beta/{autofeed_settings.name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) - - -def test_update_autofeed_settings_rest_flattened_error(transport: str = 'rest'): - client = AutofeedSettingsServiceClient( - 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.update_autofeed_settings( - autofeedsettings.UpdateAutofeedSettingsRequest(), - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AutofeedSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AutofeedSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutofeedSettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AutofeedSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AutofeedSettingsServiceClient( - 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 = AutofeedSettingsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AutofeedSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutofeedSettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutofeedSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AutofeedSettingsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutofeedSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AutofeedSettingsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AutofeedSettingsServiceGrpcTransport, - transports.AutofeedSettingsServiceGrpcAsyncIOTransport, - transports.AutofeedSettingsServiceRestTransport, -]) -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 = AutofeedSettingsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AutofeedSettingsServiceClient( - 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_get_autofeed_settings_empty_call_grpc(): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - call.return_value = autofeedsettings.AutofeedSettings() - client.get_autofeed_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autofeedsettings.GetAutofeedSettingsRequest() - - 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_update_autofeed_settings_empty_call_grpc(): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - call.return_value = autofeedsettings.AutofeedSettings() - client.update_autofeed_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AutofeedSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AutofeedSettingsServiceAsyncClient( - 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_get_autofeed_settings_empty_call_grpc_asyncio(): - client = AutofeedSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) - await client.get_autofeed_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autofeedsettings.GetAutofeedSettingsRequest() - - 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_update_autofeed_settings_empty_call_grpc_asyncio(): - client = AutofeedSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) - await client.update_autofeed_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AutofeedSettingsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_autofeed_settings_rest_bad_request(request_type=autofeedsettings.GetAutofeedSettingsRequest): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/autofeedSettings'} - 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.get_autofeed_settings(request) - - -@pytest.mark.parametrize("request_type", [ - autofeedsettings.GetAutofeedSettingsRequest, - dict, -]) -def test_get_autofeed_settings_rest_call_success(request_type): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/autofeedSettings'} - request = request_type(**request_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 = autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - ) - - # 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 = autofeedsettings.AutofeedSettings.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.get_autofeed_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' - assert response.enable_products is True - assert response.eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_autofeed_settings_rest_interceptors(null_interceptor): - transport = transports.AutofeedSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), - ) - client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings") as post, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_get_autofeed_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = autofeedsettings.GetAutofeedSettingsRequest.pb(autofeedsettings.GetAutofeedSettingsRequest()) - 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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) - req.return_value.content = return_value - - request = autofeedsettings.GetAutofeedSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autofeedsettings.AutofeedSettings() - post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata - - client.get_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_autofeed_settings_rest_bad_request(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} - 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.update_autofeed_settings(request) - - -@pytest.mark.parametrize("request_type", [ - autofeedsettings.UpdateAutofeedSettingsRequest, - dict, -]) -def test_update_autofeed_settings_rest_call_success(request_type): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} - request_init["autofeed_settings"] = {'name': 'accounts/sample1/autofeedSettings', 'enable_products': True, 'eligible': True} - # 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 = autofeedsettings.UpdateAutofeedSettingsRequest.meta.fields["autofeed_settings"] - - 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["autofeed_settings"].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["autofeed_settings"][field])): - del request_init["autofeed_settings"][field][i][subfield] - else: - del request_init["autofeed_settings"][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 = autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - ) - - # 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 = autofeedsettings.AutofeedSettings.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.update_autofeed_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' - assert response.enable_products is True - assert response.eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_autofeed_settings_rest_interceptors(null_interceptor): - transport = transports.AutofeedSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), - ) - client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings") as post, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_update_autofeed_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = autofeedsettings.UpdateAutofeedSettingsRequest.pb(autofeedsettings.UpdateAutofeedSettingsRequest()) - 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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) - req.return_value.content = return_value - - request = autofeedsettings.UpdateAutofeedSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autofeedsettings.AutofeedSettings() - post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata - - client.update_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = AutofeedSettingsServiceClient( - 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_get_autofeed_settings_empty_call_rest(): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - client.get_autofeed_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autofeedsettings.GetAutofeedSettingsRequest() - - 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_update_autofeed_settings_empty_call_rest(): - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - client.update_autofeed_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autofeedsettings.UpdateAutofeedSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AutofeedSettingsServiceGrpcTransport, - ) - -def test_autofeed_settings_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AutofeedSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_autofeed_settings_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AutofeedSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_autofeed_settings', - 'update_autofeed_settings', - ) - 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_autofeed_settings_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_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutofeedSettingsServiceTransport( - 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_autofeed_settings_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_accounts_v1beta.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutofeedSettingsServiceTransport() - adc.assert_called_once() - - -def test_autofeed_settings_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) - AutofeedSettingsServiceClient() - 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.AutofeedSettingsServiceGrpcTransport, - transports.AutofeedSettingsServiceGrpcAsyncIOTransport, - ], -) -def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, - transports.AutofeedSettingsServiceGrpcAsyncIOTransport, - transports.AutofeedSettingsServiceRestTransport, - ], -) -def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, grpc_helpers), - (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) -def test_autofeed_settings_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_autofeed_settings_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.AutofeedSettingsServiceRestTransport ( - 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_autofeed_settings_service_host_no_port(transport_name): - client = AutofeedSettingsServiceClient( - 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_autofeed_settings_service_host_with_port(transport_name): - client = AutofeedSettingsServiceClient( - 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_autofeed_settings_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AutofeedSettingsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AutofeedSettingsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_autofeed_settings._session - session2 = client2.transport.get_autofeed_settings._session - assert session1 != session2 - session1 = client1.transport.update_autofeed_settings._session - session2 = client2.transport.update_autofeed_settings._session - assert session1 != session2 -def test_autofeed_settings_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutofeedSettingsServiceGrpcTransport( - 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_autofeed_settings_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutofeedSettingsServiceGrpcAsyncIOTransport( - 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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) -def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) -def test_autofeed_settings_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_autofeed_settings_path(): - account = "squid" - expected = "accounts/{account}/autofeedSettings".format(account=account, ) - actual = AutofeedSettingsServiceClient.autofeed_settings_path(account) - assert expected == actual - - -def test_parse_autofeed_settings_path(): - expected = { - "account": "clam", - } - path = AutofeedSettingsServiceClient.autofeed_settings_path(**expected) - - # Check that the path construction is reversible. - actual = AutofeedSettingsServiceClient.parse_autofeed_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AutofeedSettingsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AutofeedSettingsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AutofeedSettingsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AutofeedSettingsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AutofeedSettingsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AutofeedSettingsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AutofeedSettingsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AutofeedSettingsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AutofeedSettingsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AutofeedSettingsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AutofeedSettingsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AutofeedSettingsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AutofeedSettingsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AutofeedSettingsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AutofeedSettingsServiceClient.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.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: - client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AutofeedSettingsServiceClient.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 = AutofeedSettingsServiceClient( - 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 = AutofeedSettingsServiceAsyncClient( - 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 = AutofeedSettingsServiceClient( - 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 = AutofeedSettingsServiceClient( - 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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py deleted file mode 100644 index c95f4dd231df..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_automatic_improvements_service.py +++ /dev/null @@ -1,2862 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service import AutomaticImprovementsServiceClient -from google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service import transports -from google.shopping.merchant_accounts_v1beta.types import automaticimprovements -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 AutomaticImprovementsServiceClient._get_default_mtls_endpoint(None) is None - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, False) is None - assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AutomaticImprovementsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AutomaticImprovementsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AutomaticImprovementsServiceClient._get_universe_domain(None, None) == AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient(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 = AutomaticImprovementsServiceClient(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", [ - (AutomaticImprovementsServiceClient, "grpc"), - (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, "rest"), -]) -def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, "grpc"), - (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AutomaticImprovementsServiceRestTransport, "rest"), -]) -def test_automatic_improvements_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", [ - (AutomaticImprovementsServiceClient, "grpc"), - (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, "rest"), -]) -def test_automatic_improvements_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_automatic_improvements_service_client_get_transport_class(): - transport = AutomaticImprovementsServiceClient.get_transport_class() - available_transports = [ - transports.AutomaticImprovementsServiceGrpcTransport, - transports.AutomaticImprovementsServiceRestTransport, - ] - assert transport in available_transports - - transport = AutomaticImprovementsServiceClient.get_transport_class("grpc") - assert transport == transports.AutomaticImprovementsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) -def test_automatic_improvements_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(AutomaticImprovementsServiceClient, '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(AutomaticImprovementsServiceClient, '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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "true"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "false"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "true"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_automatic_improvements_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", [ - AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceAsyncClient)) -def test_automatic_improvements_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", [ - AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) -def test_automatic_improvements_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutomaticImprovementsServiceClient._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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), -]) -def test_automatic_improvements_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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", None), -]) -def test_automatic_improvements_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_automatic_improvements_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AutomaticImprovementsServiceClient( - 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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_automatic_improvements_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", [ - automaticimprovements.GetAutomaticImprovementsRequest, - dict, -]) -def test_get_automatic_improvements(request_type, transport: str = 'grpc'): - client = AutomaticImprovementsServiceClient( - 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.get_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = automaticimprovements.AutomaticImprovements( - name='name_value', - ) - response = client.get_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = automaticimprovements.GetAutomaticImprovementsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' - - -def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( - 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 = automaticimprovements.GetAutomaticImprovementsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_automatic_improvements(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == automaticimprovements.GetAutomaticImprovementsRequest( - name='name_value', - ) - -def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( - 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.get_automatic_improvements in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc - request = {} - client.get_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_automatic_improvements(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_get_automatic_improvements_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 = AutomaticImprovementsServiceAsyncClient( - 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.get_automatic_improvements in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_automatic_improvements] = mock_rpc - - request = {} - await client.get_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_automatic_improvements(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_get_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.GetAutomaticImprovementsRequest): - client = AutomaticImprovementsServiceAsyncClient( - 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.get_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) - response = await client.get_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = automaticimprovements.GetAutomaticImprovementsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_automatic_improvements_async_from_dict(): - await test_get_automatic_improvements_async(request_type=dict) - -def test_get_automatic_improvements_field_headers(): - client = AutomaticImprovementsServiceClient( - 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 = automaticimprovements.GetAutomaticImprovementsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - call.return_value = automaticimprovements.AutomaticImprovements() - client.get_automatic_improvements(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_get_automatic_improvements_field_headers_async(): - client = AutomaticImprovementsServiceAsyncClient( - 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 = automaticimprovements.GetAutomaticImprovementsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) - await client.get_automatic_improvements(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_get_automatic_improvements_flattened(): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = automaticimprovements.AutomaticImprovements() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_automatic_improvements( - 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_get_automatic_improvements_flattened_error(): - client = AutomaticImprovementsServiceClient( - 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.get_automatic_improvements( - automaticimprovements.GetAutomaticImprovementsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_automatic_improvements_flattened_async(): - client = AutomaticImprovementsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = automaticimprovements.AutomaticImprovements() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_automatic_improvements( - 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_get_automatic_improvements_flattened_error_async(): - client = AutomaticImprovementsServiceAsyncClient( - 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.get_automatic_improvements( - automaticimprovements.GetAutomaticImprovementsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - automaticimprovements.UpdateAutomaticImprovementsRequest, - dict, -]) -def test_update_automatic_improvements(request_type, transport: str = 'grpc'): - client = AutomaticImprovementsServiceClient( - 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.update_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = automaticimprovements.AutomaticImprovements( - name='name_value', - ) - response = client.update_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = automaticimprovements.UpdateAutomaticImprovementsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' - - -def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( - 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 = automaticimprovements.UpdateAutomaticImprovementsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_automatic_improvements(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == automaticimprovements.UpdateAutomaticImprovementsRequest( - ) - -def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( - 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.update_automatic_improvements in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc - request = {} - client.update_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_automatic_improvements(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_update_automatic_improvements_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 = AutomaticImprovementsServiceAsyncClient( - 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.update_automatic_improvements in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_automatic_improvements] = mock_rpc - - request = {} - await client.update_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_automatic_improvements(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_update_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): - client = AutomaticImprovementsServiceAsyncClient( - 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.update_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) - response = await client.update_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = automaticimprovements.UpdateAutomaticImprovementsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_update_automatic_improvements_async_from_dict(): - await test_update_automatic_improvements_async(request_type=dict) - -def test_update_automatic_improvements_field_headers(): - client = AutomaticImprovementsServiceClient( - 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 = automaticimprovements.UpdateAutomaticImprovementsRequest() - - request.automatic_improvements.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - call.return_value = automaticimprovements.AutomaticImprovements() - client.update_automatic_improvements(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', - 'automatic_improvements.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_automatic_improvements_field_headers_async(): - client = AutomaticImprovementsServiceAsyncClient( - 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 = automaticimprovements.UpdateAutomaticImprovementsRequest() - - request.automatic_improvements.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) - await client.update_automatic_improvements(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', - 'automatic_improvements.name=name_value', - ) in kw['metadata'] - - -def test_update_automatic_improvements_flattened(): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = automaticimprovements.AutomaticImprovements() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_automatic_improvements( - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].automatic_improvements - mock_val = automaticimprovements.AutomaticImprovements(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_automatic_improvements_flattened_error(): - client = AutomaticImprovementsServiceClient( - 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.update_automatic_improvements( - automaticimprovements.UpdateAutomaticImprovementsRequest(), - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_automatic_improvements_flattened_async(): - client = AutomaticImprovementsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = automaticimprovements.AutomaticImprovements() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_automatic_improvements( - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].automatic_improvements - mock_val = automaticimprovements.AutomaticImprovements(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_automatic_improvements_flattened_error_async(): - client = AutomaticImprovementsServiceAsyncClient( - 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.update_automatic_improvements( - automaticimprovements.UpdateAutomaticImprovementsRequest(), - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_automatic_improvements_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 = AutomaticImprovementsServiceClient( - 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.get_automatic_improvements in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc - - request = {} - client.get_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_automatic_improvements(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_get_automatic_improvements_rest_required_fields(request_type=automaticimprovements.GetAutomaticImprovementsRequest): - transport_class = transports.AutomaticImprovementsServiceRestTransport - - 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()).get_automatic_improvements._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_automatic_improvements._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 = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = automaticimprovements.AutomaticImprovements() - # 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 = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_automatic_improvements_rest_unset_required_fields(): - transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_automatic_improvements._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_automatic_improvements_rest_flattened(): - client = AutomaticImprovementsServiceClient( - 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 = automaticimprovements.AutomaticImprovements() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/automaticImprovements'} - - # 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 - # Convert return value to protobuf type - return_value = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(**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/accounts/v1beta/{name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) - - -def test_get_automatic_improvements_rest_flattened_error(transport: str = 'rest'): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_automatic_improvements( - automaticimprovements.GetAutomaticImprovementsRequest(), - name='name_value', - ) - - -def test_update_automatic_improvements_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 = AutomaticImprovementsServiceClient( - 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.update_automatic_improvements in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc - - request = {} - client.update_automatic_improvements(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_automatic_improvements(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_update_automatic_improvements_rest_required_fields(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): - transport_class = transports.AutomaticImprovementsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = automaticimprovements.AutomaticImprovements() - # 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': "patch", - '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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_automatic_improvements_rest_unset_required_fields(): - transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_automatic_improvements._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("automaticImprovements", "updateMask", ))) - - -def test_update_automatic_improvements_rest_flattened(): - client = AutomaticImprovementsServiceClient( - 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 = automaticimprovements.AutomaticImprovements() - - # get arguments that satisfy an http rule for this method - sample_request = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} - - # get truthy value for each flattened field - mock_args = dict( - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(**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/accounts/v1beta/{automatic_improvements.name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) - - -def test_update_automatic_improvements_rest_flattened_error(transport: str = 'rest'): - client = AutomaticImprovementsServiceClient( - 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.update_automatic_improvements( - automaticimprovements.UpdateAutomaticImprovementsRequest(), - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutomaticImprovementsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AutomaticImprovementsServiceClient( - 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 = AutomaticImprovementsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutomaticImprovementsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AutomaticImprovementsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AutomaticImprovementsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AutomaticImprovementsServiceGrpcTransport, - transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, - transports.AutomaticImprovementsServiceRestTransport, -]) -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 = AutomaticImprovementsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AutomaticImprovementsServiceClient( - 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_get_automatic_improvements_empty_call_grpc(): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - call.return_value = automaticimprovements.AutomaticImprovements() - client.get_automatic_improvements(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = automaticimprovements.GetAutomaticImprovementsRequest() - - 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_update_automatic_improvements_empty_call_grpc(): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - call.return_value = automaticimprovements.AutomaticImprovements() - client.update_automatic_improvements(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AutomaticImprovementsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AutomaticImprovementsServiceAsyncClient( - 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_get_automatic_improvements_empty_call_grpc_asyncio(): - client = AutomaticImprovementsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) - await client.get_automatic_improvements(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = automaticimprovements.GetAutomaticImprovementsRequest() - - 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_update_automatic_improvements_empty_call_grpc_asyncio(): - client = AutomaticImprovementsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) - await client.update_automatic_improvements(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AutomaticImprovementsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_automatic_improvements_rest_bad_request(request_type=automaticimprovements.GetAutomaticImprovementsRequest): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/automaticImprovements'} - 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.get_automatic_improvements(request) - - -@pytest.mark.parametrize("request_type", [ - automaticimprovements.GetAutomaticImprovementsRequest, - dict, -]) -def test_get_automatic_improvements_rest_call_success(request_type): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/automaticImprovements'} - request = request_type(**request_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 = automaticimprovements.AutomaticImprovements( - name='name_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 = automaticimprovements.AutomaticImprovements.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.get_automatic_improvements(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_automatic_improvements_rest_interceptors(null_interceptor): - transport = transports.AutomaticImprovementsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), - ) - client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements") as post, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_get_automatic_improvements") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = automaticimprovements.GetAutomaticImprovementsRequest.pb(automaticimprovements.GetAutomaticImprovementsRequest()) - 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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) - req.return_value.content = return_value - - request = automaticimprovements.GetAutomaticImprovementsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = automaticimprovements.AutomaticImprovements() - post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata - - client.get_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_automatic_improvements_rest_bad_request(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} - 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.update_automatic_improvements(request) - - -@pytest.mark.parametrize("request_type", [ - automaticimprovements.UpdateAutomaticImprovementsRequest, - dict, -]) -def test_update_automatic_improvements_rest_call_success(request_type): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} - request_init["automatic_improvements"] = {'name': 'accounts/sample1/automaticImprovements', 'item_updates': {'account_item_updates_settings': {'allow_price_updates': True, 'allow_availability_updates': True, 'allow_strict_availability_updates': True, 'allow_condition_updates': True}, 'effective_allow_price_updates': True, 'effective_allow_availability_updates': True, 'effective_allow_strict_availability_updates': True, 'effective_allow_condition_updates': True}, 'image_improvements': {'account_image_improvements_settings': {'allow_automatic_image_improvements': True}, 'effective_allow_automatic_image_improvements': True}, 'shipping_improvements': {'allow_shipping_improvements': True}} - # 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 = automaticimprovements.UpdateAutomaticImprovementsRequest.meta.fields["automatic_improvements"] - - 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["automatic_improvements"].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["automatic_improvements"][field])): - del request_init["automatic_improvements"][field][i][subfield] - else: - del request_init["automatic_improvements"][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 = automaticimprovements.AutomaticImprovements( - name='name_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 = automaticimprovements.AutomaticImprovements.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.update_automatic_improvements(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_automatic_improvements_rest_interceptors(null_interceptor): - transport = transports.AutomaticImprovementsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), - ) - client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements") as post, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_update_automatic_improvements") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = automaticimprovements.UpdateAutomaticImprovementsRequest.pb(automaticimprovements.UpdateAutomaticImprovementsRequest()) - 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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) - req.return_value.content = return_value - - request = automaticimprovements.UpdateAutomaticImprovementsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = automaticimprovements.AutomaticImprovements() - post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata - - client.update_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = AutomaticImprovementsServiceClient( - 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_get_automatic_improvements_empty_call_rest(): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - client.get_automatic_improvements(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = automaticimprovements.GetAutomaticImprovementsRequest() - - 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_update_automatic_improvements_empty_call_rest(): - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - client.update_automatic_improvements(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = automaticimprovements.UpdateAutomaticImprovementsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AutomaticImprovementsServiceGrpcTransport, - ) - -def test_automatic_improvements_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AutomaticImprovementsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_automatic_improvements_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AutomaticImprovementsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_automatic_improvements', - 'update_automatic_improvements', - ) - 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_automatic_improvements_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_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutomaticImprovementsServiceTransport( - 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_automatic_improvements_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_accounts_v1beta.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutomaticImprovementsServiceTransport() - adc.assert_called_once() - - -def test_automatic_improvements_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) - AutomaticImprovementsServiceClient() - 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.AutomaticImprovementsServiceGrpcTransport, - transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, - ], -) -def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, - transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, - transports.AutomaticImprovementsServiceRestTransport, - ], -) -def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, grpc_helpers), - (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) -def test_automatic_improvements_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_automatic_improvements_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.AutomaticImprovementsServiceRestTransport ( - 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_automatic_improvements_service_host_no_port(transport_name): - client = AutomaticImprovementsServiceClient( - 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_automatic_improvements_service_host_with_port(transport_name): - client = AutomaticImprovementsServiceClient( - 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_automatic_improvements_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AutomaticImprovementsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AutomaticImprovementsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_automatic_improvements._session - session2 = client2.transport.get_automatic_improvements._session - assert session1 != session2 - session1 = client1.transport.update_automatic_improvements._session - session2 = client2.transport.update_automatic_improvements._session - assert session1 != session2 -def test_automatic_improvements_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutomaticImprovementsServiceGrpcTransport( - 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_automatic_improvements_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutomaticImprovementsServiceGrpcAsyncIOTransport( - 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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) -def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) -def test_automatic_improvements_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_automatic_improvements_path(): - account = "squid" - expected = "accounts/{account}/automaticImprovements".format(account=account, ) - actual = AutomaticImprovementsServiceClient.automatic_improvements_path(account) - assert expected == actual - - -def test_parse_automatic_improvements_path(): - expected = { - "account": "clam", - } - path = AutomaticImprovementsServiceClient.automatic_improvements_path(**expected) - - # Check that the path construction is reversible. - actual = AutomaticImprovementsServiceClient.parse_automatic_improvements_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AutomaticImprovementsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AutomaticImprovementsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AutomaticImprovementsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AutomaticImprovementsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AutomaticImprovementsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AutomaticImprovementsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AutomaticImprovementsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AutomaticImprovementsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AutomaticImprovementsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AutomaticImprovementsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AutomaticImprovementsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AutomaticImprovementsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AutomaticImprovementsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AutomaticImprovementsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AutomaticImprovementsServiceClient.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.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: - client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AutomaticImprovementsServiceClient.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 = AutomaticImprovementsServiceClient( - 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 = AutomaticImprovementsServiceAsyncClient( - 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 = AutomaticImprovementsServiceClient( - 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 = AutomaticImprovementsServiceClient( - 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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py deleted file mode 100644 index cc178368626f..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_identity_service.py +++ /dev/null @@ -1,2876 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.business_identity_service import BusinessIdentityServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.business_identity_service import BusinessIdentityServiceClient -from google.shopping.merchant_accounts_v1beta.services.business_identity_service import transports -from google.shopping.merchant_accounts_v1beta.types import businessidentity -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 BusinessIdentityServiceClient._get_default_mtls_endpoint(None) is None - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, False) is None - assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert BusinessIdentityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert BusinessIdentityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert BusinessIdentityServiceClient._get_universe_domain(None, None) == BusinessIdentityServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient(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 = BusinessIdentityServiceClient(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", [ - (BusinessIdentityServiceClient, "grpc"), - (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), - (BusinessIdentityServiceClient, "rest"), -]) -def test_business_identity_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.BusinessIdentityServiceGrpcTransport, "grpc"), - (transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.BusinessIdentityServiceRestTransport, "rest"), -]) -def test_business_identity_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", [ - (BusinessIdentityServiceClient, "grpc"), - (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), - (BusinessIdentityServiceClient, "rest"), -]) -def test_business_identity_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_business_identity_service_client_get_transport_class(): - transport = BusinessIdentityServiceClient.get_transport_class() - available_transports = [ - transports.BusinessIdentityServiceGrpcTransport, - transports.BusinessIdentityServiceRestTransport, - ] - assert transport in available_transports - - transport = BusinessIdentityServiceClient.get_transport_class("grpc") - assert transport == transports.BusinessIdentityServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), -]) -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) -def test_business_identity_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(BusinessIdentityServiceClient, '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(BusinessIdentityServiceClient, '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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "true"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "false"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "true"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_business_identity_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", [ - BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient -]) -@mock.patch.object(BusinessIdentityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceAsyncClient)) -def test_business_identity_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", [ - BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient -]) -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) -def test_business_identity_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = BusinessIdentityServiceClient._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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), -]) -def test_business_identity_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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", None), -]) -def test_business_identity_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_business_identity_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = BusinessIdentityServiceClient( - 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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_business_identity_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", [ - businessidentity.GetBusinessIdentityRequest, - dict, -]) -def test_get_business_identity(request_type, transport: str = 'grpc'): - client = BusinessIdentityServiceClient( - 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.get_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - ) - response = client.get_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = businessidentity.GetBusinessIdentityRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN - - -def test_get_business_identity_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 = BusinessIdentityServiceClient( - 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 = businessidentity.GetBusinessIdentityRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_business_identity(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == businessidentity.GetBusinessIdentityRequest( - name='name_value', - ) - -def test_get_business_identity_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 = BusinessIdentityServiceClient( - 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.get_business_identity in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc - request = {} - client.get_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_business_identity(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_get_business_identity_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 = BusinessIdentityServiceAsyncClient( - 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.get_business_identity in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_business_identity] = mock_rpc - - request = {} - await client.get_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_business_identity(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_get_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.GetBusinessIdentityRequest): - client = BusinessIdentityServiceAsyncClient( - 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.get_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) - response = await client.get_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = businessidentity.GetBusinessIdentityRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN - - -@pytest.mark.asyncio -async def test_get_business_identity_async_from_dict(): - await test_get_business_identity_async(request_type=dict) - -def test_get_business_identity_field_headers(): - client = BusinessIdentityServiceClient( - 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 = businessidentity.GetBusinessIdentityRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - call.return_value = businessidentity.BusinessIdentity() - client.get_business_identity(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_get_business_identity_field_headers_async(): - client = BusinessIdentityServiceAsyncClient( - 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 = businessidentity.GetBusinessIdentityRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) - await client.get_business_identity(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_get_business_identity_flattened(): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessidentity.BusinessIdentity() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_business_identity( - 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_get_business_identity_flattened_error(): - client = BusinessIdentityServiceClient( - 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.get_business_identity( - businessidentity.GetBusinessIdentityRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_business_identity_flattened_async(): - client = BusinessIdentityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessidentity.BusinessIdentity() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_business_identity( - 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_get_business_identity_flattened_error_async(): - client = BusinessIdentityServiceAsyncClient( - 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.get_business_identity( - businessidentity.GetBusinessIdentityRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - businessidentity.UpdateBusinessIdentityRequest, - dict, -]) -def test_update_business_identity(request_type, transport: str = 'grpc'): - client = BusinessIdentityServiceClient( - 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.update_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - ) - response = client.update_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = businessidentity.UpdateBusinessIdentityRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN - - -def test_update_business_identity_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 = BusinessIdentityServiceClient( - 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 = businessidentity.UpdateBusinessIdentityRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_business_identity(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == businessidentity.UpdateBusinessIdentityRequest( - ) - -def test_update_business_identity_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 = BusinessIdentityServiceClient( - 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.update_business_identity in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc - request = {} - client.update_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_business_identity(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_update_business_identity_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 = BusinessIdentityServiceAsyncClient( - 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.update_business_identity in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_business_identity] = mock_rpc - - request = {} - await client.update_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_business_identity(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_update_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.UpdateBusinessIdentityRequest): - client = BusinessIdentityServiceAsyncClient( - 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.update_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) - response = await client.update_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = businessidentity.UpdateBusinessIdentityRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN - - -@pytest.mark.asyncio -async def test_update_business_identity_async_from_dict(): - await test_update_business_identity_async(request_type=dict) - -def test_update_business_identity_field_headers(): - client = BusinessIdentityServiceClient( - 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 = businessidentity.UpdateBusinessIdentityRequest() - - request.business_identity.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - call.return_value = businessidentity.BusinessIdentity() - client.update_business_identity(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', - 'business_identity.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_business_identity_field_headers_async(): - client = BusinessIdentityServiceAsyncClient( - 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 = businessidentity.UpdateBusinessIdentityRequest() - - request.business_identity.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) - await client.update_business_identity(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', - 'business_identity.name=name_value', - ) in kw['metadata'] - - -def test_update_business_identity_flattened(): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessidentity.BusinessIdentity() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_business_identity( - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_identity - mock_val = businessidentity.BusinessIdentity(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_business_identity_flattened_error(): - client = BusinessIdentityServiceClient( - 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.update_business_identity( - businessidentity.UpdateBusinessIdentityRequest(), - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_business_identity_flattened_async(): - client = BusinessIdentityServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessidentity.BusinessIdentity() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_business_identity( - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_identity - mock_val = businessidentity.BusinessIdentity(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_business_identity_flattened_error_async(): - client = BusinessIdentityServiceAsyncClient( - 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.update_business_identity( - businessidentity.UpdateBusinessIdentityRequest(), - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_business_identity_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 = BusinessIdentityServiceClient( - 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.get_business_identity in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc - - request = {} - client.get_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_business_identity(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_get_business_identity_rest_required_fields(request_type=businessidentity.GetBusinessIdentityRequest): - transport_class = transports.BusinessIdentityServiceRestTransport - - 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()).get_business_identity._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_identity._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 = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = businessidentity.BusinessIdentity() - # 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 = businessidentity.BusinessIdentity.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.get_business_identity(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_business_identity_rest_unset_required_fields(): - transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_business_identity._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_business_identity_rest_flattened(): - client = BusinessIdentityServiceClient( - 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 = businessidentity.BusinessIdentity() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/businessIdentity'} - - # 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 - # Convert return value to protobuf type - return_value = businessidentity.BusinessIdentity.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.get_business_identity(**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/accounts/v1beta/{name=accounts/*/businessIdentity}" % client.transport._host, args[1]) - - -def test_get_business_identity_rest_flattened_error(transport: str = 'rest'): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_business_identity( - businessidentity.GetBusinessIdentityRequest(), - name='name_value', - ) - - -def test_update_business_identity_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 = BusinessIdentityServiceClient( - 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.update_business_identity in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc - - request = {} - client.update_business_identity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_business_identity(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_update_business_identity_rest_required_fields(request_type=businessidentity.UpdateBusinessIdentityRequest): - transport_class = transports.BusinessIdentityServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = businessidentity.BusinessIdentity() - # 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': "patch", - '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 = businessidentity.BusinessIdentity.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.update_business_identity(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_business_identity_rest_unset_required_fields(): - transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_business_identity._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("businessIdentity", "updateMask", ))) - - -def test_update_business_identity_rest_flattened(): - client = BusinessIdentityServiceClient( - 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 = businessidentity.BusinessIdentity() - - # get arguments that satisfy an http rule for this method - sample_request = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} - - # get truthy value for each flattened field - mock_args = dict( - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = businessidentity.BusinessIdentity.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.update_business_identity(**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/accounts/v1beta/{business_identity.name=accounts/*/businessIdentity}" % client.transport._host, args[1]) - - -def test_update_business_identity_rest_flattened_error(transport: str = 'rest'): - client = BusinessIdentityServiceClient( - 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.update_business_identity( - businessidentity.UpdateBusinessIdentityRequest(), - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BusinessIdentityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.BusinessIdentityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BusinessIdentityServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.BusinessIdentityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BusinessIdentityServiceClient( - 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 = BusinessIdentityServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.BusinessIdentityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BusinessIdentityServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BusinessIdentityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = BusinessIdentityServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BusinessIdentityServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.BusinessIdentityServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.BusinessIdentityServiceGrpcTransport, - transports.BusinessIdentityServiceGrpcAsyncIOTransport, - transports.BusinessIdentityServiceRestTransport, -]) -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 = BusinessIdentityServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = BusinessIdentityServiceClient( - 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_get_business_identity_empty_call_grpc(): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - call.return_value = businessidentity.BusinessIdentity() - client.get_business_identity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessidentity.GetBusinessIdentityRequest() - - 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_update_business_identity_empty_call_grpc(): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - call.return_value = businessidentity.BusinessIdentity() - client.update_business_identity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessidentity.UpdateBusinessIdentityRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = BusinessIdentityServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = BusinessIdentityServiceAsyncClient( - 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_get_business_identity_empty_call_grpc_asyncio(): - client = BusinessIdentityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) - await client.get_business_identity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessidentity.GetBusinessIdentityRequest() - - 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_update_business_identity_empty_call_grpc_asyncio(): - client = BusinessIdentityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) - await client.update_business_identity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessidentity.UpdateBusinessIdentityRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = BusinessIdentityServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_business_identity_rest_bad_request(request_type=businessidentity.GetBusinessIdentityRequest): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessIdentity'} - 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.get_business_identity(request) - - -@pytest.mark.parametrize("request_type", [ - businessidentity.GetBusinessIdentityRequest, - dict, -]) -def test_get_business_identity_rest_call_success(request_type): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessIdentity'} - request = request_type(**request_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 = businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - ) - - # 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 = businessidentity.BusinessIdentity.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.get_business_identity(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_business_identity_rest_interceptors(null_interceptor): - transport = transports.BusinessIdentityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), - ) - client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_get_business_identity") as post, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_get_business_identity_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_get_business_identity") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = businessidentity.GetBusinessIdentityRequest.pb(businessidentity.GetBusinessIdentityRequest()) - 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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) - req.return_value.content = return_value - - request = businessidentity.GetBusinessIdentityRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = businessidentity.BusinessIdentity() - post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata - - client.get_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_business_identity_rest_bad_request(request_type=businessidentity.UpdateBusinessIdentityRequest): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} - 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.update_business_identity(request) - - -@pytest.mark.parametrize("request_type", [ - businessidentity.UpdateBusinessIdentityRequest, - dict, -]) -def test_update_business_identity_rest_call_success(request_type): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} - request_init["business_identity"] = {'name': 'accounts/sample1/businessIdentity', 'promotions_consent': 1, 'black_owned': {'identity_declaration': 1}, 'women_owned': {}, 'veteran_owned': {}, 'latino_owned': {}, 'small_business': {}} - # 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 = businessidentity.UpdateBusinessIdentityRequest.meta.fields["business_identity"] - - 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["business_identity"].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["business_identity"][field])): - del request_init["business_identity"][field][i][subfield] - else: - del request_init["business_identity"][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 = businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - ) - - # 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 = businessidentity.BusinessIdentity.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.update_business_identity(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_business_identity_rest_interceptors(null_interceptor): - transport = transports.BusinessIdentityServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), - ) - client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_update_business_identity") as post, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_update_business_identity_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_update_business_identity") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = businessidentity.UpdateBusinessIdentityRequest.pb(businessidentity.UpdateBusinessIdentityRequest()) - 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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) - req.return_value.content = return_value - - request = businessidentity.UpdateBusinessIdentityRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = businessidentity.BusinessIdentity() - post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata - - client.update_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = BusinessIdentityServiceClient( - 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_get_business_identity_empty_call_rest(): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - client.get_business_identity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessidentity.GetBusinessIdentityRequest() - - 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_update_business_identity_empty_call_rest(): - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - client.update_business_identity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessidentity.UpdateBusinessIdentityRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.BusinessIdentityServiceGrpcTransport, - ) - -def test_business_identity_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BusinessIdentityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_business_identity_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.BusinessIdentityServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_business_identity', - 'update_business_identity', - ) - 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_business_identity_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_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BusinessIdentityServiceTransport( - 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_business_identity_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_accounts_v1beta.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BusinessIdentityServiceTransport() - adc.assert_called_once() - - -def test_business_identity_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) - BusinessIdentityServiceClient() - 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.BusinessIdentityServiceGrpcTransport, - transports.BusinessIdentityServiceGrpcAsyncIOTransport, - ], -) -def test_business_identity_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.BusinessIdentityServiceGrpcTransport, - transports.BusinessIdentityServiceGrpcAsyncIOTransport, - transports.BusinessIdentityServiceRestTransport, - ], -) -def test_business_identity_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.BusinessIdentityServiceGrpcTransport, grpc_helpers), - (transports.BusinessIdentityServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) -def test_business_identity_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_business_identity_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.BusinessIdentityServiceRestTransport ( - 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_business_identity_service_host_no_port(transport_name): - client = BusinessIdentityServiceClient( - 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_business_identity_service_host_with_port(transport_name): - client = BusinessIdentityServiceClient( - 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_business_identity_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = BusinessIdentityServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = BusinessIdentityServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_business_identity._session - session2 = client2.transport.get_business_identity._session - assert session1 != session2 - session1 = client1.transport.update_business_identity._session - session2 = client2.transport.update_business_identity._session - assert session1 != session2 -def test_business_identity_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.BusinessIdentityServiceGrpcTransport( - 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_business_identity_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.BusinessIdentityServiceGrpcAsyncIOTransport( - 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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) -def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) -def test_business_identity_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_business_identity_path(): - account = "squid" - expected = "accounts/{account}/businessIdentity".format(account=account, ) - actual = BusinessIdentityServiceClient.business_identity_path(account) - assert expected == actual - - -def test_parse_business_identity_path(): - expected = { - "account": "clam", - } - path = BusinessIdentityServiceClient.business_identity_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessIdentityServiceClient.parse_business_identity_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = BusinessIdentityServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = BusinessIdentityServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessIdentityServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = BusinessIdentityServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = BusinessIdentityServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessIdentityServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = BusinessIdentityServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = BusinessIdentityServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessIdentityServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = BusinessIdentityServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = BusinessIdentityServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessIdentityServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = BusinessIdentityServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = BusinessIdentityServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessIdentityServiceClient.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.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: - client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = BusinessIdentityServiceClient.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 = BusinessIdentityServiceClient( - 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 = BusinessIdentityServiceAsyncClient( - 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 = BusinessIdentityServiceClient( - 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 = BusinessIdentityServiceClient( - 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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py deleted file mode 100644 index eccedd1d0cee..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_business_info_service.py +++ /dev/null @@ -1,2894 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.business_info_service import BusinessInfoServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.business_info_service import BusinessInfoServiceClient -from google.shopping.merchant_accounts_v1beta.services.business_info_service import transports -from google.shopping.merchant_accounts_v1beta.types import businessinfo -from google.shopping.merchant_accounts_v1beta.types import customerservice -from google.shopping.merchant_accounts_v1beta.types import phoneverificationstate -from google.type import phone_number_pb2 # type: ignore -from google.type import postal_address_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 BusinessInfoServiceClient._get_default_mtls_endpoint(None) is None - assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert BusinessInfoServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - BusinessInfoServiceClient._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 BusinessInfoServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - BusinessInfoServiceClient._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 BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, False) is None - assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert BusinessInfoServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessInfoServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert BusinessInfoServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert BusinessInfoServiceClient._get_universe_domain(None, None) == BusinessInfoServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - BusinessInfoServiceClient._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 = BusinessInfoServiceClient(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 = BusinessInfoServiceClient(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", [ - (BusinessInfoServiceClient, "grpc"), - (BusinessInfoServiceAsyncClient, "grpc_asyncio"), - (BusinessInfoServiceClient, "rest"), -]) -def test_business_info_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.BusinessInfoServiceGrpcTransport, "grpc"), - (transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.BusinessInfoServiceRestTransport, "rest"), -]) -def test_business_info_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", [ - (BusinessInfoServiceClient, "grpc"), - (BusinessInfoServiceAsyncClient, "grpc_asyncio"), - (BusinessInfoServiceClient, "rest"), -]) -def test_business_info_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_business_info_service_client_get_transport_class(): - transport = BusinessInfoServiceClient.get_transport_class() - available_transports = [ - transports.BusinessInfoServiceGrpcTransport, - transports.BusinessInfoServiceRestTransport, - ] - assert transport in available_transports - - transport = BusinessInfoServiceClient.get_transport_class("grpc") - assert transport == transports.BusinessInfoServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), -]) -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) -def test_business_info_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(BusinessInfoServiceClient, '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(BusinessInfoServiceClient, '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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "true"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "false"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "true"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_business_info_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", [ - BusinessInfoServiceClient, BusinessInfoServiceAsyncClient -]) -@mock.patch.object(BusinessInfoServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceAsyncClient)) -def test_business_info_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", [ - BusinessInfoServiceClient, BusinessInfoServiceAsyncClient -]) -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) -def test_business_info_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = BusinessInfoServiceClient._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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), -]) -def test_business_info_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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", None), -]) -def test_business_info_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_business_info_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = BusinessInfoServiceClient( - 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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_business_info_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", [ - businessinfo.GetBusinessInfoRequest, - dict, -]) -def test_get_business_info(request_type, transport: str = 'grpc'): - client = BusinessInfoServiceClient( - 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.get_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - ) - response = client.get_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = businessinfo.GetBusinessInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' - - -def test_get_business_info_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 = BusinessInfoServiceClient( - 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 = businessinfo.GetBusinessInfoRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_business_info(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == businessinfo.GetBusinessInfoRequest( - name='name_value', - ) - -def test_get_business_info_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 = BusinessInfoServiceClient( - 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.get_business_info in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc - request = {} - client.get_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_business_info(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_get_business_info_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 = BusinessInfoServiceAsyncClient( - 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.get_business_info in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_business_info] = mock_rpc - - request = {} - await client.get_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_business_info(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_get_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.GetBusinessInfoRequest): - client = BusinessInfoServiceAsyncClient( - 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.get_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) - response = await client.get_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = businessinfo.GetBusinessInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' - - -@pytest.mark.asyncio -async def test_get_business_info_async_from_dict(): - await test_get_business_info_async(request_type=dict) - -def test_get_business_info_field_headers(): - client = BusinessInfoServiceClient( - 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 = businessinfo.GetBusinessInfoRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - call.return_value = businessinfo.BusinessInfo() - client.get_business_info(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_get_business_info_field_headers_async(): - client = BusinessInfoServiceAsyncClient( - 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 = businessinfo.GetBusinessInfoRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) - await client.get_business_info(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_get_business_info_flattened(): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessinfo.BusinessInfo() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_business_info( - 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_get_business_info_flattened_error(): - client = BusinessInfoServiceClient( - 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.get_business_info( - businessinfo.GetBusinessInfoRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_business_info_flattened_async(): - client = BusinessInfoServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessinfo.BusinessInfo() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_business_info( - 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_get_business_info_flattened_error_async(): - client = BusinessInfoServiceAsyncClient( - 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.get_business_info( - businessinfo.GetBusinessInfoRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - businessinfo.UpdateBusinessInfoRequest, - dict, -]) -def test_update_business_info(request_type, transport: str = 'grpc'): - client = BusinessInfoServiceClient( - 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.update_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - ) - response = client.update_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = businessinfo.UpdateBusinessInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' - - -def test_update_business_info_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 = BusinessInfoServiceClient( - 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 = businessinfo.UpdateBusinessInfoRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_business_info(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == businessinfo.UpdateBusinessInfoRequest( - ) - -def test_update_business_info_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 = BusinessInfoServiceClient( - 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.update_business_info in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc - request = {} - client.update_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_business_info(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_update_business_info_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 = BusinessInfoServiceAsyncClient( - 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.update_business_info in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_business_info] = mock_rpc - - request = {} - await client.update_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_business_info(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_update_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.UpdateBusinessInfoRequest): - client = BusinessInfoServiceAsyncClient( - 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.update_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) - response = await client.update_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = businessinfo.UpdateBusinessInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' - - -@pytest.mark.asyncio -async def test_update_business_info_async_from_dict(): - await test_update_business_info_async(request_type=dict) - -def test_update_business_info_field_headers(): - client = BusinessInfoServiceClient( - 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 = businessinfo.UpdateBusinessInfoRequest() - - request.business_info.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - call.return_value = businessinfo.BusinessInfo() - client.update_business_info(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', - 'business_info.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_business_info_field_headers_async(): - client = BusinessInfoServiceAsyncClient( - 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 = businessinfo.UpdateBusinessInfoRequest() - - request.business_info.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) - await client.update_business_info(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', - 'business_info.name=name_value', - ) in kw['metadata'] - - -def test_update_business_info_flattened(): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessinfo.BusinessInfo() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_business_info( - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_info - mock_val = businessinfo.BusinessInfo(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_business_info_flattened_error(): - client = BusinessInfoServiceClient( - 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.update_business_info( - businessinfo.UpdateBusinessInfoRequest(), - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_business_info_flattened_async(): - client = BusinessInfoServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = businessinfo.BusinessInfo() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_business_info( - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].business_info - mock_val = businessinfo.BusinessInfo(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_business_info_flattened_error_async(): - client = BusinessInfoServiceAsyncClient( - 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.update_business_info( - businessinfo.UpdateBusinessInfoRequest(), - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_business_info_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 = BusinessInfoServiceClient( - 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.get_business_info in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc - - request = {} - client.get_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_business_info(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_get_business_info_rest_required_fields(request_type=businessinfo.GetBusinessInfoRequest): - transport_class = transports.BusinessInfoServiceRestTransport - - 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()).get_business_info._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_info._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 = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = businessinfo.BusinessInfo() - # 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 = businessinfo.BusinessInfo.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.get_business_info(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_business_info_rest_unset_required_fields(): - transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_business_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_business_info_rest_flattened(): - client = BusinessInfoServiceClient( - 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 = businessinfo.BusinessInfo() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/businessInfo'} - - # 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 - # Convert return value to protobuf type - return_value = businessinfo.BusinessInfo.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.get_business_info(**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/accounts/v1beta/{name=accounts/*/businessInfo}" % client.transport._host, args[1]) - - -def test_get_business_info_rest_flattened_error(transport: str = 'rest'): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_business_info( - businessinfo.GetBusinessInfoRequest(), - name='name_value', - ) - - -def test_update_business_info_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 = BusinessInfoServiceClient( - 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.update_business_info in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc - - request = {} - client.update_business_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_business_info(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_update_business_info_rest_required_fields(request_type=businessinfo.UpdateBusinessInfoRequest): - transport_class = transports.BusinessInfoServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = businessinfo.BusinessInfo() - # 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': "patch", - '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 = businessinfo.BusinessInfo.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.update_business_info(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_business_info_rest_unset_required_fields(): - transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_business_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("businessInfo", "updateMask", ))) - - -def test_update_business_info_rest_flattened(): - client = BusinessInfoServiceClient( - 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 = businessinfo.BusinessInfo() - - # get arguments that satisfy an http rule for this method - sample_request = {'business_info': {'name': 'accounts/sample1/businessInfo'}} - - # get truthy value for each flattened field - mock_args = dict( - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = businessinfo.BusinessInfo.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.update_business_info(**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/accounts/v1beta/{business_info.name=accounts/*/businessInfo}" % client.transport._host, args[1]) - - -def test_update_business_info_rest_flattened_error(transport: str = 'rest'): - client = BusinessInfoServiceClient( - 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.update_business_info( - businessinfo.UpdateBusinessInfoRequest(), - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BusinessInfoServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.BusinessInfoServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BusinessInfoServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.BusinessInfoServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BusinessInfoServiceClient( - 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 = BusinessInfoServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.BusinessInfoServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BusinessInfoServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BusinessInfoServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = BusinessInfoServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BusinessInfoServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.BusinessInfoServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.BusinessInfoServiceGrpcTransport, - transports.BusinessInfoServiceGrpcAsyncIOTransport, - transports.BusinessInfoServiceRestTransport, -]) -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 = BusinessInfoServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = BusinessInfoServiceClient( - 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_get_business_info_empty_call_grpc(): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - call.return_value = businessinfo.BusinessInfo() - client.get_business_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessinfo.GetBusinessInfoRequest() - - 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_update_business_info_empty_call_grpc(): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - call.return_value = businessinfo.BusinessInfo() - client.update_business_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessinfo.UpdateBusinessInfoRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = BusinessInfoServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = BusinessInfoServiceAsyncClient( - 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_get_business_info_empty_call_grpc_asyncio(): - client = BusinessInfoServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) - await client.get_business_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessinfo.GetBusinessInfoRequest() - - 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_update_business_info_empty_call_grpc_asyncio(): - client = BusinessInfoServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) - await client.update_business_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessinfo.UpdateBusinessInfoRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = BusinessInfoServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_business_info_rest_bad_request(request_type=businessinfo.GetBusinessInfoRequest): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessInfo'} - 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.get_business_info(request) - - -@pytest.mark.parametrize("request_type", [ - businessinfo.GetBusinessInfoRequest, - dict, -]) -def test_get_business_info_rest_call_success(request_type): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessInfo'} - request = request_type(**request_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 = businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_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 = businessinfo.BusinessInfo.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.get_business_info(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_business_info_rest_interceptors(null_interceptor): - transport = transports.BusinessInfoServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), - ) - client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_get_business_info") as post, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_get_business_info_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_get_business_info") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = businessinfo.GetBusinessInfoRequest.pb(businessinfo.GetBusinessInfoRequest()) - 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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) - req.return_value.content = return_value - - request = businessinfo.GetBusinessInfoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = businessinfo.BusinessInfo() - post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata - - client.get_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_business_info_rest_bad_request(request_type=businessinfo.UpdateBusinessInfoRequest): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} - 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.update_business_info(request) - - -@pytest.mark.parametrize("request_type", [ - businessinfo.UpdateBusinessInfoRequest, - dict, -]) -def test_update_business_info_rest_call_success(request_type): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} - request_init["business_info"] = {'name': 'accounts/sample1/businessInfo', 'address': {'revision': 879, 'region_code': 'region_code_value', 'language_code': 'language_code_value', 'postal_code': 'postal_code_value', 'sorting_code': 'sorting_code_value', 'administrative_area': 'administrative_area_value', 'locality': 'locality_value', 'sublocality': 'sublocality_value', 'address_lines': ['address_lines_value1', 'address_lines_value2'], 'recipients': ['recipients_value1', 'recipients_value2'], 'organization': 'organization_value'}, 'phone': {'e164_number': 'e164_number_value', 'short_code': {'region_code': 'region_code_value', 'number': 'number_value'}, 'extension': 'extension_value'}, 'phone_verification_state': 1, 'customer_service': {'uri': 'uri_value', 'email': 'email_value', 'phone': {}}, 'korean_business_registration_number': 'korean_business_registration_number_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 = businessinfo.UpdateBusinessInfoRequest.meta.fields["business_info"] - - 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["business_info"].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["business_info"][field])): - del request_init["business_info"][field][i][subfield] - else: - del request_init["business_info"][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 = businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_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 = businessinfo.BusinessInfo.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.update_business_info(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_business_info_rest_interceptors(null_interceptor): - transport = transports.BusinessInfoServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), - ) - client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_update_business_info") as post, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_update_business_info_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_update_business_info") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = businessinfo.UpdateBusinessInfoRequest.pb(businessinfo.UpdateBusinessInfoRequest()) - 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 = businessinfo.BusinessInfo.to_json(businessinfo.BusinessInfo()) - req.return_value.content = return_value - - request = businessinfo.UpdateBusinessInfoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = businessinfo.BusinessInfo() - post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata - - client.update_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = BusinessInfoServiceClient( - 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_get_business_info_empty_call_rest(): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - client.get_business_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessinfo.GetBusinessInfoRequest() - - 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_update_business_info_empty_call_rest(): - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - client.update_business_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = businessinfo.UpdateBusinessInfoRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.BusinessInfoServiceGrpcTransport, - ) - -def test_business_info_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BusinessInfoServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_business_info_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.BusinessInfoServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_business_info', - 'update_business_info', - ) - 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_business_info_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_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BusinessInfoServiceTransport( - 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_business_info_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_accounts_v1beta.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.BusinessInfoServiceTransport() - adc.assert_called_once() - - -def test_business_info_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) - BusinessInfoServiceClient() - 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.BusinessInfoServiceGrpcTransport, - transports.BusinessInfoServiceGrpcAsyncIOTransport, - ], -) -def test_business_info_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.BusinessInfoServiceGrpcTransport, - transports.BusinessInfoServiceGrpcAsyncIOTransport, - transports.BusinessInfoServiceRestTransport, - ], -) -def test_business_info_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.BusinessInfoServiceGrpcTransport, grpc_helpers), - (transports.BusinessInfoServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) -def test_business_info_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_business_info_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.BusinessInfoServiceRestTransport ( - 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_business_info_service_host_no_port(transport_name): - client = BusinessInfoServiceClient( - 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_business_info_service_host_with_port(transport_name): - client = BusinessInfoServiceClient( - 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_business_info_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = BusinessInfoServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = BusinessInfoServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_business_info._session - session2 = client2.transport.get_business_info._session - assert session1 != session2 - session1 = client1.transport.update_business_info._session - session2 = client2.transport.update_business_info._session - assert session1 != session2 -def test_business_info_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.BusinessInfoServiceGrpcTransport( - 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_business_info_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.BusinessInfoServiceGrpcAsyncIOTransport( - 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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) -def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) -def test_business_info_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_business_info_path(): - account = "squid" - expected = "accounts/{account}/businessInfo".format(account=account, ) - actual = BusinessInfoServiceClient.business_info_path(account) - assert expected == actual - - -def test_parse_business_info_path(): - expected = { - "account": "clam", - } - path = BusinessInfoServiceClient.business_info_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessInfoServiceClient.parse_business_info_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = BusinessInfoServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = BusinessInfoServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessInfoServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = BusinessInfoServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = BusinessInfoServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessInfoServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = BusinessInfoServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = BusinessInfoServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessInfoServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = BusinessInfoServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = BusinessInfoServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessInfoServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = BusinessInfoServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = BusinessInfoServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = BusinessInfoServiceClient.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.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: - client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = BusinessInfoServiceClient.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 = BusinessInfoServiceClient( - 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 = BusinessInfoServiceAsyncClient( - 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 = BusinessInfoServiceClient( - 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 = BusinessInfoServiceClient( - 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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py deleted file mode 100644 index 9df5ec1b5213..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_checkout_settings_service.py +++ /dev/null @@ -1,4334 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service import CheckoutSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service import CheckoutSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.checkout_settings_service import transports -from google.shopping.merchant_accounts_v1beta.types import checkoutsettings -from google.shopping.type.types import types -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 CheckoutSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, False) is None - assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert CheckoutSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert CheckoutSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert CheckoutSettingsServiceClient._get_universe_domain(None, None) == CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient(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 = CheckoutSettingsServiceClient(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", [ - (CheckoutSettingsServiceClient, "grpc"), - (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), - (CheckoutSettingsServiceClient, "rest"), -]) -def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, "grpc"), - (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.CheckoutSettingsServiceRestTransport, "rest"), -]) -def test_checkout_settings_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", [ - (CheckoutSettingsServiceClient, "grpc"), - (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), - (CheckoutSettingsServiceClient, "rest"), -]) -def test_checkout_settings_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_checkout_settings_service_client_get_transport_class(): - transport = CheckoutSettingsServiceClient.get_transport_class() - available_transports = [ - transports.CheckoutSettingsServiceGrpcTransport, - transports.CheckoutSettingsServiceRestTransport, - ] - assert transport in available_transports - - transport = CheckoutSettingsServiceClient.get_transport_class("grpc") - assert transport == transports.CheckoutSettingsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) -def test_checkout_settings_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(CheckoutSettingsServiceClient, '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(CheckoutSettingsServiceClient, '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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "true"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "false"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "true"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_checkout_settings_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", [ - CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient -]) -@mock.patch.object(CheckoutSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceAsyncClient)) -def test_checkout_settings_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", [ - CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient -]) -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) -def test_checkout_settings_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = CheckoutSettingsServiceClient._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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), -]) -def test_checkout_settings_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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", None), -]) -def test_checkout_settings_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_checkout_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CheckoutSettingsServiceClient( - 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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_checkout_settings_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", [ - checkoutsettings.GetCheckoutSettingsRequest, - dict, -]) -def test_get_checkout_settings(request_type, transport: str = 'grpc'): - client = CheckoutSettingsServiceClient( - 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.get_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - ) - response = client.get_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = checkoutsettings.GetCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( - 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 = checkoutsettings.GetCheckoutSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_checkout_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == checkoutsettings.GetCheckoutSettingsRequest( - name='name_value', - ) - -def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( - 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.get_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc - request = {} - client.get_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_checkout_settings(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_get_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( - 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.get_checkout_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_checkout_settings] = mock_rpc - - request = {} - await client.get_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_checkout_settings(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_get_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.GetCheckoutSettingsRequest): - client = CheckoutSettingsServiceAsyncClient( - 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.get_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) - response = await client.get_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = checkoutsettings.GetCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -@pytest.mark.asyncio -async def test_get_checkout_settings_async_from_dict(): - await test_get_checkout_settings_async(request_type=dict) - -def test_get_checkout_settings_field_headers(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.GetCheckoutSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - call.return_value = checkoutsettings.CheckoutSettings() - client.get_checkout_settings(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_get_checkout_settings_field_headers_async(): - client = CheckoutSettingsServiceAsyncClient( - 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 = checkoutsettings.GetCheckoutSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) - await client.get_checkout_settings(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_get_checkout_settings_flattened(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_checkout_settings( - 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_get_checkout_settings_flattened_error(): - client = CheckoutSettingsServiceClient( - 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.get_checkout_settings( - checkoutsettings.GetCheckoutSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_checkout_settings_flattened_async(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_checkout_settings( - 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_get_checkout_settings_flattened_error_async(): - client = CheckoutSettingsServiceAsyncClient( - 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.get_checkout_settings( - checkoutsettings.GetCheckoutSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.CreateCheckoutSettingsRequest, - dict, -]) -def test_create_checkout_settings(request_type, transport: str = 'grpc'): - client = CheckoutSettingsServiceClient( - 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.create_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - ) - response = client.create_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = checkoutsettings.CreateCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( - 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 = checkoutsettings.CreateCheckoutSettingsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_checkout_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == checkoutsettings.CreateCheckoutSettingsRequest( - parent='parent_value', - ) - -def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( - 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.create_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc - request = {} - client.create_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_checkout_settings(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_create_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( - 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.create_checkout_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_checkout_settings] = mock_rpc - - request = {} - await client.create_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_checkout_settings(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_create_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.CreateCheckoutSettingsRequest): - client = CheckoutSettingsServiceAsyncClient( - 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.create_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) - response = await client.create_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = checkoutsettings.CreateCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -@pytest.mark.asyncio -async def test_create_checkout_settings_async_from_dict(): - await test_create_checkout_settings_async(request_type=dict) - -def test_create_checkout_settings_field_headers(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.CreateCheckoutSettingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - call.return_value = checkoutsettings.CheckoutSettings() - client.create_checkout_settings(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_create_checkout_settings_field_headers_async(): - client = CheckoutSettingsServiceAsyncClient( - 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 = checkoutsettings.CreateCheckoutSettingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) - await client.create_checkout_settings(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_create_checkout_settings_flattened(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_checkout_settings( - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') - assert arg == mock_val - - -def test_create_checkout_settings_flattened_error(): - client = CheckoutSettingsServiceClient( - 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.create_checkout_settings( - checkoutsettings.CreateCheckoutSettingsRequest(), - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_checkout_settings_flattened_async(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_checkout_settings( - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_checkout_settings_flattened_error_async(): - client = CheckoutSettingsServiceAsyncClient( - 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.create_checkout_settings( - checkoutsettings.CreateCheckoutSettingsRequest(), - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.UpdateCheckoutSettingsRequest, - dict, -]) -def test_update_checkout_settings(request_type, transport: str = 'grpc'): - client = CheckoutSettingsServiceClient( - 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.update_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - ) - response = client.update_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = checkoutsettings.UpdateCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( - 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 = checkoutsettings.UpdateCheckoutSettingsRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_checkout_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == checkoutsettings.UpdateCheckoutSettingsRequest( - ) - -def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( - 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.update_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc - request = {} - client.update_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_checkout_settings(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_update_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( - 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.update_checkout_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_checkout_settings] = mock_rpc - - request = {} - await client.update_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_checkout_settings(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_update_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.UpdateCheckoutSettingsRequest): - client = CheckoutSettingsServiceAsyncClient( - 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.update_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) - response = await client.update_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = checkoutsettings.UpdateCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -@pytest.mark.asyncio -async def test_update_checkout_settings_async_from_dict(): - await test_update_checkout_settings_async(request_type=dict) - -def test_update_checkout_settings_field_headers(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.UpdateCheckoutSettingsRequest() - - request.checkout_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - call.return_value = checkoutsettings.CheckoutSettings() - client.update_checkout_settings(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', - 'checkout_settings.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_checkout_settings_field_headers_async(): - client = CheckoutSettingsServiceAsyncClient( - 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 = checkoutsettings.UpdateCheckoutSettingsRequest() - - request.checkout_settings.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) - await client.update_checkout_settings(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', - 'checkout_settings.name=name_value', - ) in kw['metadata'] - - -def test_update_checkout_settings_flattened(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_checkout_settings( - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_checkout_settings_flattened_error(): - client = CheckoutSettingsServiceClient( - 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.update_checkout_settings( - checkoutsettings.UpdateCheckoutSettingsRequest(), - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_checkout_settings_flattened_async(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = checkoutsettings.CheckoutSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_checkout_settings( - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_checkout_settings_flattened_error_async(): - client = CheckoutSettingsServiceAsyncClient( - 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.update_checkout_settings( - checkoutsettings.UpdateCheckoutSettingsRequest(), - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.DeleteCheckoutSettingsRequest, - dict, -]) -def test_delete_checkout_settings(request_type, transport: str = 'grpc'): - client = CheckoutSettingsServiceClient( - 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_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = checkoutsettings.DeleteCheckoutSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( - 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 = checkoutsettings.DeleteCheckoutSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_checkout_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == checkoutsettings.DeleteCheckoutSettingsRequest( - name='name_value', - ) - -def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( - 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_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_checkout_settings] = mock_rpc - request = {} - client.delete_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_checkout_settings(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_checkout_settings_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 = CheckoutSettingsServiceAsyncClient( - 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_checkout_settings 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_checkout_settings] = mock_rpc - - request = {} - await client.delete_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_checkout_settings(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_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.DeleteCheckoutSettingsRequest): - client = CheckoutSettingsServiceAsyncClient( - 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_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = checkoutsettings.DeleteCheckoutSettingsRequest() - 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_checkout_settings_async_from_dict(): - await test_delete_checkout_settings_async(request_type=dict) - -def test_delete_checkout_settings_field_headers(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.DeleteCheckoutSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: - call.return_value = None - client.delete_checkout_settings(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_checkout_settings_field_headers_async(): - client = CheckoutSettingsServiceAsyncClient( - 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 = checkoutsettings.DeleteCheckoutSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_checkout_settings(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_checkout_settings_flattened(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__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_checkout_settings( - 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_checkout_settings_flattened_error(): - client = CheckoutSettingsServiceClient( - 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_checkout_settings( - checkoutsettings.DeleteCheckoutSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_checkout_settings_flattened_async(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__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_checkout_settings( - 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_checkout_settings_flattened_error_async(): - client = CheckoutSettingsServiceAsyncClient( - 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_checkout_settings( - checkoutsettings.DeleteCheckoutSettingsRequest(), - name='name_value', - ) - - -def test_get_checkout_settings_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 = CheckoutSettingsServiceClient( - 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.get_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc - - request = {} - client.get_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_checkout_settings(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_get_checkout_settings_rest_required_fields(request_type=checkoutsettings.GetCheckoutSettingsRequest): - transport_class = transports.CheckoutSettingsServiceRestTransport - - 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()).get_checkout_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_checkout_settings._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 = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = checkoutsettings.CheckoutSettings() - # 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 = checkoutsettings.CheckoutSettings.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.get_checkout_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_checkout_settings_rest_flattened(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.CheckoutSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} - - # 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 - # Convert return value to protobuf type - return_value = checkoutsettings.CheckoutSettings.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.get_checkout_settings(**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/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) - - -def test_get_checkout_settings_rest_flattened_error(transport: str = 'rest'): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_checkout_settings( - checkoutsettings.GetCheckoutSettingsRequest(), - name='name_value', - ) - - -def test_create_checkout_settings_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 = CheckoutSettingsServiceClient( - 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.create_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc - - request = {} - client.create_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_checkout_settings(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_create_checkout_settings_rest_required_fields(request_type=checkoutsettings.CreateCheckoutSettingsRequest): - transport_class = transports.CheckoutSettingsServiceRestTransport - - 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()).create_checkout_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_checkout_settings._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 = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = checkoutsettings.CheckoutSettings() - # 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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "checkoutSettings", ))) - - -def test_create_checkout_settings_rest_flattened(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.CheckoutSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/programs/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(**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/accounts/v1beta/{parent=accounts/*/programs/*}/checkoutSettings" % client.transport._host, args[1]) - - -def test_create_checkout_settings_rest_flattened_error(transport: str = 'rest'): - client = CheckoutSettingsServiceClient( - 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.create_checkout_settings( - checkoutsettings.CreateCheckoutSettingsRequest(), - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - ) - - -def test_update_checkout_settings_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 = CheckoutSettingsServiceClient( - 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.update_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc - - request = {} - client.update_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_checkout_settings(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_update_checkout_settings_rest_required_fields(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): - transport_class = transports.CheckoutSettingsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = checkoutsettings.CheckoutSettings() - # 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': "patch", - '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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("checkoutSettings", "updateMask", ))) - - -def test_update_checkout_settings_rest_flattened(): - client = CheckoutSettingsServiceClient( - 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 = checkoutsettings.CheckoutSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} - - # get truthy value for each flattened field - mock_args = dict( - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(**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/accounts/v1beta/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) - - -def test_update_checkout_settings_rest_flattened_error(transport: str = 'rest'): - client = CheckoutSettingsServiceClient( - 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.update_checkout_settings( - checkoutsettings.UpdateCheckoutSettingsRequest(), - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_checkout_settings_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 = CheckoutSettingsServiceClient( - 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_checkout_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_checkout_settings] = mock_rpc - - request = {} - client.delete_checkout_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_checkout_settings(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_checkout_settings_rest_required_fields(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): - transport_class = transports.CheckoutSettingsServiceRestTransport - - 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_checkout_settings._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_checkout_settings._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 = CheckoutSettingsServiceClient( - 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_checkout_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_checkout_settings_rest_flattened(): - client = CheckoutSettingsServiceClient( - 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/programs/sample2/checkoutSettings'} - - # 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_checkout_settings(**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/accounts/v1beta/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) - - -def test_delete_checkout_settings_rest_flattened_error(transport: str = 'rest'): - client = CheckoutSettingsServiceClient( - 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_checkout_settings( - checkoutsettings.DeleteCheckoutSettingsRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CheckoutSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CheckoutSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CheckoutSettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CheckoutSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CheckoutSettingsServiceClient( - 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 = CheckoutSettingsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CheckoutSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CheckoutSettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CheckoutSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CheckoutSettingsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CheckoutSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CheckoutSettingsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CheckoutSettingsServiceGrpcTransport, - transports.CheckoutSettingsServiceGrpcAsyncIOTransport, - transports.CheckoutSettingsServiceRestTransport, -]) -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 = CheckoutSettingsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = CheckoutSettingsServiceClient( - 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_get_checkout_settings_empty_call_grpc(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - call.return_value = checkoutsettings.CheckoutSettings() - client.get_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.GetCheckoutSettingsRequest() - - 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_create_checkout_settings_empty_call_grpc(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - call.return_value = checkoutsettings.CheckoutSettings() - client.create_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.CreateCheckoutSettingsRequest() - - 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_update_checkout_settings_empty_call_grpc(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - call.return_value = checkoutsettings.CheckoutSettings() - client.update_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() - - 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_checkout_settings_empty_call_grpc(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: - call.return_value = None - client.delete_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = CheckoutSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = CheckoutSettingsServiceAsyncClient( - 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_get_checkout_settings_empty_call_grpc_asyncio(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) - await client.get_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.GetCheckoutSettingsRequest() - - 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_create_checkout_settings_empty_call_grpc_asyncio(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) - await client.create_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.CreateCheckoutSettingsRequest() - - 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_update_checkout_settings_empty_call_grpc_asyncio(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) - await client.update_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() - - 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_checkout_settings_empty_call_grpc_asyncio(): - client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = CheckoutSettingsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_checkout_settings_rest_bad_request(request_type=checkoutsettings.GetCheckoutSettingsRequest): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} - 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.get_checkout_settings(request) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.GetCheckoutSettingsRequest, - dict, -]) -def test_get_checkout_settings_rest_call_success(request_type): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} - request = request_type(**request_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 = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - ) - - # 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 = checkoutsettings.CheckoutSettings.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.get_checkout_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_checkout_settings_rest_interceptors(null_interceptor): - transport = transports.CheckoutSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) - client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings") as post, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_get_checkout_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = checkoutsettings.GetCheckoutSettingsRequest.pb(checkoutsettings.GetCheckoutSettingsRequest()) - 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) - req.return_value.content = return_value - - request = checkoutsettings.GetCheckoutSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = checkoutsettings.CheckoutSettings() - post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata - - client.get_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_checkout_settings_rest_bad_request(request_type=checkoutsettings.CreateCheckoutSettingsRequest): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/programs/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.create_checkout_settings(request) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.CreateCheckoutSettingsRequest, - dict, -]) -def test_create_checkout_settings_rest_call_success(request_type): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/programs/sample2'} - request_init["checkout_settings"] = {'name': 'name_value', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 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 = checkoutsettings.CreateCheckoutSettingsRequest.meta.fields["checkout_settings"] - - 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["checkout_settings"].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["checkout_settings"][field])): - del request_init["checkout_settings"][field][i][subfield] - else: - del request_init["checkout_settings"][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 = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - ) - - # 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 = checkoutsettings.CheckoutSettings.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.create_checkout_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_checkout_settings_rest_interceptors(null_interceptor): - transport = transports.CheckoutSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) - client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings") as post, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_create_checkout_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = checkoutsettings.CreateCheckoutSettingsRequest.pb(checkoutsettings.CreateCheckoutSettingsRequest()) - 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) - req.return_value.content = return_value - - request = checkoutsettings.CreateCheckoutSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = checkoutsettings.CheckoutSettings() - post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata - - client.create_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_checkout_settings_rest_bad_request(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} - 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.update_checkout_settings(request) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.UpdateCheckoutSettingsRequest, - dict, -]) -def test_update_checkout_settings_rest_call_success(request_type): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} - request_init["checkout_settings"] = {'name': 'accounts/sample1/programs/sample2/checkoutSettings', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 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 = checkoutsettings.UpdateCheckoutSettingsRequest.meta.fields["checkout_settings"] - - 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["checkout_settings"].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["checkout_settings"][field])): - del request_init["checkout_settings"][field][i][subfield] - else: - del request_init["checkout_settings"][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 = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - ) - - # 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 = checkoutsettings.CheckoutSettings.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.update_checkout_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_checkout_settings_rest_interceptors(null_interceptor): - transport = transports.CheckoutSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) - client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings") as post, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_update_checkout_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = checkoutsettings.UpdateCheckoutSettingsRequest.pb(checkoutsettings.UpdateCheckoutSettingsRequest()) - 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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) - req.return_value.content = return_value - - request = checkoutsettings.UpdateCheckoutSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = checkoutsettings.CheckoutSettings() - post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata - - client.update_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_checkout_settings_rest_bad_request(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} - 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_checkout_settings(request) - - -@pytest.mark.parametrize("request_type", [ - checkoutsettings.DeleteCheckoutSettingsRequest, - dict, -]) -def test_delete_checkout_settings_rest_call_success(request_type): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} - request = request_type(**request_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_checkout_settings(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_checkout_settings_rest_interceptors(null_interceptor): - transport = transports.CheckoutSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) - client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "pre_delete_checkout_settings") as pre: - pre.assert_not_called() - pb_message = checkoutsettings.DeleteCheckoutSettingsRequest.pb(checkoutsettings.DeleteCheckoutSettingsRequest()) - 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 = checkoutsettings.DeleteCheckoutSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = CheckoutSettingsServiceClient( - 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_get_checkout_settings_empty_call_rest(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - client.get_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.GetCheckoutSettingsRequest() - - 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_create_checkout_settings_empty_call_rest(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - client.create_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.CreateCheckoutSettingsRequest() - - 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_update_checkout_settings_empty_call_rest(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - client.update_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.UpdateCheckoutSettingsRequest() - - 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_checkout_settings_empty_call_rest(): - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: - client.delete_checkout_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = checkoutsettings.DeleteCheckoutSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CheckoutSettingsServiceGrpcTransport, - ) - -def test_checkout_settings_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CheckoutSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_checkout_settings_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CheckoutSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_checkout_settings', - 'create_checkout_settings', - 'update_checkout_settings', - 'delete_checkout_settings', - ) - 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_checkout_settings_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_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CheckoutSettingsServiceTransport( - 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_checkout_settings_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_accounts_v1beta.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CheckoutSettingsServiceTransport() - adc.assert_called_once() - - -def test_checkout_settings_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) - CheckoutSettingsServiceClient() - 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.CheckoutSettingsServiceGrpcTransport, - transports.CheckoutSettingsServiceGrpcAsyncIOTransport, - ], -) -def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, - transports.CheckoutSettingsServiceGrpcAsyncIOTransport, - transports.CheckoutSettingsServiceRestTransport, - ], -) -def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, grpc_helpers), - (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) -def test_checkout_settings_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_checkout_settings_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.CheckoutSettingsServiceRestTransport ( - 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_checkout_settings_service_host_no_port(transport_name): - client = CheckoutSettingsServiceClient( - 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_checkout_settings_service_host_with_port(transport_name): - client = CheckoutSettingsServiceClient( - 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_checkout_settings_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CheckoutSettingsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CheckoutSettingsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_checkout_settings._session - session2 = client2.transport.get_checkout_settings._session - assert session1 != session2 - session1 = client1.transport.create_checkout_settings._session - session2 = client2.transport.create_checkout_settings._session - assert session1 != session2 - session1 = client1.transport.update_checkout_settings._session - session2 = client2.transport.update_checkout_settings._session - assert session1 != session2 - session1 = client1.transport.delete_checkout_settings._session - session2 = client2.transport.delete_checkout_settings._session - assert session1 != session2 -def test_checkout_settings_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CheckoutSettingsServiceGrpcTransport( - 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_checkout_settings_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CheckoutSettingsServiceGrpcAsyncIOTransport( - 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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) -def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) -def test_checkout_settings_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_checkout_settings_path(): - account = "squid" - program = "clam" - expected = "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) - actual = CheckoutSettingsServiceClient.checkout_settings_path(account, program) - assert expected == actual - - -def test_parse_checkout_settings_path(): - expected = { - "account": "whelk", - "program": "octopus", - } - path = CheckoutSettingsServiceClient.checkout_settings_path(**expected) - - # Check that the path construction is reversible. - actual = CheckoutSettingsServiceClient.parse_checkout_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CheckoutSettingsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = CheckoutSettingsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CheckoutSettingsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = CheckoutSettingsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = CheckoutSettingsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CheckoutSettingsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CheckoutSettingsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = CheckoutSettingsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CheckoutSettingsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = CheckoutSettingsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = CheckoutSettingsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CheckoutSettingsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CheckoutSettingsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = CheckoutSettingsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CheckoutSettingsServiceClient.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.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: - client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CheckoutSettingsServiceClient.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 = CheckoutSettingsServiceClient( - 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 = CheckoutSettingsServiceAsyncClient( - 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 = CheckoutSettingsServiceClient( - 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 = CheckoutSettingsServiceClient( - 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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py deleted file mode 100644 index 52282fdb4e6a..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_email_preferences_service.py +++ /dev/null @@ -1,2878 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.email_preferences_service import EmailPreferencesServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.email_preferences_service import EmailPreferencesServiceClient -from google.shopping.merchant_accounts_v1beta.services.email_preferences_service import transports -from google.shopping.merchant_accounts_v1beta.types import emailpreferences -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 EmailPreferencesServiceClient._get_default_mtls_endpoint(None) is None - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, False) is None - assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EmailPreferencesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EmailPreferencesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EmailPreferencesServiceClient._get_universe_domain(None, None) == EmailPreferencesServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient(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 = EmailPreferencesServiceClient(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", [ - (EmailPreferencesServiceClient, "grpc"), - (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), - (EmailPreferencesServiceClient, "rest"), -]) -def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, "grpc"), - (transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EmailPreferencesServiceRestTransport, "rest"), -]) -def test_email_preferences_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", [ - (EmailPreferencesServiceClient, "grpc"), - (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), - (EmailPreferencesServiceClient, "rest"), -]) -def test_email_preferences_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_email_preferences_service_client_get_transport_class(): - transport = EmailPreferencesServiceClient.get_transport_class() - available_transports = [ - transports.EmailPreferencesServiceGrpcTransport, - transports.EmailPreferencesServiceRestTransport, - ] - assert transport in available_transports - - transport = EmailPreferencesServiceClient.get_transport_class("grpc") - assert transport == transports.EmailPreferencesServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), -]) -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) -def test_email_preferences_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(EmailPreferencesServiceClient, '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(EmailPreferencesServiceClient, '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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "true"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "false"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "true"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_email_preferences_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", [ - EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient -]) -@mock.patch.object(EmailPreferencesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceAsyncClient)) -def test_email_preferences_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", [ - EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient -]) -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) -def test_email_preferences_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EmailPreferencesServiceClient._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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), -]) -def test_email_preferences_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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", None), -]) -def test_email_preferences_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_email_preferences_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EmailPreferencesServiceClient( - 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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_email_preferences_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", [ - emailpreferences.GetEmailPreferencesRequest, - dict, -]) -def test_get_email_preferences(request_type, transport: str = 'grpc'): - client = EmailPreferencesServiceClient( - 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.get_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - ) - response = client.get_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = emailpreferences.GetEmailPreferencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT - - -def test_get_email_preferences_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 = EmailPreferencesServiceClient( - 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 = emailpreferences.GetEmailPreferencesRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_email_preferences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == emailpreferences.GetEmailPreferencesRequest( - name='name_value', - ) - -def test_get_email_preferences_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 = EmailPreferencesServiceClient( - 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.get_email_preferences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc - request = {} - client.get_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_email_preferences(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_get_email_preferences_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 = EmailPreferencesServiceAsyncClient( - 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.get_email_preferences in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_email_preferences] = mock_rpc - - request = {} - await client.get_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_email_preferences(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_get_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.GetEmailPreferencesRequest): - client = EmailPreferencesServiceAsyncClient( - 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.get_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) - response = await client.get_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = emailpreferences.GetEmailPreferencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT - - -@pytest.mark.asyncio -async def test_get_email_preferences_async_from_dict(): - await test_get_email_preferences_async(request_type=dict) - -def test_get_email_preferences_field_headers(): - client = EmailPreferencesServiceClient( - 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 = emailpreferences.GetEmailPreferencesRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - call.return_value = emailpreferences.EmailPreferences() - client.get_email_preferences(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_get_email_preferences_field_headers_async(): - client = EmailPreferencesServiceAsyncClient( - 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 = emailpreferences.GetEmailPreferencesRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) - await client.get_email_preferences(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_get_email_preferences_flattened(): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = emailpreferences.EmailPreferences() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_email_preferences( - 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_get_email_preferences_flattened_error(): - client = EmailPreferencesServiceClient( - 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.get_email_preferences( - emailpreferences.GetEmailPreferencesRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_email_preferences_flattened_async(): - client = EmailPreferencesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = emailpreferences.EmailPreferences() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_email_preferences( - 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_get_email_preferences_flattened_error_async(): - client = EmailPreferencesServiceAsyncClient( - 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.get_email_preferences( - emailpreferences.GetEmailPreferencesRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - emailpreferences.UpdateEmailPreferencesRequest, - dict, -]) -def test_update_email_preferences(request_type, transport: str = 'grpc'): - client = EmailPreferencesServiceClient( - 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.update_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - ) - response = client.update_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = emailpreferences.UpdateEmailPreferencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT - - -def test_update_email_preferences_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 = EmailPreferencesServiceClient( - 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 = emailpreferences.UpdateEmailPreferencesRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_email_preferences(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == emailpreferences.UpdateEmailPreferencesRequest( - ) - -def test_update_email_preferences_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 = EmailPreferencesServiceClient( - 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.update_email_preferences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc - request = {} - client.update_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_email_preferences(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_update_email_preferences_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 = EmailPreferencesServiceAsyncClient( - 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.update_email_preferences in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_email_preferences] = mock_rpc - - request = {} - await client.update_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_email_preferences(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_update_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.UpdateEmailPreferencesRequest): - client = EmailPreferencesServiceAsyncClient( - 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.update_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) - response = await client.update_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = emailpreferences.UpdateEmailPreferencesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT - - -@pytest.mark.asyncio -async def test_update_email_preferences_async_from_dict(): - await test_update_email_preferences_async(request_type=dict) - -def test_update_email_preferences_field_headers(): - client = EmailPreferencesServiceClient( - 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 = emailpreferences.UpdateEmailPreferencesRequest() - - request.email_preferences.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - call.return_value = emailpreferences.EmailPreferences() - client.update_email_preferences(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', - 'email_preferences.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_email_preferences_field_headers_async(): - client = EmailPreferencesServiceAsyncClient( - 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 = emailpreferences.UpdateEmailPreferencesRequest() - - request.email_preferences.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) - await client.update_email_preferences(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', - 'email_preferences.name=name_value', - ) in kw['metadata'] - - -def test_update_email_preferences_flattened(): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = emailpreferences.EmailPreferences() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_email_preferences( - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].email_preferences - mock_val = emailpreferences.EmailPreferences(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_email_preferences_flattened_error(): - client = EmailPreferencesServiceClient( - 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.update_email_preferences( - emailpreferences.UpdateEmailPreferencesRequest(), - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_email_preferences_flattened_async(): - client = EmailPreferencesServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = emailpreferences.EmailPreferences() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_email_preferences( - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].email_preferences - mock_val = emailpreferences.EmailPreferences(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_email_preferences_flattened_error_async(): - client = EmailPreferencesServiceAsyncClient( - 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.update_email_preferences( - emailpreferences.UpdateEmailPreferencesRequest(), - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_email_preferences_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 = EmailPreferencesServiceClient( - 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.get_email_preferences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc - - request = {} - client.get_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_email_preferences(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_get_email_preferences_rest_required_fields(request_type=emailpreferences.GetEmailPreferencesRequest): - transport_class = transports.EmailPreferencesServiceRestTransport - - 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()).get_email_preferences._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_email_preferences._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 = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = emailpreferences.EmailPreferences() - # 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 = emailpreferences.EmailPreferences.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.get_email_preferences(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_email_preferences_rest_unset_required_fields(): - transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_email_preferences._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_email_preferences_rest_flattened(): - client = EmailPreferencesServiceClient( - 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 = emailpreferences.EmailPreferences() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/users/sample2/emailPreferences'} - - # 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 - # Convert return value to protobuf type - return_value = emailpreferences.EmailPreferences.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.get_email_preferences(**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/accounts/v1beta/{name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) - - -def test_get_email_preferences_rest_flattened_error(transport: str = 'rest'): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_email_preferences( - emailpreferences.GetEmailPreferencesRequest(), - name='name_value', - ) - - -def test_update_email_preferences_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 = EmailPreferencesServiceClient( - 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.update_email_preferences in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc - - request = {} - client.update_email_preferences(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_email_preferences(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_update_email_preferences_rest_required_fields(request_type=emailpreferences.UpdateEmailPreferencesRequest): - transport_class = transports.EmailPreferencesServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = emailpreferences.EmailPreferences() - # 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': "patch", - '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 = emailpreferences.EmailPreferences.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.update_email_preferences(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_email_preferences_rest_unset_required_fields(): - transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_email_preferences._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("emailPreferences", "updateMask", ))) - - -def test_update_email_preferences_rest_flattened(): - client = EmailPreferencesServiceClient( - 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 = emailpreferences.EmailPreferences() - - # get arguments that satisfy an http rule for this method - sample_request = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} - - # get truthy value for each flattened field - mock_args = dict( - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = emailpreferences.EmailPreferences.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.update_email_preferences(**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/accounts/v1beta/{email_preferences.name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) - - -def test_update_email_preferences_rest_flattened_error(transport: str = 'rest'): - client = EmailPreferencesServiceClient( - 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.update_email_preferences( - emailpreferences.UpdateEmailPreferencesRequest(), - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EmailPreferencesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EmailPreferencesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EmailPreferencesServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EmailPreferencesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EmailPreferencesServiceClient( - 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 = EmailPreferencesServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EmailPreferencesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EmailPreferencesServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EmailPreferencesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EmailPreferencesServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EmailPreferencesServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EmailPreferencesServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EmailPreferencesServiceGrpcTransport, - transports.EmailPreferencesServiceGrpcAsyncIOTransport, - transports.EmailPreferencesServiceRestTransport, -]) -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 = EmailPreferencesServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EmailPreferencesServiceClient( - 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_get_email_preferences_empty_call_grpc(): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - call.return_value = emailpreferences.EmailPreferences() - client.get_email_preferences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = emailpreferences.GetEmailPreferencesRequest() - - 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_update_email_preferences_empty_call_grpc(): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - call.return_value = emailpreferences.EmailPreferences() - client.update_email_preferences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = emailpreferences.UpdateEmailPreferencesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = EmailPreferencesServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EmailPreferencesServiceAsyncClient( - 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_get_email_preferences_empty_call_grpc_asyncio(): - client = EmailPreferencesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) - await client.get_email_preferences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = emailpreferences.GetEmailPreferencesRequest() - - 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_update_email_preferences_empty_call_grpc_asyncio(): - client = EmailPreferencesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) - await client.update_email_preferences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = emailpreferences.UpdateEmailPreferencesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = EmailPreferencesServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_email_preferences_rest_bad_request(request_type=emailpreferences.GetEmailPreferencesRequest): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} - 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.get_email_preferences(request) - - -@pytest.mark.parametrize("request_type", [ - emailpreferences.GetEmailPreferencesRequest, - dict, -]) -def test_get_email_preferences_rest_call_success(request_type): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} - request = request_type(**request_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 = emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - ) - - # 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 = emailpreferences.EmailPreferences.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.get_email_preferences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_email_preferences_rest_interceptors(null_interceptor): - transport = transports.EmailPreferencesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), - ) - client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences") as post, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_get_email_preferences") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = emailpreferences.GetEmailPreferencesRequest.pb(emailpreferences.GetEmailPreferencesRequest()) - 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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) - req.return_value.content = return_value - - request = emailpreferences.GetEmailPreferencesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = emailpreferences.EmailPreferences() - post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata - - client.get_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_email_preferences_rest_bad_request(request_type=emailpreferences.UpdateEmailPreferencesRequest): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} - 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.update_email_preferences(request) - - -@pytest.mark.parametrize("request_type", [ - emailpreferences.UpdateEmailPreferencesRequest, - dict, -]) -def test_update_email_preferences_rest_call_success(request_type): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} - request_init["email_preferences"] = {'name': 'accounts/sample1/users/sample2/emailPreferences', 'news_and_tips': 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 = emailpreferences.UpdateEmailPreferencesRequest.meta.fields["email_preferences"] - - 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["email_preferences"].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["email_preferences"][field])): - del request_init["email_preferences"][field][i][subfield] - else: - del request_init["email_preferences"][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 = emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - ) - - # 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 = emailpreferences.EmailPreferences.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.update_email_preferences(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_email_preferences_rest_interceptors(null_interceptor): - transport = transports.EmailPreferencesServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), - ) - client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences") as post, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_update_email_preferences") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = emailpreferences.UpdateEmailPreferencesRequest.pb(emailpreferences.UpdateEmailPreferencesRequest()) - 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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) - req.return_value.content = return_value - - request = emailpreferences.UpdateEmailPreferencesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = emailpreferences.EmailPreferences() - post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata - - client.update_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = EmailPreferencesServiceClient( - 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_get_email_preferences_empty_call_rest(): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - client.get_email_preferences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = emailpreferences.GetEmailPreferencesRequest() - - 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_update_email_preferences_empty_call_rest(): - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - client.update_email_preferences(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = emailpreferences.UpdateEmailPreferencesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EmailPreferencesServiceGrpcTransport, - ) - -def test_email_preferences_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EmailPreferencesServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_email_preferences_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EmailPreferencesServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_email_preferences', - 'update_email_preferences', - ) - 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_email_preferences_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_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EmailPreferencesServiceTransport( - 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_email_preferences_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_accounts_v1beta.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EmailPreferencesServiceTransport() - adc.assert_called_once() - - -def test_email_preferences_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) - EmailPreferencesServiceClient() - 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.EmailPreferencesServiceGrpcTransport, - transports.EmailPreferencesServiceGrpcAsyncIOTransport, - ], -) -def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, - transports.EmailPreferencesServiceGrpcAsyncIOTransport, - transports.EmailPreferencesServiceRestTransport, - ], -) -def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, grpc_helpers), - (transports.EmailPreferencesServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) -def test_email_preferences_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_email_preferences_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.EmailPreferencesServiceRestTransport ( - 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_email_preferences_service_host_no_port(transport_name): - client = EmailPreferencesServiceClient( - 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_email_preferences_service_host_with_port(transport_name): - client = EmailPreferencesServiceClient( - 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_email_preferences_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EmailPreferencesServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EmailPreferencesServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_email_preferences._session - session2 = client2.transport.get_email_preferences._session - assert session1 != session2 - session1 = client1.transport.update_email_preferences._session - session2 = client2.transport.update_email_preferences._session - assert session1 != session2 -def test_email_preferences_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EmailPreferencesServiceGrpcTransport( - 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_email_preferences_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EmailPreferencesServiceGrpcAsyncIOTransport( - 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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) -def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) -def test_email_preferences_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_email_preferences_path(): - account = "squid" - email = "clam" - expected = "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) - actual = EmailPreferencesServiceClient.email_preferences_path(account, email) - assert expected == actual - - -def test_parse_email_preferences_path(): - expected = { - "account": "whelk", - "email": "octopus", - } - path = EmailPreferencesServiceClient.email_preferences_path(**expected) - - # Check that the path construction is reversible. - actual = EmailPreferencesServiceClient.parse_email_preferences_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EmailPreferencesServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = EmailPreferencesServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EmailPreferencesServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = EmailPreferencesServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = EmailPreferencesServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EmailPreferencesServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EmailPreferencesServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = EmailPreferencesServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EmailPreferencesServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = EmailPreferencesServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = EmailPreferencesServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EmailPreferencesServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = EmailPreferencesServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = EmailPreferencesServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EmailPreferencesServiceClient.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.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: - client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = EmailPreferencesServiceClient.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 = EmailPreferencesServiceClient( - 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 = EmailPreferencesServiceAsyncClient( - 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 = EmailPreferencesServiceClient( - 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 = EmailPreferencesServiceClient( - 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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py deleted file mode 100644 index 0bd0f6a1ae38..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_gbp_accounts_service.py +++ /dev/null @@ -1,3072 +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 empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import GbpAccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import GbpAccountsServiceClient -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import pagers -from google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service import transports -from google.shopping.merchant_accounts_v1beta.types import gbpaccounts -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 GbpAccountsServiceClient._get_default_mtls_endpoint(None) is None - assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert GbpAccountsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - GbpAccountsServiceClient._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 GbpAccountsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - GbpAccountsServiceClient._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 GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, False) is None - assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert GbpAccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert GbpAccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert GbpAccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert GbpAccountsServiceClient._get_universe_domain(None, None) == GbpAccountsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - GbpAccountsServiceClient._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 = GbpAccountsServiceClient(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 = GbpAccountsServiceClient(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", [ - (GbpAccountsServiceClient, "grpc"), - (GbpAccountsServiceAsyncClient, "grpc_asyncio"), - (GbpAccountsServiceClient, "rest"), -]) -def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, "grpc"), - (transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.GbpAccountsServiceRestTransport, "rest"), -]) -def test_gbp_accounts_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", [ - (GbpAccountsServiceClient, "grpc"), - (GbpAccountsServiceAsyncClient, "grpc_asyncio"), - (GbpAccountsServiceClient, "rest"), -]) -def test_gbp_accounts_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_gbp_accounts_service_client_get_transport_class(): - transport = GbpAccountsServiceClient.get_transport_class() - available_transports = [ - transports.GbpAccountsServiceGrpcTransport, - transports.GbpAccountsServiceRestTransport, - ] - assert transport in available_transports - - transport = GbpAccountsServiceClient.get_transport_class("grpc") - assert transport == transports.GbpAccountsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), -]) -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) -def test_gbp_accounts_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(GbpAccountsServiceClient, '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(GbpAccountsServiceClient, '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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "true"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "false"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "true"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_gbp_accounts_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", [ - GbpAccountsServiceClient, GbpAccountsServiceAsyncClient -]) -@mock.patch.object(GbpAccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceAsyncClient)) -def test_gbp_accounts_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", [ - GbpAccountsServiceClient, GbpAccountsServiceAsyncClient -]) -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) -def test_gbp_accounts_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = GbpAccountsServiceClient._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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), -]) -def test_gbp_accounts_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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", None), -]) -def test_gbp_accounts_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_gbp_accounts_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = GbpAccountsServiceClient( - 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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_gbp_accounts_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", [ - gbpaccounts.ListGbpAccountsRequest, - dict, -]) -def test_list_gbp_accounts(request_type, transport: str = 'grpc'): - client = GbpAccountsServiceClient( - 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_gbp_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_gbp_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gbpaccounts.ListGbpAccountsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGbpAccountsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_gbp_accounts_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 = GbpAccountsServiceClient( - 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 = gbpaccounts.ListGbpAccountsRequest( - 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_gbp_accounts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_gbp_accounts(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gbpaccounts.ListGbpAccountsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_gbp_accounts_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 = GbpAccountsServiceClient( - 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_gbp_accounts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_gbp_accounts] = mock_rpc - request = {} - client.list_gbp_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_gbp_accounts(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_gbp_accounts_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 = GbpAccountsServiceAsyncClient( - 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_gbp_accounts 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_gbp_accounts] = mock_rpc - - request = {} - await client.list_gbp_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_gbp_accounts(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_gbp_accounts_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.ListGbpAccountsRequest): - client = GbpAccountsServiceAsyncClient( - 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_gbp_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_gbp_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gbpaccounts.ListGbpAccountsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGbpAccountsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_gbp_accounts_async_from_dict(): - await test_list_gbp_accounts_async(request_type=dict) - -def test_list_gbp_accounts_field_headers(): - client = GbpAccountsServiceClient( - 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 = gbpaccounts.ListGbpAccountsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - call.return_value = gbpaccounts.ListGbpAccountsResponse() - client.list_gbp_accounts(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_gbp_accounts_field_headers_async(): - client = GbpAccountsServiceAsyncClient( - 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 = gbpaccounts.ListGbpAccountsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) - await client.list_gbp_accounts(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_gbp_accounts_flattened(): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.ListGbpAccountsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_gbp_accounts( - 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_gbp_accounts_flattened_error(): - client = GbpAccountsServiceClient( - 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_gbp_accounts( - gbpaccounts.ListGbpAccountsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_gbp_accounts_flattened_async(): - client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.ListGbpAccountsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_gbp_accounts( - 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_gbp_accounts_flattened_error_async(): - client = GbpAccountsServiceAsyncClient( - 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_gbp_accounts( - gbpaccounts.ListGbpAccountsRequest(), - parent='parent_value', - ) - - -def test_list_gbp_accounts_pager(transport_name: str = "grpc"): - client = GbpAccountsServiceClient( - 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_gbp_accounts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - next_page_token='abc', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[], - next_page_token='def', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - ], - next_page_token='ghi', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_gbp_accounts(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, gbpaccounts.GbpAccount) - for i in results) -def test_list_gbp_accounts_pages(transport_name: str = "grpc"): - client = GbpAccountsServiceClient( - 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_gbp_accounts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - next_page_token='abc', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[], - next_page_token='def', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - ], - next_page_token='ghi', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - ), - RuntimeError, - ) - pages = list(client.list_gbp_accounts(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_gbp_accounts_async_pager(): - client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - next_page_token='abc', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[], - next_page_token='def', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - ], - next_page_token='ghi', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_gbp_accounts(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, gbpaccounts.GbpAccount) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_gbp_accounts_async_pages(): - client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - next_page_token='abc', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[], - next_page_token='def', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - ], - next_page_token='ghi', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - ), - 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_gbp_accounts(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", [ - gbpaccounts.LinkGbpAccountRequest, - dict, -]) -def test_link_gbp_account(request_type, transport: str = 'grpc'): - client = GbpAccountsServiceClient( - 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.link_gbp_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.LinkGbpAccountResponse( - ) - response = client.link_gbp_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gbpaccounts.LinkGbpAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) - - -def test_link_gbp_account_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 = GbpAccountsServiceClient( - 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 = gbpaccounts.LinkGbpAccountRequest( - parent='parent_value', - gbp_email='gbp_email_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.link_gbp_account(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gbpaccounts.LinkGbpAccountRequest( - parent='parent_value', - gbp_email='gbp_email_value', - ) - -def test_link_gbp_account_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 = GbpAccountsServiceClient( - 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.link_gbp_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc - request = {} - client.link_gbp_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.link_gbp_account(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_link_gbp_account_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 = GbpAccountsServiceAsyncClient( - 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.link_gbp_account 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.link_gbp_account] = mock_rpc - - request = {} - await client.link_gbp_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.link_gbp_account(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_link_gbp_account_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.LinkGbpAccountRequest): - client = GbpAccountsServiceAsyncClient( - 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.link_gbp_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( - )) - response = await client.link_gbp_account(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gbpaccounts.LinkGbpAccountRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) - - -@pytest.mark.asyncio -async def test_link_gbp_account_async_from_dict(): - await test_link_gbp_account_async(request_type=dict) - -def test_link_gbp_account_field_headers(): - client = GbpAccountsServiceClient( - 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 = gbpaccounts.LinkGbpAccountRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - call.return_value = gbpaccounts.LinkGbpAccountResponse() - client.link_gbp_account(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_link_gbp_account_field_headers_async(): - client = GbpAccountsServiceAsyncClient( - 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 = gbpaccounts.LinkGbpAccountRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) - await client.link_gbp_account(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_link_gbp_account_flattened(): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.LinkGbpAccountResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.link_gbp_account( - 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_link_gbp_account_flattened_error(): - client = GbpAccountsServiceClient( - 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.link_gbp_account( - gbpaccounts.LinkGbpAccountRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_link_gbp_account_flattened_async(): - client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.LinkGbpAccountResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.link_gbp_account( - 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_link_gbp_account_flattened_error_async(): - client = GbpAccountsServiceAsyncClient( - 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.link_gbp_account( - gbpaccounts.LinkGbpAccountRequest(), - parent='parent_value', - ) - - -def test_list_gbp_accounts_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 = GbpAccountsServiceClient( - 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_gbp_accounts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_gbp_accounts] = mock_rpc - - request = {} - client.list_gbp_accounts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_gbp_accounts(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_gbp_accounts_rest_required_fields(request_type=gbpaccounts.ListGbpAccountsRequest): - transport_class = transports.GbpAccountsServiceRestTransport - - 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_gbp_accounts._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_gbp_accounts._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 = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gbpaccounts.ListGbpAccountsResponse() - # 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_gbp_accounts_rest_unset_required_fields(): - transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_gbp_accounts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_gbp_accounts_rest_flattened(): - client = GbpAccountsServiceClient( - 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 = gbpaccounts.ListGbpAccountsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(**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/accounts/v1beta/{parent=accounts/*}/gbpAccounts" % client.transport._host, args[1]) - - -def test_list_gbp_accounts_rest_flattened_error(transport: str = 'rest'): - client = GbpAccountsServiceClient( - 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_gbp_accounts( - gbpaccounts.ListGbpAccountsRequest(), - parent='parent_value', - ) - - -def test_list_gbp_accounts_rest_pager(transport: str = 'rest'): - client = GbpAccountsServiceClient( - 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 = ( - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - next_page_token='abc', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[], - next_page_token='def', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - ], - next_page_token='ghi', - ), - gbpaccounts.ListGbpAccountsResponse( - gbp_accounts=[ - gbpaccounts.GbpAccount(), - gbpaccounts.GbpAccount(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(gbpaccounts.ListGbpAccountsResponse.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'} - - pager = client.list_gbp_accounts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, gbpaccounts.GbpAccount) - for i in results) - - pages = list(client.list_gbp_accounts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_link_gbp_account_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 = GbpAccountsServiceClient( - 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.link_gbp_account in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc - - request = {} - client.link_gbp_account(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.link_gbp_account(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_link_gbp_account_rest_required_fields(request_type=gbpaccounts.LinkGbpAccountRequest): - transport_class = transports.GbpAccountsServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["gbp_email"] = "" - 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()).link_gbp_account._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["gbpEmail"] = 'gbp_email_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_gbp_account._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 "gbpEmail" in jsonified_request - assert jsonified_request["gbpEmail"] == 'gbp_email_value' - - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gbpaccounts.LinkGbpAccountResponse() - # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_link_gbp_account_rest_unset_required_fields(): - transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.link_gbp_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "gbpEmail", ))) - - -def test_link_gbp_account_rest_flattened(): - client = GbpAccountsServiceClient( - 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 = gbpaccounts.LinkGbpAccountResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(**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/accounts/v1beta/{parent=accounts/*}/gbpAccounts:linkGbpAccount" % client.transport._host, args[1]) - - -def test_link_gbp_account_rest_flattened_error(transport: str = 'rest'): - client = GbpAccountsServiceClient( - 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.link_gbp_account( - gbpaccounts.LinkGbpAccountRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.GbpAccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.GbpAccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GbpAccountsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.GbpAccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = GbpAccountsServiceClient( - 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 = GbpAccountsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.GbpAccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = GbpAccountsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.GbpAccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = GbpAccountsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.GbpAccountsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.GbpAccountsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.GbpAccountsServiceGrpcTransport, - transports.GbpAccountsServiceGrpcAsyncIOTransport, - transports.GbpAccountsServiceRestTransport, -]) -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 = GbpAccountsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = GbpAccountsServiceClient( - 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_gbp_accounts_empty_call_grpc(): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - call.return_value = gbpaccounts.ListGbpAccountsResponse() - client.list_gbp_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gbpaccounts.ListGbpAccountsRequest() - - 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_link_gbp_account_empty_call_grpc(): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - call.return_value = gbpaccounts.LinkGbpAccountResponse() - client.link_gbp_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gbpaccounts.LinkGbpAccountRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = GbpAccountsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = GbpAccountsServiceAsyncClient( - 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_gbp_accounts_empty_call_grpc_asyncio(): - client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', - )) - await client.list_gbp_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gbpaccounts.ListGbpAccountsRequest() - - 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_link_gbp_account_empty_call_grpc_asyncio(): - client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( - )) - await client.link_gbp_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gbpaccounts.LinkGbpAccountRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = GbpAccountsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_gbp_accounts_rest_bad_request(request_type=gbpaccounts.ListGbpAccountsRequest): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_gbp_accounts(request) - - -@pytest.mark.parametrize("request_type", [ - gbpaccounts.ListGbpAccountsRequest, - dict, -]) -def test_list_gbp_accounts_rest_call_success(request_type): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gbpaccounts.ListGbpAccountsResponse( - 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 = gbpaccounts.ListGbpAccountsResponse.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_gbp_accounts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGbpAccountsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_gbp_accounts_rest_interceptors(null_interceptor): - transport = transports.GbpAccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), - ) - client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts") as post, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_list_gbp_accounts") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gbpaccounts.ListGbpAccountsRequest.pb(gbpaccounts.ListGbpAccountsRequest()) - 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 = gbpaccounts.ListGbpAccountsResponse.to_json(gbpaccounts.ListGbpAccountsResponse()) - req.return_value.content = return_value - - request = gbpaccounts.ListGbpAccountsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gbpaccounts.ListGbpAccountsResponse() - post_with_metadata.return_value = gbpaccounts.ListGbpAccountsResponse(), metadata - - client.list_gbp_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_link_gbp_account_rest_bad_request(request_type=gbpaccounts.LinkGbpAccountRequest): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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.link_gbp_account(request) - - -@pytest.mark.parametrize("request_type", [ - gbpaccounts.LinkGbpAccountRequest, - dict, -]) -def test_link_gbp_account_rest_call_success(request_type): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gbpaccounts.LinkGbpAccountResponse( - ) - - # 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 = gbpaccounts.LinkGbpAccountResponse.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.link_gbp_account(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gbpaccounts.LinkGbpAccountResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_link_gbp_account_rest_interceptors(null_interceptor): - transport = transports.GbpAccountsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), - ) - client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_link_gbp_account") as post, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_link_gbp_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_link_gbp_account") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gbpaccounts.LinkGbpAccountRequest.pb(gbpaccounts.LinkGbpAccountRequest()) - 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 = gbpaccounts.LinkGbpAccountResponse.to_json(gbpaccounts.LinkGbpAccountResponse()) - req.return_value.content = return_value - - request = gbpaccounts.LinkGbpAccountRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gbpaccounts.LinkGbpAccountResponse() - post_with_metadata.return_value = gbpaccounts.LinkGbpAccountResponse(), metadata - - client.link_gbp_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = GbpAccountsServiceClient( - 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_gbp_accounts_empty_call_rest(): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: - client.list_gbp_accounts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gbpaccounts.ListGbpAccountsRequest() - - 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_link_gbp_account_empty_call_rest(): - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - client.link_gbp_account(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gbpaccounts.LinkGbpAccountRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.GbpAccountsServiceGrpcTransport, - ) - -def test_gbp_accounts_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.GbpAccountsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_gbp_accounts_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.GbpAccountsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_gbp_accounts', - 'link_gbp_account', - ) - 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_gbp_accounts_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_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GbpAccountsServiceTransport( - 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_gbp_accounts_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_accounts_v1beta.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.GbpAccountsServiceTransport() - adc.assert_called_once() - - -def test_gbp_accounts_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) - GbpAccountsServiceClient() - 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.GbpAccountsServiceGrpcTransport, - transports.GbpAccountsServiceGrpcAsyncIOTransport, - ], -) -def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, - transports.GbpAccountsServiceGrpcAsyncIOTransport, - transports.GbpAccountsServiceRestTransport, - ], -) -def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, grpc_helpers), - (transports.GbpAccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) -def test_gbp_accounts_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_gbp_accounts_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.GbpAccountsServiceRestTransport ( - 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_gbp_accounts_service_host_no_port(transport_name): - client = GbpAccountsServiceClient( - 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_gbp_accounts_service_host_with_port(transport_name): - client = GbpAccountsServiceClient( - 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_gbp_accounts_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = GbpAccountsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = GbpAccountsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_gbp_accounts._session - session2 = client2.transport.list_gbp_accounts._session - assert session1 != session2 - session1 = client1.transport.link_gbp_account._session - session2 = client2.transport.link_gbp_account._session - assert session1 != session2 -def test_gbp_accounts_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GbpAccountsServiceGrpcTransport( - 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_gbp_accounts_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.GbpAccountsServiceGrpcAsyncIOTransport( - 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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) -def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) -def test_gbp_accounts_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = GbpAccountsServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = GbpAccountsServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.parse_account_path(path) - assert expected == actual - -def test_gbp_account_path(): - account = "whelk" - gbp_account = "octopus" - expected = "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) - actual = GbpAccountsServiceClient.gbp_account_path(account, gbp_account) - assert expected == actual - - -def test_parse_gbp_account_path(): - expected = { - "account": "oyster", - "gbp_account": "nudibranch", - } - path = GbpAccountsServiceClient.gbp_account_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.parse_gbp_account_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = GbpAccountsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = GbpAccountsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = GbpAccountsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = GbpAccountsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = GbpAccountsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = GbpAccountsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = GbpAccountsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = GbpAccountsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = GbpAccountsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = GbpAccountsServiceClient.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.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: - client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = GbpAccountsServiceClient.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 = GbpAccountsServiceClient( - 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 = GbpAccountsServiceAsyncClient( - 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 = GbpAccountsServiceClient( - 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 = GbpAccountsServiceClient( - 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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py deleted file mode 100644 index 942d0a7a36a6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_homepage_service.py +++ /dev/null @@ -1,3965 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.homepage_service import HomepageServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.homepage_service import HomepageServiceClient -from google.shopping.merchant_accounts_v1beta.services.homepage_service import transports -from google.shopping.merchant_accounts_v1beta.types import homepage -from google.shopping.merchant_accounts_v1beta.types import homepage as gsma_homepage -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 HomepageServiceClient._get_default_mtls_endpoint(None) is None - assert HomepageServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert HomepageServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - HomepageServiceClient._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 HomepageServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert HomepageServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - HomepageServiceClient._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 HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, False) is None - assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = HomepageServiceClient._DEFAULT_UNIVERSE - default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert HomepageServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - assert HomepageServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - HomepageServiceClient._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 HomepageServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert HomepageServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert HomepageServiceClient._get_universe_domain(None, None) == HomepageServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - HomepageServiceClient._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 = HomepageServiceClient(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 = HomepageServiceClient(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", [ - (HomepageServiceClient, "grpc"), - (HomepageServiceAsyncClient, "grpc_asyncio"), - (HomepageServiceClient, "rest"), -]) -def test_homepage_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.HomepageServiceGrpcTransport, "grpc"), - (transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.HomepageServiceRestTransport, "rest"), -]) -def test_homepage_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", [ - (HomepageServiceClient, "grpc"), - (HomepageServiceAsyncClient, "grpc_asyncio"), - (HomepageServiceClient, "rest"), -]) -def test_homepage_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_homepage_service_client_get_transport_class(): - transport = HomepageServiceClient.get_transport_class() - available_transports = [ - transports.HomepageServiceGrpcTransport, - transports.HomepageServiceRestTransport, - ] - assert transport in available_transports - - transport = HomepageServiceClient.get_transport_class("grpc") - assert transport == transports.HomepageServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), -]) -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) -def test_homepage_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(HomepageServiceClient, '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(HomepageServiceClient, '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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "true"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "false"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "true"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_homepage_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", [ - HomepageServiceClient, HomepageServiceAsyncClient -]) -@mock.patch.object(HomepageServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceAsyncClient)) -def test_homepage_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", [ - HomepageServiceClient, HomepageServiceAsyncClient -]) -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) -def test_homepage_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = HomepageServiceClient._DEFAULT_UNIVERSE - default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = HomepageServiceClient._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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), -]) -def test_homepage_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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", None), -]) -def test_homepage_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_homepage_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.homepage_service.transports.HomepageServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = HomepageServiceClient( - 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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_homepage_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", [ - homepage.GetHomepageRequest, - dict, -]) -def test_get_homepage(request_type, transport: str = 'grpc'): - client = HomepageServiceClient( - 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.get_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - response = client.get_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = homepage.GetHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -def test_get_homepage_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 = HomepageServiceClient( - 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 = homepage.GetHomepageRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_homepage(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == homepage.GetHomepageRequest( - name='name_value', - ) - -def test_get_homepage_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 = HomepageServiceClient( - 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.get_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc - request = {} - client.get_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_homepage(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_get_homepage_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 = HomepageServiceAsyncClient( - 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.get_homepage in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_homepage] = mock_rpc - - request = {} - await client.get_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_homepage(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_get_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.GetHomepageRequest): - client = HomepageServiceAsyncClient( - 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.get_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - response = await client.get_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = homepage.GetHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.asyncio -async def test_get_homepage_async_from_dict(): - await test_get_homepage_async(request_type=dict) - -def test_get_homepage_field_headers(): - client = HomepageServiceClient( - 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 = homepage.GetHomepageRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - call.return_value = homepage.Homepage() - client.get_homepage(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_get_homepage_field_headers_async(): - client = HomepageServiceAsyncClient( - 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 = homepage.GetHomepageRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) - await client.get_homepage(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_get_homepage_flattened(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = homepage.Homepage() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_homepage( - 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_get_homepage_flattened_error(): - client = HomepageServiceClient( - 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.get_homepage( - homepage.GetHomepageRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_homepage_flattened_async(): - client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = homepage.Homepage() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_homepage( - 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_get_homepage_flattened_error_async(): - client = HomepageServiceAsyncClient( - 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.get_homepage( - homepage.GetHomepageRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gsma_homepage.UpdateHomepageRequest, - dict, -]) -def test_update_homepage(request_type, transport: str = 'grpc'): - client = HomepageServiceClient( - 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.update_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - response = client.update_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gsma_homepage.UpdateHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -def test_update_homepage_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 = HomepageServiceClient( - 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 = gsma_homepage.UpdateHomepageRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_homepage(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gsma_homepage.UpdateHomepageRequest( - ) - -def test_update_homepage_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 = HomepageServiceClient( - 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.update_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc - request = {} - client.update_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_homepage(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_update_homepage_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 = HomepageServiceAsyncClient( - 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.update_homepage in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_homepage] = mock_rpc - - request = {} - await client.update_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_homepage(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_update_homepage_async(transport: str = 'grpc_asyncio', request_type=gsma_homepage.UpdateHomepageRequest): - client = HomepageServiceAsyncClient( - 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.update_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - response = await client.update_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gsma_homepage.UpdateHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.asyncio -async def test_update_homepage_async_from_dict(): - await test_update_homepage_async(request_type=dict) - -def test_update_homepage_field_headers(): - client = HomepageServiceClient( - 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 = gsma_homepage.UpdateHomepageRequest() - - request.homepage.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - call.return_value = gsma_homepage.Homepage() - client.update_homepage(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', - 'homepage.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_homepage_field_headers_async(): - client = HomepageServiceAsyncClient( - 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 = gsma_homepage.UpdateHomepageRequest() - - request.homepage.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) - await client.update_homepage(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', - 'homepage.name=name_value', - ) in kw['metadata'] - - -def test_update_homepage_flattened(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_homepage.Homepage() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_homepage( - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].homepage - mock_val = gsma_homepage.Homepage(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_homepage_flattened_error(): - client = HomepageServiceClient( - 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.update_homepage( - gsma_homepage.UpdateHomepageRequest(), - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_homepage_flattened_async(): - client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_homepage.Homepage() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_homepage( - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].homepage - mock_val = gsma_homepage.Homepage(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_homepage_flattened_error_async(): - client = HomepageServiceAsyncClient( - 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.update_homepage( - gsma_homepage.UpdateHomepageRequest(), - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - homepage.ClaimHomepageRequest, - dict, -]) -def test_claim_homepage(request_type, transport: str = 'grpc'): - client = HomepageServiceClient( - 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.claim_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - response = client.claim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = homepage.ClaimHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -def test_claim_homepage_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 = HomepageServiceClient( - 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 = homepage.ClaimHomepageRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.claim_homepage(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == homepage.ClaimHomepageRequest( - name='name_value', - ) - -def test_claim_homepage_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 = HomepageServiceClient( - 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.claim_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc - request = {} - client.claim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.claim_homepage(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_claim_homepage_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 = HomepageServiceAsyncClient( - 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.claim_homepage 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.claim_homepage] = mock_rpc - - request = {} - await client.claim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.claim_homepage(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_claim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.ClaimHomepageRequest): - client = HomepageServiceAsyncClient( - 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.claim_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - response = await client.claim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = homepage.ClaimHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.asyncio -async def test_claim_homepage_async_from_dict(): - await test_claim_homepage_async(request_type=dict) - -def test_claim_homepage_field_headers(): - client = HomepageServiceClient( - 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 = homepage.ClaimHomepageRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: - call.return_value = homepage.Homepage() - client.claim_homepage(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_claim_homepage_field_headers_async(): - client = HomepageServiceAsyncClient( - 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 = homepage.ClaimHomepageRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) - await client.claim_homepage(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'] - - -@pytest.mark.parametrize("request_type", [ - homepage.UnclaimHomepageRequest, - dict, -]) -def test_unclaim_homepage(request_type, transport: str = 'grpc'): - client = HomepageServiceClient( - 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.unclaim_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - response = client.unclaim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = homepage.UnclaimHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -def test_unclaim_homepage_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 = HomepageServiceClient( - 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 = homepage.UnclaimHomepageRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.unclaim_homepage(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == homepage.UnclaimHomepageRequest( - name='name_value', - ) - -def test_unclaim_homepage_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 = HomepageServiceClient( - 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.unclaim_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc - request = {} - client.unclaim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.unclaim_homepage(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_unclaim_homepage_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 = HomepageServiceAsyncClient( - 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.unclaim_homepage 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.unclaim_homepage] = mock_rpc - - request = {} - await client.unclaim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.unclaim_homepage(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_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.UnclaimHomepageRequest): - client = HomepageServiceAsyncClient( - 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.unclaim_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - response = await client.unclaim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = homepage.UnclaimHomepageRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.asyncio -async def test_unclaim_homepage_async_from_dict(): - await test_unclaim_homepage_async(request_type=dict) - -def test_unclaim_homepage_field_headers(): - client = HomepageServiceClient( - 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 = homepage.UnclaimHomepageRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: - call.return_value = homepage.Homepage() - client.unclaim_homepage(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_unclaim_homepage_field_headers_async(): - client = HomepageServiceAsyncClient( - 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 = homepage.UnclaimHomepageRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) - await client.unclaim_homepage(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_get_homepage_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 = HomepageServiceClient( - 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.get_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc - - request = {} - client.get_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_homepage(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_get_homepage_rest_required_fields(request_type=homepage.GetHomepageRequest): - transport_class = transports.HomepageServiceRestTransport - - 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()).get_homepage._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_homepage._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 = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = homepage.Homepage() - # 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 = homepage.Homepage.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.get_homepage(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_homepage_rest_flattened(): - client = HomepageServiceClient( - 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 = homepage.Homepage() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/homepage'} - - # 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 - # Convert return value to protobuf type - return_value = homepage.Homepage.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.get_homepage(**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/accounts/v1beta/{name=accounts/*/homepage}" % client.transport._host, args[1]) - - -def test_get_homepage_rest_flattened_error(transport: str = 'rest'): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_homepage( - homepage.GetHomepageRequest(), - name='name_value', - ) - - -def test_update_homepage_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 = HomepageServiceClient( - 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.update_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc - - request = {} - client.update_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_homepage(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_update_homepage_rest_required_fields(request_type=gsma_homepage.UpdateHomepageRequest): - transport_class = transports.HomepageServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gsma_homepage.Homepage() - # 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': "patch", - '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 = gsma_homepage.Homepage.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.update_homepage(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("homepage", "updateMask", ))) - - -def test_update_homepage_rest_flattened(): - client = HomepageServiceClient( - 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 = gsma_homepage.Homepage() - - # get arguments that satisfy an http rule for this method - sample_request = {'homepage': {'name': 'accounts/sample1/homepage'}} - - # get truthy value for each flattened field - mock_args = dict( - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_homepage.Homepage.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.update_homepage(**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/accounts/v1beta/{homepage.name=accounts/*/homepage}" % client.transport._host, args[1]) - - -def test_update_homepage_rest_flattened_error(transport: str = 'rest'): - client = HomepageServiceClient( - 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.update_homepage( - gsma_homepage.UpdateHomepageRequest(), - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_claim_homepage_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 = HomepageServiceClient( - 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.claim_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc - - request = {} - client.claim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.claim_homepage(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_claim_homepage_rest_required_fields(request_type=homepage.ClaimHomepageRequest): - transport_class = transports.HomepageServiceRestTransport - - 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()).claim_homepage._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()).claim_homepage._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 = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = homepage.Homepage() - # 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 = homepage.Homepage.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.claim_homepage(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_claim_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.claim_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_unclaim_homepage_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 = HomepageServiceClient( - 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.unclaim_homepage in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc - - request = {} - client.unclaim_homepage(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.unclaim_homepage(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_unclaim_homepage_rest_required_fields(request_type=homepage.UnclaimHomepageRequest): - transport_class = transports.HomepageServiceRestTransport - - 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()).unclaim_homepage._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()).unclaim_homepage._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 = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = homepage.Homepage() - # 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 = homepage.Homepage.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.unclaim_homepage(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_unclaim_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.unclaim_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.HomepageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.HomepageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = HomepageServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.HomepageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = HomepageServiceClient( - 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 = HomepageServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.HomepageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = HomepageServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.HomepageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = HomepageServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.HomepageServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.HomepageServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.HomepageServiceGrpcTransport, - transports.HomepageServiceGrpcAsyncIOTransport, - transports.HomepageServiceRestTransport, -]) -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 = HomepageServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = HomepageServiceClient( - 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_get_homepage_empty_call_grpc(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - call.return_value = homepage.Homepage() - client.get_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.GetHomepageRequest() - - 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_update_homepage_empty_call_grpc(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - call.return_value = gsma_homepage.Homepage() - client.update_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_homepage.UpdateHomepageRequest() - - 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_claim_homepage_empty_call_grpc(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: - call.return_value = homepage.Homepage() - client.claim_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.ClaimHomepageRequest() - - 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_unclaim_homepage_empty_call_grpc(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: - call.return_value = homepage.Homepage() - client.unclaim_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.UnclaimHomepageRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = HomepageServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = HomepageServiceAsyncClient( - 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_get_homepage_empty_call_grpc_asyncio(): - client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - await client.get_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.GetHomepageRequest() - - 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_update_homepage_empty_call_grpc_asyncio(): - client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - await client.update_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_homepage.UpdateHomepageRequest() - - 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_claim_homepage_empty_call_grpc_asyncio(): - client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - await client.claim_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.ClaimHomepageRequest() - - 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_unclaim_homepage_empty_call_grpc_asyncio(): - client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) - await client.unclaim_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.UnclaimHomepageRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = HomepageServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_homepage_rest_bad_request(request_type=homepage.GetHomepageRequest): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} - 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.get_homepage(request) - - -@pytest.mark.parametrize("request_type", [ - homepage.GetHomepageRequest, - dict, -]) -def test_get_homepage_rest_call_success(request_type): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} - request = request_type(**request_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 = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - - # 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 = homepage.Homepage.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.get_homepage(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_homepage_rest_interceptors(null_interceptor): - transport = transports.HomepageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) - client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_get_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_get_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_get_homepage") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = homepage.GetHomepageRequest.pb(homepage.GetHomepageRequest()) - 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 = homepage.Homepage.to_json(homepage.Homepage()) - req.return_value.content = return_value - - request = homepage.GetHomepageRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = homepage.Homepage() - post_with_metadata.return_value = homepage.Homepage(), metadata - - client.get_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_homepage_rest_bad_request(request_type=gsma_homepage.UpdateHomepageRequest): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} - 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.update_homepage(request) - - -@pytest.mark.parametrize("request_type", [ - gsma_homepage.UpdateHomepageRequest, - dict, -]) -def test_update_homepage_rest_call_success(request_type): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} - request_init["homepage"] = {'name': 'accounts/sample1/homepage', 'uri': 'uri_value', 'claimed': True} - # 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 = gsma_homepage.UpdateHomepageRequest.meta.fields["homepage"] - - 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["homepage"].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["homepage"][field])): - del request_init["homepage"][field][i][subfield] - else: - del request_init["homepage"][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 = gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - - # 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 = gsma_homepage.Homepage.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.update_homepage(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_homepage_rest_interceptors(null_interceptor): - transport = transports.HomepageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) - client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_update_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_update_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_update_homepage") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gsma_homepage.UpdateHomepageRequest.pb(gsma_homepage.UpdateHomepageRequest()) - 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 = gsma_homepage.Homepage.to_json(gsma_homepage.Homepage()) - req.return_value.content = return_value - - request = gsma_homepage.UpdateHomepageRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gsma_homepage.Homepage() - post_with_metadata.return_value = gsma_homepage.Homepage(), metadata - - client.update_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_claim_homepage_rest_bad_request(request_type=homepage.ClaimHomepageRequest): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} - 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.claim_homepage(request) - - -@pytest.mark.parametrize("request_type", [ - homepage.ClaimHomepageRequest, - dict, -]) -def test_claim_homepage_rest_call_success(request_type): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} - request = request_type(**request_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 = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - - # 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 = homepage.Homepage.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.claim_homepage(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_claim_homepage_rest_interceptors(null_interceptor): - transport = transports.HomepageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) - client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_claim_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_claim_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_claim_homepage") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = homepage.ClaimHomepageRequest.pb(homepage.ClaimHomepageRequest()) - 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 = homepage.Homepage.to_json(homepage.Homepage()) - req.return_value.content = return_value - - request = homepage.ClaimHomepageRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = homepage.Homepage() - post_with_metadata.return_value = homepage.Homepage(), metadata - - client.claim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_unclaim_homepage_rest_bad_request(request_type=homepage.UnclaimHomepageRequest): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} - 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.unclaim_homepage(request) - - -@pytest.mark.parametrize("request_type", [ - homepage.UnclaimHomepageRequest, - dict, -]) -def test_unclaim_homepage_rest_call_success(request_type): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} - request = request_type(**request_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 = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - ) - - # 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 = homepage.Homepage.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.unclaim_homepage(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' - assert response.claimed is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_unclaim_homepage_rest_interceptors(null_interceptor): - transport = transports.HomepageServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) - client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_unclaim_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_unclaim_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_unclaim_homepage") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = homepage.UnclaimHomepageRequest.pb(homepage.UnclaimHomepageRequest()) - 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 = homepage.Homepage.to_json(homepage.Homepage()) - req.return_value.content = return_value - - request = homepage.UnclaimHomepageRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = homepage.Homepage() - post_with_metadata.return_value = homepage.Homepage(), metadata - - client.unclaim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = HomepageServiceClient( - 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_get_homepage_empty_call_rest(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - client.get_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.GetHomepageRequest() - - 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_update_homepage_empty_call_rest(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - client.update_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_homepage.UpdateHomepageRequest() - - 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_claim_homepage_empty_call_rest(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: - client.claim_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.ClaimHomepageRequest() - - 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_unclaim_homepage_empty_call_rest(): - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: - client.unclaim_homepage(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = homepage.UnclaimHomepageRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.HomepageServiceGrpcTransport, - ) - -def test_homepage_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.HomepageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_homepage_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.homepage_service.transports.HomepageServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.HomepageServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_homepage', - 'update_homepage', - 'claim_homepage', - 'unclaim_homepage', - ) - 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_homepage_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_accounts_v1beta.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.HomepageServiceTransport( - 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_homepage_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_accounts_v1beta.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.HomepageServiceTransport() - adc.assert_called_once() - - -def test_homepage_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) - HomepageServiceClient() - 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.HomepageServiceGrpcTransport, - transports.HomepageServiceGrpcAsyncIOTransport, - ], -) -def test_homepage_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.HomepageServiceGrpcTransport, - transports.HomepageServiceGrpcAsyncIOTransport, - transports.HomepageServiceRestTransport, - ], -) -def test_homepage_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.HomepageServiceGrpcTransport, grpc_helpers), - (transports.HomepageServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) -def test_homepage_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_homepage_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.HomepageServiceRestTransport ( - 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_homepage_service_host_no_port(transport_name): - client = HomepageServiceClient( - 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_homepage_service_host_with_port(transport_name): - client = HomepageServiceClient( - 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_homepage_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = HomepageServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = HomepageServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_homepage._session - session2 = client2.transport.get_homepage._session - assert session1 != session2 - session1 = client1.transport.update_homepage._session - session2 = client2.transport.update_homepage._session - assert session1 != session2 - session1 = client1.transport.claim_homepage._session - session2 = client2.transport.claim_homepage._session - assert session1 != session2 - session1 = client1.transport.unclaim_homepage._session - session2 = client2.transport.unclaim_homepage._session - assert session1 != session2 -def test_homepage_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.HomepageServiceGrpcTransport( - 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_homepage_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.HomepageServiceGrpcAsyncIOTransport( - 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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) -def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) -def test_homepage_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_homepage_path(): - account = "squid" - expected = "accounts/{account}/homepage".format(account=account, ) - actual = HomepageServiceClient.homepage_path(account) - assert expected == actual - - -def test_parse_homepage_path(): - expected = { - "account": "clam", - } - path = HomepageServiceClient.homepage_path(**expected) - - # Check that the path construction is reversible. - actual = HomepageServiceClient.parse_homepage_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = HomepageServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = HomepageServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = HomepageServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = HomepageServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = HomepageServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = HomepageServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = HomepageServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = HomepageServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = HomepageServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = HomepageServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = HomepageServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = HomepageServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = HomepageServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = HomepageServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = HomepageServiceClient.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.HomepageServiceTransport, '_prep_wrapped_messages') as prep: - client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.HomepageServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = HomepageServiceClient.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 = HomepageServiceClient( - 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 = HomepageServiceAsyncClient( - 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 = HomepageServiceClient( - 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 = HomepageServiceClient( - 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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py deleted file mode 100644 index 1062b5e21719..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_lfp_providers_service.py +++ /dev/null @@ -1,3076 +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 empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import LfpProvidersServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import LfpProvidersServiceClient -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import pagers -from google.shopping.merchant_accounts_v1beta.services.lfp_providers_service import transports -from google.shopping.merchant_accounts_v1beta.types import lfpproviders -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 LfpProvidersServiceClient._get_default_mtls_endpoint(None) is None - assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LfpProvidersServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - LfpProvidersServiceClient._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 LfpProvidersServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpProvidersServiceClient._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 LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, False) is None - assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert LfpProvidersServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpProvidersServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LfpProvidersServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LfpProvidersServiceClient._get_universe_domain(None, None) == LfpProvidersServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - LfpProvidersServiceClient._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 = LfpProvidersServiceClient(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 = LfpProvidersServiceClient(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", [ - (LfpProvidersServiceClient, "grpc"), - (LfpProvidersServiceAsyncClient, "grpc_asyncio"), - (LfpProvidersServiceClient, "rest"), -]) -def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, "grpc"), - (transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LfpProvidersServiceRestTransport, "rest"), -]) -def test_lfp_providers_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", [ - (LfpProvidersServiceClient, "grpc"), - (LfpProvidersServiceAsyncClient, "grpc_asyncio"), - (LfpProvidersServiceClient, "rest"), -]) -def test_lfp_providers_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_lfp_providers_service_client_get_transport_class(): - transport = LfpProvidersServiceClient.get_transport_class() - available_transports = [ - transports.LfpProvidersServiceGrpcTransport, - transports.LfpProvidersServiceRestTransport, - ] - assert transport in available_transports - - transport = LfpProvidersServiceClient.get_transport_class("grpc") - assert transport == transports.LfpProvidersServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), -]) -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) -def test_lfp_providers_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(LfpProvidersServiceClient, '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(LfpProvidersServiceClient, '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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "true"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "false"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "true"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lfp_providers_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", [ - LfpProvidersServiceClient, LfpProvidersServiceAsyncClient -]) -@mock.patch.object(LfpProvidersServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceAsyncClient)) -def test_lfp_providers_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", [ - LfpProvidersServiceClient, LfpProvidersServiceAsyncClient -]) -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) -def test_lfp_providers_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = LfpProvidersServiceClient._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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), -]) -def test_lfp_providers_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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", None), -]) -def test_lfp_providers_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_lfp_providers_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = LfpProvidersServiceClient( - 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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_lfp_providers_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", [ - lfpproviders.FindLfpProvidersRequest, - dict, -]) -def test_find_lfp_providers(request_type, transport: str = 'grpc'): - client = LfpProvidersServiceClient( - 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.find_lfp_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', - ) - response = client.find_lfp_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpproviders.FindLfpProvidersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FindLfpProvidersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_find_lfp_providers_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 = LfpProvidersServiceClient( - 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 = lfpproviders.FindLfpProvidersRequest( - 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.find_lfp_providers), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.find_lfp_providers(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpproviders.FindLfpProvidersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_find_lfp_providers_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 = LfpProvidersServiceClient( - 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.find_lfp_providers in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc - request = {} - client.find_lfp_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.find_lfp_providers(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_find_lfp_providers_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 = LfpProvidersServiceAsyncClient( - 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.find_lfp_providers 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.find_lfp_providers] = mock_rpc - - request = {} - await client.find_lfp_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.find_lfp_providers(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_find_lfp_providers_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.FindLfpProvidersRequest): - client = LfpProvidersServiceAsyncClient( - 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.find_lfp_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', - )) - response = await client.find_lfp_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpproviders.FindLfpProvidersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FindLfpProvidersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_find_lfp_providers_async_from_dict(): - await test_find_lfp_providers_async(request_type=dict) - -def test_find_lfp_providers_field_headers(): - client = LfpProvidersServiceClient( - 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 = lfpproviders.FindLfpProvidersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - call.return_value = lfpproviders.FindLfpProvidersResponse() - client.find_lfp_providers(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_find_lfp_providers_field_headers_async(): - client = LfpProvidersServiceAsyncClient( - 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 = lfpproviders.FindLfpProvidersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) - await client.find_lfp_providers(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_find_lfp_providers_flattened(): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpproviders.FindLfpProvidersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.find_lfp_providers( - 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_find_lfp_providers_flattened_error(): - client = LfpProvidersServiceClient( - 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.find_lfp_providers( - lfpproviders.FindLfpProvidersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_find_lfp_providers_flattened_async(): - client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpproviders.FindLfpProvidersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.find_lfp_providers( - 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_find_lfp_providers_flattened_error_async(): - client = LfpProvidersServiceAsyncClient( - 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.find_lfp_providers( - lfpproviders.FindLfpProvidersRequest(), - parent='parent_value', - ) - - -def test_find_lfp_providers_pager(transport_name: str = "grpc"): - client = LfpProvidersServiceClient( - 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.find_lfp_providers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - next_page_token='abc', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[], - next_page_token='def', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - ], - next_page_token='ghi', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.find_lfp_providers(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, lfpproviders.LfpProvider) - for i in results) -def test_find_lfp_providers_pages(transport_name: str = "grpc"): - client = LfpProvidersServiceClient( - 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.find_lfp_providers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - next_page_token='abc', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[], - next_page_token='def', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - ], - next_page_token='ghi', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - ), - RuntimeError, - ) - pages = list(client.find_lfp_providers(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_find_lfp_providers_async_pager(): - client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - next_page_token='abc', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[], - next_page_token='def', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - ], - next_page_token='ghi', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - ), - RuntimeError, - ) - async_pager = await client.find_lfp_providers(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, lfpproviders.LfpProvider) - for i in responses) - - -@pytest.mark.asyncio -async def test_find_lfp_providers_async_pages(): - client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - next_page_token='abc', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[], - next_page_token='def', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - ], - next_page_token='ghi', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - ), - 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.find_lfp_providers(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", [ - lfpproviders.LinkLfpProviderRequest, - dict, -]) -def test_link_lfp_provider(request_type, transport: str = 'grpc'): - client = LfpProvidersServiceClient( - 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.link_lfp_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpproviders.LinkLfpProviderResponse( - ) - response = client.link_lfp_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = lfpproviders.LinkLfpProviderRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpproviders.LinkLfpProviderResponse) - - -def test_link_lfp_provider_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 = LfpProvidersServiceClient( - 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 = lfpproviders.LinkLfpProviderRequest( - name='name_value', - external_account_id='external_account_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.link_lfp_provider(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == lfpproviders.LinkLfpProviderRequest( - name='name_value', - external_account_id='external_account_id_value', - ) - -def test_link_lfp_provider_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 = LfpProvidersServiceClient( - 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.link_lfp_provider in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc - request = {} - client.link_lfp_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.link_lfp_provider(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_link_lfp_provider_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 = LfpProvidersServiceAsyncClient( - 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.link_lfp_provider 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.link_lfp_provider] = mock_rpc - - request = {} - await client.link_lfp_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.link_lfp_provider(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_link_lfp_provider_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.LinkLfpProviderRequest): - client = LfpProvidersServiceAsyncClient( - 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.link_lfp_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( - )) - response = await client.link_lfp_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = lfpproviders.LinkLfpProviderRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpproviders.LinkLfpProviderResponse) - - -@pytest.mark.asyncio -async def test_link_lfp_provider_async_from_dict(): - await test_link_lfp_provider_async(request_type=dict) - -def test_link_lfp_provider_field_headers(): - client = LfpProvidersServiceClient( - 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 = lfpproviders.LinkLfpProviderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - call.return_value = lfpproviders.LinkLfpProviderResponse() - client.link_lfp_provider(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_link_lfp_provider_field_headers_async(): - client = LfpProvidersServiceAsyncClient( - 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 = lfpproviders.LinkLfpProviderRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) - await client.link_lfp_provider(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_link_lfp_provider_flattened(): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpproviders.LinkLfpProviderResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.link_lfp_provider( - 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_link_lfp_provider_flattened_error(): - client = LfpProvidersServiceClient( - 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.link_lfp_provider( - lfpproviders.LinkLfpProviderRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_link_lfp_provider_flattened_async(): - client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = lfpproviders.LinkLfpProviderResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.link_lfp_provider( - 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_link_lfp_provider_flattened_error_async(): - client = LfpProvidersServiceAsyncClient( - 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.link_lfp_provider( - lfpproviders.LinkLfpProviderRequest(), - name='name_value', - ) - - -def test_find_lfp_providers_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 = LfpProvidersServiceClient( - 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.find_lfp_providers in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc - - request = {} - client.find_lfp_providers(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.find_lfp_providers(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_find_lfp_providers_rest_required_fields(request_type=lfpproviders.FindLfpProvidersRequest): - transport_class = transports.LfpProvidersServiceRestTransport - - 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()).find_lfp_providers._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()).find_lfp_providers._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 = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpproviders.FindLfpProvidersResponse() - # 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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_find_lfp_providers_rest_unset_required_fields(): - transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.find_lfp_providers._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_find_lfp_providers_rest_flattened(): - client = LfpProvidersServiceClient( - 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 = lfpproviders.FindLfpProvidersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(**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/accounts/v1beta/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find" % client.transport._host, args[1]) - - -def test_find_lfp_providers_rest_flattened_error(transport: str = 'rest'): - client = LfpProvidersServiceClient( - 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.find_lfp_providers( - lfpproviders.FindLfpProvidersRequest(), - parent='parent_value', - ) - - -def test_find_lfp_providers_rest_pager(transport: str = 'rest'): - client = LfpProvidersServiceClient( - 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 = ( - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - next_page_token='abc', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[], - next_page_token='def', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - ], - next_page_token='ghi', - ), - lfpproviders.FindLfpProvidersResponse( - lfp_providers=[ - lfpproviders.LfpProvider(), - lfpproviders.LfpProvider(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(lfpproviders.FindLfpProvidersResponse.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/omnichannelSettings/sample2'} - - pager = client.find_lfp_providers(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, lfpproviders.LfpProvider) - for i in results) - - pages = list(client.find_lfp_providers(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_link_lfp_provider_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 = LfpProvidersServiceClient( - 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.link_lfp_provider in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc - - request = {} - client.link_lfp_provider(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.link_lfp_provider(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_link_lfp_provider_rest_required_fields(request_type=lfpproviders.LinkLfpProviderRequest): - transport_class = transports.LfpProvidersServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["external_account_id"] = "" - 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()).link_lfp_provider._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["externalAccountId"] = 'external_account_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_lfp_provider._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 "externalAccountId" in jsonified_request - assert jsonified_request["externalAccountId"] == 'external_account_id_value' - - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = lfpproviders.LinkLfpProviderResponse() - # 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 = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_link_lfp_provider_rest_unset_required_fields(): - transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.link_lfp_provider._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "externalAccountId", ))) - - -def test_link_lfp_provider_rest_flattened(): - client = LfpProvidersServiceClient( - 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 = lfpproviders.LinkLfpProviderResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 - # Convert return value to protobuf type - return_value = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(**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/accounts/v1beta/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider" % client.transport._host, args[1]) - - -def test_link_lfp_provider_rest_flattened_error(transport: str = 'rest'): - client = LfpProvidersServiceClient( - 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.link_lfp_provider( - lfpproviders.LinkLfpProviderRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LfpProvidersServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.LfpProvidersServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpProvidersServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.LfpProvidersServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = LfpProvidersServiceClient( - 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 = LfpProvidersServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.LfpProvidersServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = LfpProvidersServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpProvidersServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = LfpProvidersServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.LfpProvidersServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.LfpProvidersServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.LfpProvidersServiceGrpcTransport, - transports.LfpProvidersServiceGrpcAsyncIOTransport, - transports.LfpProvidersServiceRestTransport, -]) -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 = LfpProvidersServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = LfpProvidersServiceClient( - 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_find_lfp_providers_empty_call_grpc(): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - call.return_value = lfpproviders.FindLfpProvidersResponse() - client.find_lfp_providers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpproviders.FindLfpProvidersRequest() - - 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_link_lfp_provider_empty_call_grpc(): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - call.return_value = lfpproviders.LinkLfpProviderResponse() - client.link_lfp_provider(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpproviders.LinkLfpProviderRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = LfpProvidersServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = LfpProvidersServiceAsyncClient( - 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_find_lfp_providers_empty_call_grpc_asyncio(): - client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', - )) - await client.find_lfp_providers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpproviders.FindLfpProvidersRequest() - - 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_link_lfp_provider_empty_call_grpc_asyncio(): - client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( - )) - await client.link_lfp_provider(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpproviders.LinkLfpProviderRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = LfpProvidersServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_find_lfp_providers_rest_bad_request(request_type=lfpproviders.FindLfpProvidersRequest): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/omnichannelSettings/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.find_lfp_providers(request) - - -@pytest.mark.parametrize("request_type", [ - lfpproviders.FindLfpProvidersRequest, - dict, -]) -def test_find_lfp_providers_rest_call_success(request_type): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse( - 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 = lfpproviders.FindLfpProvidersResponse.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.find_lfp_providers(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FindLfpProvidersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_find_lfp_providers_rest_interceptors(null_interceptor): - transport = transports.LfpProvidersServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), - ) - client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers") as post, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_find_lfp_providers") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = lfpproviders.FindLfpProvidersRequest.pb(lfpproviders.FindLfpProvidersRequest()) - 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 = lfpproviders.FindLfpProvidersResponse.to_json(lfpproviders.FindLfpProvidersResponse()) - req.return_value.content = return_value - - request = lfpproviders.FindLfpProvidersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpproviders.FindLfpProvidersResponse() - post_with_metadata.return_value = lfpproviders.FindLfpProvidersResponse(), metadata - - client.find_lfp_providers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_link_lfp_provider_rest_bad_request(request_type=lfpproviders.LinkLfpProviderRequest): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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.link_lfp_provider(request) - - -@pytest.mark.parametrize("request_type", [ - lfpproviders.LinkLfpProviderRequest, - dict, -]) -def test_link_lfp_provider_rest_call_success(request_type): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 = lfpproviders.LinkLfpProviderResponse( - ) - - # 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 = lfpproviders.LinkLfpProviderResponse.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.link_lfp_provider(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, lfpproviders.LinkLfpProviderResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_link_lfp_provider_rest_interceptors(null_interceptor): - transport = transports.LfpProvidersServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), - ) - client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider") as post, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_link_lfp_provider") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = lfpproviders.LinkLfpProviderRequest.pb(lfpproviders.LinkLfpProviderRequest()) - 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 = lfpproviders.LinkLfpProviderResponse.to_json(lfpproviders.LinkLfpProviderResponse()) - req.return_value.content = return_value - - request = lfpproviders.LinkLfpProviderRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = lfpproviders.LinkLfpProviderResponse() - post_with_metadata.return_value = lfpproviders.LinkLfpProviderResponse(), metadata - - client.link_lfp_provider(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = LfpProvidersServiceClient( - 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_find_lfp_providers_empty_call_rest(): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: - client.find_lfp_providers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpproviders.FindLfpProvidersRequest() - - 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_link_lfp_provider_empty_call_rest(): - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - client.link_lfp_provider(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = lfpproviders.LinkLfpProviderRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.LfpProvidersServiceGrpcTransport, - ) - -def test_lfp_providers_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.LfpProvidersServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_lfp_providers_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.LfpProvidersServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'find_lfp_providers', - 'link_lfp_provider', - ) - 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_lfp_providers_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_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpProvidersServiceTransport( - 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_lfp_providers_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_accounts_v1beta.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.LfpProvidersServiceTransport() - adc.assert_called_once() - - -def test_lfp_providers_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) - LfpProvidersServiceClient() - 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.LfpProvidersServiceGrpcTransport, - transports.LfpProvidersServiceGrpcAsyncIOTransport, - ], -) -def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, - transports.LfpProvidersServiceGrpcAsyncIOTransport, - transports.LfpProvidersServiceRestTransport, - ], -) -def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, grpc_helpers), - (transports.LfpProvidersServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) -def test_lfp_providers_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_lfp_providers_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.LfpProvidersServiceRestTransport ( - 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_lfp_providers_service_host_no_port(transport_name): - client = LfpProvidersServiceClient( - 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_lfp_providers_service_host_with_port(transport_name): - client = LfpProvidersServiceClient( - 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_lfp_providers_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = LfpProvidersServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = LfpProvidersServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.find_lfp_providers._session - session2 = client2.transport.find_lfp_providers._session - assert session1 != session2 - session1 = client1.transport.link_lfp_provider._session - session2 = client2.transport.link_lfp_provider._session - assert session1 != session2 -def test_lfp_providers_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpProvidersServiceGrpcTransport( - 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_lfp_providers_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.LfpProvidersServiceGrpcAsyncIOTransport( - 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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) -def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) -def test_lfp_providers_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_lfp_provider_path(): - account = "squid" - omnichannel_setting = "clam" - lfp_provider = "whelk" - expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) - actual = LfpProvidersServiceClient.lfp_provider_path(account, omnichannel_setting, lfp_provider) - assert expected == actual - - -def test_parse_lfp_provider_path(): - expected = { - "account": "octopus", - "omnichannel_setting": "oyster", - "lfp_provider": "nudibranch", - } - path = LfpProvidersServiceClient.lfp_provider_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.parse_lfp_provider_path(path) - assert expected == actual - -def test_omnichannel_setting_path(): - account = "cuttlefish" - omnichannel_setting = "mussel" - expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) - actual = LfpProvidersServiceClient.omnichannel_setting_path(account, omnichannel_setting) - assert expected == actual - - -def test_parse_omnichannel_setting_path(): - expected = { - "account": "winkle", - "omnichannel_setting": "nautilus", - } - path = LfpProvidersServiceClient.omnichannel_setting_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.parse_omnichannel_setting_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = LfpProvidersServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = LfpProvidersServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = LfpProvidersServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = LfpProvidersServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = LfpProvidersServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = LfpProvidersServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = LfpProvidersServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = LfpProvidersServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = LfpProvidersServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = LfpProvidersServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = LfpProvidersServiceClient.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.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: - client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = LfpProvidersServiceClient.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 = LfpProvidersServiceClient( - 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 = LfpProvidersServiceAsyncClient( - 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 = LfpProvidersServiceClient( - 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 = LfpProvidersServiceClient( - 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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py deleted file mode 100644 index ffb35c285cf6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_omnichannel_settings_service.py +++ /dev/null @@ -1,5231 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import OmnichannelSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import pagers -from google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service import transports -from google.shopping.merchant_accounts_v1beta.types import omnichannelsettings -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 OmnichannelSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, False) is None - assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert OmnichannelSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert OmnichannelSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert OmnichannelSettingsServiceClient._get_universe_domain(None, None) == OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient(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 = OmnichannelSettingsServiceClient(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", [ - (OmnichannelSettingsServiceClient, "grpc"), - (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, "rest"), -]) -def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, "grpc"), - (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.OmnichannelSettingsServiceRestTransport, "rest"), -]) -def test_omnichannel_settings_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", [ - (OmnichannelSettingsServiceClient, "grpc"), - (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, "rest"), -]) -def test_omnichannel_settings_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_omnichannel_settings_service_client_get_transport_class(): - transport = OmnichannelSettingsServiceClient.get_transport_class() - available_transports = [ - transports.OmnichannelSettingsServiceGrpcTransport, - transports.OmnichannelSettingsServiceRestTransport, - ] - assert transport in available_transports - - transport = OmnichannelSettingsServiceClient.get_transport_class("grpc") - assert transport == transports.OmnichannelSettingsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) -def test_omnichannel_settings_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(OmnichannelSettingsServiceClient, '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(OmnichannelSettingsServiceClient, '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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "true"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "false"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "true"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_omnichannel_settings_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", [ - OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceAsyncClient)) -def test_omnichannel_settings_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", [ - OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) -def test_omnichannel_settings_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = OmnichannelSettingsServiceClient._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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), -]) -def test_omnichannel_settings_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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", None), -]) -def test_omnichannel_settings_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_omnichannel_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = OmnichannelSettingsServiceClient( - 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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_omnichannel_settings_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", [ - omnichannelsettings.GetOmnichannelSettingRequest, - dict, -]) -def test_get_omnichannel_setting(request_type, transport: str = 'grpc'): - client = OmnichannelSettingsServiceClient( - 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.get_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - ) - response = client.get_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.GetOmnichannelSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.GetOmnichannelSettingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_omnichannel_setting(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == omnichannelsettings.GetOmnichannelSettingRequest( - name='name_value', - ) - -def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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.get_omnichannel_setting in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc - request = {} - client.get_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_omnichannel_setting(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_get_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( - 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.get_omnichannel_setting in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_omnichannel_setting] = mock_rpc - - request = {} - await client.get_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_omnichannel_setting(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_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.GetOmnichannelSettingRequest): - client = OmnichannelSettingsServiceAsyncClient( - 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.get_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) - response = await client.get_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.GetOmnichannelSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -@pytest.mark.asyncio -async def test_get_omnichannel_setting_async_from_dict(): - await test_get_omnichannel_setting_async(request_type=dict) - -def test_get_omnichannel_setting_field_headers(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.GetOmnichannelSettingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - call.return_value = omnichannelsettings.OmnichannelSetting() - client.get_omnichannel_setting(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_get_omnichannel_setting_field_headers_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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 = omnichannelsettings.GetOmnichannelSettingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) - await client.get_omnichannel_setting(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_get_omnichannel_setting_flattened(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_omnichannel_setting( - 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_get_omnichannel_setting_flattened_error(): - client = OmnichannelSettingsServiceClient( - 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.get_omnichannel_setting( - omnichannelsettings.GetOmnichannelSettingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_omnichannel_setting_flattened_async(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_omnichannel_setting( - 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_get_omnichannel_setting_flattened_error_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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.get_omnichannel_setting( - omnichannelsettings.GetOmnichannelSettingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.ListOmnichannelSettingsRequest, - dict, -]) -def test_list_omnichannel_settings(request_type, transport: str = 'grpc'): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_omnichannel_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.ListOmnichannelSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOmnichannelSettingsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.ListOmnichannelSettingsRequest( - 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_omnichannel_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_omnichannel_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == omnichannelsettings.ListOmnichannelSettingsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( - 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_omnichannel_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_omnichannel_settings] = mock_rpc - request = {} - client.list_omnichannel_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_omnichannel_settings(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_omnichannel_settings_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 = OmnichannelSettingsServiceAsyncClient( - 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_omnichannel_settings 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_omnichannel_settings] = mock_rpc - - request = {} - await client.list_omnichannel_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_omnichannel_settings(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_omnichannel_settings_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.ListOmnichannelSettingsRequest): - client = OmnichannelSettingsServiceAsyncClient( - 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_omnichannel_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_omnichannel_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.ListOmnichannelSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOmnichannelSettingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_omnichannel_settings_async_from_dict(): - await test_list_omnichannel_settings_async(request_type=dict) - -def test_list_omnichannel_settings_field_headers(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.ListOmnichannelSettingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - client.list_omnichannel_settings(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_omnichannel_settings_field_headers_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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 = omnichannelsettings.ListOmnichannelSettingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) - await client.list_omnichannel_settings(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_omnichannel_settings_flattened(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_omnichannel_settings( - 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_omnichannel_settings_flattened_error(): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings( - omnichannelsettings.ListOmnichannelSettingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_omnichannel_settings_flattened_async(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_omnichannel_settings( - 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_omnichannel_settings_flattened_error_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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_omnichannel_settings( - omnichannelsettings.ListOmnichannelSettingsRequest(), - parent='parent_value', - ) - - -def test_list_omnichannel_settings_pager(transport_name: str = "grpc"): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='abc', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[], - next_page_token='def', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='ghi', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_omnichannel_settings(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, omnichannelsettings.OmnichannelSetting) - for i in results) -def test_list_omnichannel_settings_pages(transport_name: str = "grpc"): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='abc', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[], - next_page_token='def', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='ghi', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - ), - RuntimeError, - ) - pages = list(client.list_omnichannel_settings(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_omnichannel_settings_async_pager(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='abc', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[], - next_page_token='def', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='ghi', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_omnichannel_settings(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, omnichannelsettings.OmnichannelSetting) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_omnichannel_settings_async_pages(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='abc', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[], - next_page_token='def', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='ghi', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - ), - 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_omnichannel_settings(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", [ - omnichannelsettings.CreateOmnichannelSettingRequest, - dict, -]) -def test_create_omnichannel_setting(request_type, transport: str = 'grpc'): - client = OmnichannelSettingsServiceClient( - 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.create_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - ) - response = client.create_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.CreateOmnichannelSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.CreateOmnichannelSettingRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_omnichannel_setting(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == omnichannelsettings.CreateOmnichannelSettingRequest( - parent='parent_value', - ) - -def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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.create_omnichannel_setting in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc - request = {} - client.create_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_omnichannel_setting(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_create_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( - 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.create_omnichannel_setting in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_omnichannel_setting] = mock_rpc - - request = {} - await client.create_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_omnichannel_setting(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_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.CreateOmnichannelSettingRequest): - client = OmnichannelSettingsServiceAsyncClient( - 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.create_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) - response = await client.create_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.CreateOmnichannelSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -@pytest.mark.asyncio -async def test_create_omnichannel_setting_async_from_dict(): - await test_create_omnichannel_setting_async(request_type=dict) - -def test_create_omnichannel_setting_field_headers(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.CreateOmnichannelSettingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - call.return_value = omnichannelsettings.OmnichannelSetting() - client.create_omnichannel_setting(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_create_omnichannel_setting_field_headers_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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 = omnichannelsettings.CreateOmnichannelSettingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) - await client.create_omnichannel_setting(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_create_omnichannel_setting_flattened(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_omnichannel_setting( - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') - assert arg == mock_val - - -def test_create_omnichannel_setting_flattened_error(): - client = OmnichannelSettingsServiceClient( - 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.create_omnichannel_setting( - omnichannelsettings.CreateOmnichannelSettingRequest(), - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_omnichannel_setting_flattened_async(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_omnichannel_setting( - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_omnichannel_setting_flattened_error_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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.create_omnichannel_setting( - omnichannelsettings.CreateOmnichannelSettingRequest(), - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.UpdateOmnichannelSettingRequest, - dict, -]) -def test_update_omnichannel_setting(request_type, transport: str = 'grpc'): - client = OmnichannelSettingsServiceClient( - 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.update_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - ) - response = client.update_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.UpdateOmnichannelSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.UpdateOmnichannelSettingRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_omnichannel_setting(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == omnichannelsettings.UpdateOmnichannelSettingRequest( - ) - -def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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.update_omnichannel_setting in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc - request = {} - client.update_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_omnichannel_setting(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_update_omnichannel_setting_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 = OmnichannelSettingsServiceAsyncClient( - 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.update_omnichannel_setting in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_omnichannel_setting] = mock_rpc - - request = {} - await client.update_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_omnichannel_setting(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_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): - client = OmnichannelSettingsServiceAsyncClient( - 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.update_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) - response = await client.update_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.UpdateOmnichannelSettingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -@pytest.mark.asyncio -async def test_update_omnichannel_setting_async_from_dict(): - await test_update_omnichannel_setting_async(request_type=dict) - -def test_update_omnichannel_setting_field_headers(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.UpdateOmnichannelSettingRequest() - - request.omnichannel_setting.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - call.return_value = omnichannelsettings.OmnichannelSetting() - client.update_omnichannel_setting(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', - 'omnichannel_setting.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_omnichannel_setting_field_headers_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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 = omnichannelsettings.UpdateOmnichannelSettingRequest() - - request.omnichannel_setting.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) - await client.update_omnichannel_setting(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', - 'omnichannel_setting.name=name_value', - ) in kw['metadata'] - - -def test_update_omnichannel_setting_flattened(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_omnichannel_setting( - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_omnichannel_setting_flattened_error(): - client = OmnichannelSettingsServiceClient( - 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.update_omnichannel_setting( - omnichannelsettings.UpdateOmnichannelSettingRequest(), - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_omnichannel_setting_flattened_async(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.OmnichannelSetting() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_omnichannel_setting( - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_omnichannel_setting_flattened_error_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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.update_omnichannel_setting( - omnichannelsettings.UpdateOmnichannelSettingRequest(), - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.RequestInventoryVerificationRequest, - dict, -]) -def test_request_inventory_verification(request_type, transport: str = 'grpc'): - client = OmnichannelSettingsServiceClient( - 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.request_inventory_verification), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.RequestInventoryVerificationResponse( - ) - response = client.request_inventory_verification(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.RequestInventoryVerificationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) - - -def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.RequestInventoryVerificationRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.request_inventory_verification(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == omnichannelsettings.RequestInventoryVerificationRequest( - name='name_value', - ) - -def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( - 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.request_inventory_verification in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc - request = {} - client.request_inventory_verification(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.request_inventory_verification(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_request_inventory_verification_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 = OmnichannelSettingsServiceAsyncClient( - 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.request_inventory_verification 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.request_inventory_verification] = mock_rpc - - request = {} - await client.request_inventory_verification(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.request_inventory_verification(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_request_inventory_verification_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.RequestInventoryVerificationRequest): - client = OmnichannelSettingsServiceAsyncClient( - 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.request_inventory_verification), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( - )) - response = await client.request_inventory_verification(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = omnichannelsettings.RequestInventoryVerificationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) - - -@pytest.mark.asyncio -async def test_request_inventory_verification_async_from_dict(): - await test_request_inventory_verification_async(request_type=dict) - -def test_request_inventory_verification_field_headers(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.RequestInventoryVerificationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - client.request_inventory_verification(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_request_inventory_verification_field_headers_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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 = omnichannelsettings.RequestInventoryVerificationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) - await client.request_inventory_verification(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_request_inventory_verification_flattened(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.request_inventory_verification( - 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_request_inventory_verification_flattened_error(): - client = OmnichannelSettingsServiceClient( - 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.request_inventory_verification( - omnichannelsettings.RequestInventoryVerificationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_request_inventory_verification_flattened_async(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.request_inventory_verification( - 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_request_inventory_verification_flattened_error_async(): - client = OmnichannelSettingsServiceAsyncClient( - 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.request_inventory_verification( - omnichannelsettings.RequestInventoryVerificationRequest(), - name='name_value', - ) - - -def test_get_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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.get_omnichannel_setting in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc - - request = {} - client.get_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_omnichannel_setting(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_get_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.GetOmnichannelSettingRequest): - transport_class = transports.OmnichannelSettingsServiceRestTransport - - 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()).get_omnichannel_setting._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_omnichannel_setting._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 = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = omnichannelsettings.OmnichannelSetting() - # 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 = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_omnichannel_setting_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_omnichannel_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_omnichannel_setting_rest_flattened(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.OmnichannelSetting() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(**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/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) - - -def test_get_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_omnichannel_setting( - omnichannelsettings.GetOmnichannelSettingRequest(), - name='name_value', - ) - - -def test_list_omnichannel_settings_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 = OmnichannelSettingsServiceClient( - 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_omnichannel_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_omnichannel_settings] = mock_rpc - - request = {} - client.list_omnichannel_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_omnichannel_settings(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_omnichannel_settings_rest_required_fields(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): - transport_class = transports.OmnichannelSettingsServiceRestTransport - - 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_omnichannel_settings._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_omnichannel_settings._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 = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - # 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_omnichannel_settings_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_omnichannel_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_omnichannel_settings_rest_flattened(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.ListOmnichannelSettingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(**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/accounts/v1beta/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) - - -def test_list_omnichannel_settings_rest_flattened_error(transport: str = 'rest'): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings( - omnichannelsettings.ListOmnichannelSettingsRequest(), - parent='parent_value', - ) - - -def test_list_omnichannel_settings_rest_pager(transport: str = 'rest'): - client = OmnichannelSettingsServiceClient( - 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 = ( - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='abc', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[], - next_page_token='def', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - ], - next_page_token='ghi', - ), - omnichannelsettings.ListOmnichannelSettingsResponse( - omnichannel_settings=[ - omnichannelsettings.OmnichannelSetting(), - omnichannelsettings.OmnichannelSetting(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(omnichannelsettings.ListOmnichannelSettingsResponse.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'} - - pager = client.list_omnichannel_settings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, omnichannelsettings.OmnichannelSetting) - for i in results) - - pages = list(client.list_omnichannel_settings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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.create_omnichannel_setting in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc - - request = {} - client.create_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_omnichannel_setting(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_create_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): - transport_class = transports.OmnichannelSettingsServiceRestTransport - - 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()).create_omnichannel_setting._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_omnichannel_setting._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 = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = omnichannelsettings.OmnichannelSetting() - # 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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_omnichannel_setting_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_omnichannel_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "omnichannelSetting", ))) - - -def test_create_omnichannel_setting_rest_flattened(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.OmnichannelSetting() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(**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/accounts/v1beta/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) - - -def test_create_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): - client = OmnichannelSettingsServiceClient( - 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.create_omnichannel_setting( - omnichannelsettings.CreateOmnichannelSettingRequest(), - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - ) - - -def test_update_omnichannel_setting_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 = OmnichannelSettingsServiceClient( - 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.update_omnichannel_setting in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc - - request = {} - client.update_omnichannel_setting(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_omnichannel_setting(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_update_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): - transport_class = transports.OmnichannelSettingsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = omnichannelsettings.OmnichannelSetting() - # 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': "patch", - '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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_omnichannel_setting_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_omnichannel_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("omnichannelSetting", "updateMask", ))) - - -def test_update_omnichannel_setting_rest_flattened(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.OmnichannelSetting() - - # get arguments that satisfy an http rule for this method - sample_request = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(**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/accounts/v1beta/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) - - -def test_update_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): - client = OmnichannelSettingsServiceClient( - 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.update_omnichannel_setting( - omnichannelsettings.UpdateOmnichannelSettingRequest(), - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_request_inventory_verification_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 = OmnichannelSettingsServiceClient( - 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.request_inventory_verification in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc - - request = {} - client.request_inventory_verification(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.request_inventory_verification(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_request_inventory_verification_rest_required_fields(request_type=omnichannelsettings.RequestInventoryVerificationRequest): - transport_class = transports.OmnichannelSettingsServiceRestTransport - - 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()).request_inventory_verification._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()).request_inventory_verification._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 = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = omnichannelsettings.RequestInventoryVerificationResponse() - # 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 = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_request_inventory_verification_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.request_inventory_verification._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_request_inventory_verification_rest_flattened(): - client = OmnichannelSettingsServiceClient( - 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 = omnichannelsettings.RequestInventoryVerificationResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(**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/accounts/v1beta/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification" % client.transport._host, args[1]) - - -def test_request_inventory_verification_rest_flattened_error(transport: str = 'rest'): - client = OmnichannelSettingsServiceClient( - 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.request_inventory_verification( - omnichannelsettings.RequestInventoryVerificationRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OmnichannelSettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OmnichannelSettingsServiceClient( - 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 = OmnichannelSettingsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OmnichannelSettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = OmnichannelSettingsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.OmnichannelSettingsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.OmnichannelSettingsServiceGrpcTransport, - transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, - transports.OmnichannelSettingsServiceRestTransport, -]) -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 = OmnichannelSettingsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = OmnichannelSettingsServiceClient( - 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_get_omnichannel_setting_empty_call_grpc(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - call.return_value = omnichannelsettings.OmnichannelSetting() - client.get_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.GetOmnichannelSettingRequest() - - 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_list_omnichannel_settings_empty_call_grpc(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - client.list_omnichannel_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() - - 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_create_omnichannel_setting_empty_call_grpc(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - call.return_value = omnichannelsettings.OmnichannelSetting() - client.create_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() - - 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_update_omnichannel_setting_empty_call_grpc(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - call.return_value = omnichannelsettings.OmnichannelSetting() - client.update_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() - - 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_request_inventory_verification_empty_call_grpc(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - client.request_inventory_verification(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.RequestInventoryVerificationRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = OmnichannelSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = OmnichannelSettingsServiceAsyncClient( - 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_get_omnichannel_setting_empty_call_grpc_asyncio(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) - await client.get_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.GetOmnichannelSettingRequest() - - 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_list_omnichannel_settings_empty_call_grpc_asyncio(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', - )) - await client.list_omnichannel_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() - - 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_create_omnichannel_setting_empty_call_grpc_asyncio(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) - await client.create_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() - - 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_update_omnichannel_setting_empty_call_grpc_asyncio(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) - await client.update_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() - - 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_request_inventory_verification_empty_call_grpc_asyncio(): - client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( - )) - await client.request_inventory_verification(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.RequestInventoryVerificationRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = OmnichannelSettingsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.GetOmnichannelSettingRequest): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/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.get_omnichannel_setting(request) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.GetOmnichannelSettingRequest, - dict, -]) -def test_get_omnichannel_setting_rest_call_success(request_type): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/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 = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - ) - - # 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 = omnichannelsettings.OmnichannelSetting.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.get_omnichannel_setting(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_omnichannel_setting_rest_interceptors(null_interceptor): - transport = transports.OmnichannelSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) - client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_get_omnichannel_setting") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.GetOmnichannelSettingRequest.pb(omnichannelsettings.GetOmnichannelSettingRequest()) - 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) - req.return_value.content = return_value - - request = omnichannelsettings.GetOmnichannelSettingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = omnichannelsettings.OmnichannelSetting() - post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata - - client.get_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_omnichannel_settings_rest_bad_request(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_omnichannel_settings(request) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.ListOmnichannelSettingsRequest, - dict, -]) -def test_list_omnichannel_settings_rest_call_success(request_type): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = omnichannelsettings.ListOmnichannelSettingsResponse( - 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 = omnichannelsettings.ListOmnichannelSettingsResponse.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_omnichannel_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOmnichannelSettingsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_omnichannel_settings_rest_interceptors(null_interceptor): - transport = transports.OmnichannelSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) - client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_list_omnichannel_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.ListOmnichannelSettingsRequest.pb(omnichannelsettings.ListOmnichannelSettingsRequest()) - 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 = omnichannelsettings.ListOmnichannelSettingsResponse.to_json(omnichannelsettings.ListOmnichannelSettingsResponse()) - req.return_value.content = return_value - - request = omnichannelsettings.ListOmnichannelSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - post_with_metadata.return_value = omnichannelsettings.ListOmnichannelSettingsResponse(), metadata - - client.list_omnichannel_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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.create_omnichannel_setting(request) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.CreateOmnichannelSettingRequest, - dict, -]) -def test_create_omnichannel_setting_rest_call_success(request_type): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["omnichannel_setting"] = {'name': 'name_value', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 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 = omnichannelsettings.CreateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] - - 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["omnichannel_setting"].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["omnichannel_setting"][field])): - del request_init["omnichannel_setting"][field][i][subfield] - else: - del request_init["omnichannel_setting"][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 = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - ) - - # 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 = omnichannelsettings.OmnichannelSetting.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.create_omnichannel_setting(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_omnichannel_setting_rest_interceptors(null_interceptor): - transport = transports.OmnichannelSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) - client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_create_omnichannel_setting") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.CreateOmnichannelSettingRequest.pb(omnichannelsettings.CreateOmnichannelSettingRequest()) - 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) - req.return_value.content = return_value - - request = omnichannelsettings.CreateOmnichannelSettingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = omnichannelsettings.OmnichannelSetting() - post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata - - client.create_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/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.update_omnichannel_setting(request) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.UpdateOmnichannelSettingRequest, - dict, -]) -def test_update_omnichannel_setting_rest_call_success(request_type): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} - request_init["omnichannel_setting"] = {'name': 'accounts/sample1/omnichannelSettings/sample2', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 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 = omnichannelsettings.UpdateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] - - 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["omnichannel_setting"].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["omnichannel_setting"][field])): - del request_init["omnichannel_setting"][field][i][subfield] - else: - del request_init["omnichannel_setting"][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 = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - ) - - # 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 = omnichannelsettings.OmnichannelSetting.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.update_omnichannel_setting(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_omnichannel_setting_rest_interceptors(null_interceptor): - transport = transports.OmnichannelSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) - client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_update_omnichannel_setting") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.UpdateOmnichannelSettingRequest.pb(omnichannelsettings.UpdateOmnichannelSettingRequest()) - 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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) - req.return_value.content = return_value - - request = omnichannelsettings.UpdateOmnichannelSettingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = omnichannelsettings.OmnichannelSetting() - post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata - - client.update_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_request_inventory_verification_rest_bad_request(request_type=omnichannelsettings.RequestInventoryVerificationRequest): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/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.request_inventory_verification(request) - - -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.RequestInventoryVerificationRequest, - dict, -]) -def test_request_inventory_verification_rest_call_success(request_type): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/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 = omnichannelsettings.RequestInventoryVerificationResponse( - ) - - # 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 = omnichannelsettings.RequestInventoryVerificationResponse.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.request_inventory_verification(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_request_inventory_verification_rest_interceptors(null_interceptor): - transport = transports.OmnichannelSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) - client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_request_inventory_verification") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.RequestInventoryVerificationRequest.pb(omnichannelsettings.RequestInventoryVerificationRequest()) - 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 = omnichannelsettings.RequestInventoryVerificationResponse.to_json(omnichannelsettings.RequestInventoryVerificationResponse()) - req.return_value.content = return_value - - request = omnichannelsettings.RequestInventoryVerificationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - post_with_metadata.return_value = omnichannelsettings.RequestInventoryVerificationResponse(), metadata - - client.request_inventory_verification(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = OmnichannelSettingsServiceClient( - 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_get_omnichannel_setting_empty_call_rest(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - client.get_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.GetOmnichannelSettingRequest() - - 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_list_omnichannel_settings_empty_call_rest(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: - client.list_omnichannel_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.ListOmnichannelSettingsRequest() - - 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_create_omnichannel_setting_empty_call_rest(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - client.create_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.CreateOmnichannelSettingRequest() - - 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_update_omnichannel_setting_empty_call_rest(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - client.update_omnichannel_setting(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.UpdateOmnichannelSettingRequest() - - 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_request_inventory_verification_empty_call_rest(): - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: - client.request_inventory_verification(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = omnichannelsettings.RequestInventoryVerificationRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.OmnichannelSettingsServiceGrpcTransport, - ) - -def test_omnichannel_settings_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.OmnichannelSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_omnichannel_settings_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.OmnichannelSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_omnichannel_setting', - 'list_omnichannel_settings', - 'create_omnichannel_setting', - 'update_omnichannel_setting', - 'request_inventory_verification', - ) - 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_omnichannel_settings_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_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OmnichannelSettingsServiceTransport( - 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_omnichannel_settings_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_accounts_v1beta.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OmnichannelSettingsServiceTransport() - adc.assert_called_once() - - -def test_omnichannel_settings_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) - OmnichannelSettingsServiceClient() - 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.OmnichannelSettingsServiceGrpcTransport, - transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, - ], -) -def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, - transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, - transports.OmnichannelSettingsServiceRestTransport, - ], -) -def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, grpc_helpers), - (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) -def test_omnichannel_settings_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_omnichannel_settings_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.OmnichannelSettingsServiceRestTransport ( - 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_omnichannel_settings_service_host_no_port(transport_name): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings_service_host_with_port(transport_name): - client = OmnichannelSettingsServiceClient( - 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_omnichannel_settings_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = OmnichannelSettingsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = OmnichannelSettingsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_omnichannel_setting._session - session2 = client2.transport.get_omnichannel_setting._session - assert session1 != session2 - session1 = client1.transport.list_omnichannel_settings._session - session2 = client2.transport.list_omnichannel_settings._session - assert session1 != session2 - session1 = client1.transport.create_omnichannel_setting._session - session2 = client2.transport.create_omnichannel_setting._session - assert session1 != session2 - session1 = client1.transport.update_omnichannel_setting._session - session2 = client2.transport.update_omnichannel_setting._session - assert session1 != session2 - session1 = client1.transport.request_inventory_verification._session - session2 = client2.transport.request_inventory_verification._session - assert session1 != session2 -def test_omnichannel_settings_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OmnichannelSettingsServiceGrpcTransport( - 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_omnichannel_settings_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OmnichannelSettingsServiceGrpcAsyncIOTransport( - 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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) -def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) -def test_omnichannel_settings_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = OmnichannelSettingsServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = OmnichannelSettingsServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.parse_account_path(path) - assert expected == actual - -def test_omnichannel_setting_path(): - account = "whelk" - omnichannel_setting = "octopus" - expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) - actual = OmnichannelSettingsServiceClient.omnichannel_setting_path(account, omnichannel_setting) - assert expected == actual - - -def test_parse_omnichannel_setting_path(): - expected = { - "account": "oyster", - "omnichannel_setting": "nudibranch", - } - path = OmnichannelSettingsServiceClient.omnichannel_setting_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.parse_omnichannel_setting_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OmnichannelSettingsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = OmnichannelSettingsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = OmnichannelSettingsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = OmnichannelSettingsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OmnichannelSettingsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = OmnichannelSettingsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = OmnichannelSettingsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = OmnichannelSettingsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = OmnichannelSettingsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = OmnichannelSettingsServiceClient.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.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: - client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient( - 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 = OmnichannelSettingsServiceAsyncClient( - 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 = OmnichannelSettingsServiceClient( - 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 = OmnichannelSettingsServiceClient( - 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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py deleted file mode 100644 index e58a8e9072ca..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_online_return_policy_service.py +++ /dev/null @@ -1,5362 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import OnlineReturnPolicyServiceClient -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import pagers -from google.shopping.merchant_accounts_v1beta.services.online_return_policy_service import transports -from google.shopping.merchant_accounts_v1beta.types import online_return_policy -from google.shopping.merchant_accounts_v1beta.types import online_return_policy as gsma_online_return_policy -from google.shopping.type.types import types -from google.type import date_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 OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(None) is None - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, False) is None - assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert OnlineReturnPolicyServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert OnlineReturnPolicyServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert OnlineReturnPolicyServiceClient._get_universe_domain(None, None) == OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient(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 = OnlineReturnPolicyServiceClient(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", [ - (OnlineReturnPolicyServiceClient, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, "rest"), -]) -def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -def test_online_return_policy_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", [ - (OnlineReturnPolicyServiceClient, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, "rest"), -]) -def test_online_return_policy_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_online_return_policy_service_client_get_transport_class(): - transport = OnlineReturnPolicyServiceClient.get_transport_class() - available_transports = [ - transports.OnlineReturnPolicyServiceGrpcTransport, - transports.OnlineReturnPolicyServiceRestTransport, - ] - assert transport in available_transports - - transport = OnlineReturnPolicyServiceClient.get_transport_class("grpc") - assert transport == transports.OnlineReturnPolicyServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) -def test_online_return_policy_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(OnlineReturnPolicyServiceClient, '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(OnlineReturnPolicyServiceClient, '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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "true"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "false"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "true"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_online_return_policy_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", [ - OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceAsyncClient)) -def test_online_return_policy_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", [ - OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) -def test_online_return_policy_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = OnlineReturnPolicyServiceClient._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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -def test_online_return_policy_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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", None), -]) -def test_online_return_policy_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_online_return_policy_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = OnlineReturnPolicyServiceClient( - 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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_online_return_policy_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", [ - online_return_policy.GetOnlineReturnPolicyRequest, - dict, -]) -def test_get_online_return_policy(request_type, transport: str = 'grpc'): - client = OnlineReturnPolicyServiceClient( - 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.get_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - ) - response = client.get_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = online_return_policy.GetOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.GetOnlineReturnPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_online_return_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == online_return_policy.GetOnlineReturnPolicyRequest( - name='name_value', - ) - -def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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.get_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc - request = {} - client.get_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_online_return_policy(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_get_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( - 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.get_online_return_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_online_return_policy] = mock_rpc - - request = {} - await client.get_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_online_return_policy(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_get_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.GetOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceAsyncClient( - 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.get_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) - response = await client.get_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = online_return_policy.GetOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -@pytest.mark.asyncio -async def test_get_online_return_policy_async_from_dict(): - await test_get_online_return_policy_async(request_type=dict) - -def test_get_online_return_policy_field_headers(): - client = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.GetOnlineReturnPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - call.return_value = online_return_policy.OnlineReturnPolicy() - client.get_online_return_policy(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_get_online_return_policy_field_headers_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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 = online_return_policy.GetOnlineReturnPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) - await client.get_online_return_policy(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_get_online_return_policy_flattened(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = online_return_policy.OnlineReturnPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_online_return_policy( - 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_get_online_return_policy_flattened_error(): - client = OnlineReturnPolicyServiceClient( - 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.get_online_return_policy( - online_return_policy.GetOnlineReturnPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_online_return_policy_flattened_async(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = online_return_policy.OnlineReturnPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_online_return_policy( - 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_get_online_return_policy_flattened_error_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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.get_online_return_policy( - online_return_policy.GetOnlineReturnPolicyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - online_return_policy.ListOnlineReturnPoliciesRequest, - dict, -]) -def test_list_online_return_policies(request_type, transport: str = 'grpc'): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_online_return_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = online_return_policy.ListOnlineReturnPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.ListOnlineReturnPoliciesRequest( - 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_online_return_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_online_return_policies(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == online_return_policy.ListOnlineReturnPoliciesRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( - 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_online_return_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_online_return_policies] = mock_rpc - request = {} - client.list_online_return_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_online_return_policies(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_online_return_policies_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 = OnlineReturnPolicyServiceAsyncClient( - 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_online_return_policies 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_online_return_policies] = mock_rpc - - request = {} - await client.list_online_return_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_online_return_policies(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_online_return_policies_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.ListOnlineReturnPoliciesRequest): - client = OnlineReturnPolicyServiceAsyncClient( - 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_online_return_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_online_return_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = online_return_policy.ListOnlineReturnPoliciesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOnlineReturnPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_online_return_policies_async_from_dict(): - await test_list_online_return_policies_async(request_type=dict) - -def test_list_online_return_policies_field_headers(): - client = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.ListOnlineReturnPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - client.list_online_return_policies(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_online_return_policies_field_headers_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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 = online_return_policy.ListOnlineReturnPoliciesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) - await client.list_online_return_policies(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_online_return_policies_flattened(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_online_return_policies( - 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_online_return_policies_flattened_error(): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policies( - online_return_policy.ListOnlineReturnPoliciesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_online_return_policies_flattened_async(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_online_return_policies( - 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_online_return_policies_flattened_error_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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_online_return_policies( - online_return_policy.ListOnlineReturnPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_online_return_policies_pager(transport_name: str = "grpc"): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='abc', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[], - next_page_token='def', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='ghi', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_online_return_policies(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, online_return_policy.OnlineReturnPolicy) - for i in results) -def test_list_online_return_policies_pages(transport_name: str = "grpc"): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='abc', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[], - next_page_token='def', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='ghi', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - ), - RuntimeError, - ) - pages = list(client.list_online_return_policies(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_online_return_policies_async_pager(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='abc', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[], - next_page_token='def', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='ghi', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_online_return_policies(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, online_return_policy.OnlineReturnPolicy) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_online_return_policies_async_pages(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='abc', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[], - next_page_token='def', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='ghi', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - ), - 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_online_return_policies(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", [ - gsma_online_return_policy.CreateOnlineReturnPolicyRequest, - dict, -]) -def test_create_online_return_policy(request_type, transport: str = 'grpc'): - client = OnlineReturnPolicyServiceClient( - 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.create_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - ) - response = client.create_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_online_return_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gsma_online_return_policy.CreateOnlineReturnPolicyRequest( - parent='parent_value', - ) - -def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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.create_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc - request = {} - client.create_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_online_return_policy(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_create_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( - 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.create_online_return_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_online_return_policy] = mock_rpc - - request = {} - await client.create_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_online_return_policy(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_create_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceAsyncClient( - 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.create_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) - response = await client.create_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -@pytest.mark.asyncio -async def test_create_online_return_policy_async_from_dict(): - await test_create_online_return_policy_async(request_type=dict) - -def test_create_online_return_policy_field_headers(): - client = OnlineReturnPolicyServiceClient( - 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - client.create_online_return_policy(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_create_online_return_policy_field_headers_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) - await client.create_online_return_policy(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_create_online_return_policy_flattened(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_online_return_policy( - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].online_return_policy - mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') - assert arg == mock_val - - -def test_create_online_return_policy_flattened_error(): - client = OnlineReturnPolicyServiceClient( - 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.create_online_return_policy( - gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_online_return_policy_flattened_async(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_online_return_policy( - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].online_return_policy - mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_online_return_policy_flattened_error_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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.create_online_return_policy( - gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, - dict, -]) -def test_update_online_return_policy(request_type, transport: str = 'grpc'): - client = OnlineReturnPolicyServiceClient( - 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.update_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - ) - response = client.update_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -def test_update_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_online_return_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gsma_online_return_policy.UpdateOnlineReturnPolicyRequest( - ) - -def test_update_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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.update_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_online_return_policy] = mock_rpc - request = {} - client.update_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_online_return_policy(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_update_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( - 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.update_online_return_policy in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_online_return_policy] = mock_rpc - - request = {} - await client.update_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_online_return_policy(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_update_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceAsyncClient( - 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.update_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) - response = await client.update_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -@pytest.mark.asyncio -async def test_update_online_return_policy_async_from_dict(): - await test_update_online_return_policy_async(request_type=dict) - -def test_update_online_return_policy_field_headers(): - client = OnlineReturnPolicyServiceClient( - 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - - request.online_return_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - client.update_online_return_policy(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', - 'online_return_policy.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_online_return_policy_field_headers_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - - request.online_return_policy.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) - await client.update_online_return_policy(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', - 'online_return_policy.name=name_value', - ) in kw['metadata'] - - -def test_update_online_return_policy_flattened(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_online_return_policy( - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].online_return_policy - mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_online_return_policy_flattened_error(): - client = OnlineReturnPolicyServiceClient( - 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.update_online_return_policy( - gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(), - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_online_return_policy_flattened_async(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_online_return_policy( - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].online_return_policy - mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_online_return_policy_flattened_error_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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.update_online_return_policy( - gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(), - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - online_return_policy.DeleteOnlineReturnPolicyRequest, - dict, -]) -def test_delete_online_return_policy(request_type, transport: str = 'grpc'): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = online_return_policy.DeleteOnlineReturnPolicyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.DeleteOnlineReturnPolicyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_online_return_policy(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == online_return_policy.DeleteOnlineReturnPolicyRequest( - name='name_value', - ) - -def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_online_return_policy] = mock_rpc - request = {} - client.delete_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_online_return_policy(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_online_return_policy_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 = OnlineReturnPolicyServiceAsyncClient( - 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_online_return_policy 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_online_return_policy] = mock_rpc - - request = {} - await client.delete_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_online_return_policy(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_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceAsyncClient( - 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_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = online_return_policy.DeleteOnlineReturnPolicyRequest() - 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_online_return_policy_async_from_dict(): - await test_delete_online_return_policy_async(request_type=dict) - -def test_delete_online_return_policy_field_headers(): - client = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: - call.return_value = None - client.delete_online_return_policy(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_online_return_policy_field_headers_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_online_return_policy(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_online_return_policy_flattened(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__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_online_return_policy( - 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_online_return_policy_flattened_error(): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policy( - online_return_policy.DeleteOnlineReturnPolicyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_online_return_policy_flattened_async(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__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_online_return_policy( - 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_online_return_policy_flattened_error_async(): - client = OnlineReturnPolicyServiceAsyncClient( - 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_online_return_policy( - online_return_policy.DeleteOnlineReturnPolicyRequest(), - name='name_value', - ) - - -def test_get_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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.get_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc - - request = {} - client.get_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_online_return_policy(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_get_online_return_policy_rest_required_fields(request_type=online_return_policy.GetOnlineReturnPolicyRequest): - transport_class = transports.OnlineReturnPolicyServiceRestTransport - - 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()).get_online_return_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_online_return_policy._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 = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = online_return_policy.OnlineReturnPolicy() - # 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 = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_online_return_policy_rest_flattened(): - client = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.OnlineReturnPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(**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/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) - - -def test_get_online_return_policy_rest_flattened_error(transport: str = 'rest'): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_online_return_policy( - online_return_policy.GetOnlineReturnPolicyRequest(), - name='name_value', - ) - - -def test_list_online_return_policies_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 = OnlineReturnPolicyServiceClient( - 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_online_return_policies in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_online_return_policies] = mock_rpc - - request = {} - client.list_online_return_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_online_return_policies(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_online_return_policies_rest_required_fields(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): - transport_class = transports.OnlineReturnPolicyServiceRestTransport - - 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_online_return_policies._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_online_return_policies._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 = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - # 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_online_return_policies_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_online_return_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_online_return_policies_rest_flattened(): - client = OnlineReturnPolicyServiceClient( - 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 = online_return_policy.ListOnlineReturnPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(**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/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) - - -def test_list_online_return_policies_rest_flattened_error(transport: str = 'rest'): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policies( - online_return_policy.ListOnlineReturnPoliciesRequest(), - parent='parent_value', - ) - - -def test_list_online_return_policies_rest_pager(transport: str = 'rest'): - client = OnlineReturnPolicyServiceClient( - 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 = ( - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='abc', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[], - next_page_token='def', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - ], - next_page_token='ghi', - ), - online_return_policy.ListOnlineReturnPoliciesResponse( - online_return_policies=[ - online_return_policy.OnlineReturnPolicy(), - online_return_policy.OnlineReturnPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(online_return_policy.ListOnlineReturnPoliciesResponse.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'} - - pager = client.list_online_return_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, online_return_policy.OnlineReturnPolicy) - for i in results) - - pages = list(client.list_online_return_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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.create_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc - - request = {} - client.create_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_online_return_policy(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_create_online_return_policy_rest_required_fields(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - transport_class = transports.OnlineReturnPolicyServiceRestTransport - - 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()).create_online_return_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_online_return_policy._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 = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gsma_online_return_policy.OnlineReturnPolicy() - # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "onlineReturnPolicy", ))) - - -def test_create_online_return_policy_rest_flattened(): - client = OnlineReturnPolicyServiceClient( - 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 = gsma_online_return_policy.OnlineReturnPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(**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/accounts/v1beta/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) - - -def test_create_online_return_policy_rest_flattened_error(transport: str = 'rest'): - client = OnlineReturnPolicyServiceClient( - 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.create_online_return_policy( - gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - ) - - -def test_update_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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.update_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_online_return_policy] = mock_rpc - - request = {} - client.update_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_online_return_policy(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_update_online_return_policy_rest_required_fields(request_type=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): - transport_class = transports.OnlineReturnPolicyServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_online_return_policy._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_online_return_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gsma_online_return_policy.OnlineReturnPolicy() - # 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': "patch", - '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 = gsma_online_return_policy.OnlineReturnPolicy.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.update_online_return_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("onlineReturnPolicy", ))) - - -def test_update_online_return_policy_rest_flattened(): - client = OnlineReturnPolicyServiceClient( - 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 = gsma_online_return_policy.OnlineReturnPolicy() - - # get arguments that satisfy an http rule for this method - sample_request = {'online_return_policy': {'name': 'accounts/sample1/onlineReturnPolicies/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_online_return_policy.OnlineReturnPolicy.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.update_online_return_policy(**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/accounts/v1beta/{online_return_policy.name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) - - -def test_update_online_return_policy_rest_flattened_error(transport: str = 'rest'): - client = OnlineReturnPolicyServiceClient( - 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.update_online_return_policy( - gsma_online_return_policy.UpdateOnlineReturnPolicyRequest(), - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_online_return_policy_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 = OnlineReturnPolicyServiceClient( - 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_online_return_policy in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_online_return_policy] = mock_rpc - - request = {} - client.delete_online_return_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_online_return_policy(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_online_return_policy_rest_required_fields(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): - transport_class = transports.OnlineReturnPolicyServiceRestTransport - - 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_online_return_policy._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_online_return_policy._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 = OnlineReturnPolicyServiceClient( - 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_online_return_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_online_return_policy_rest_flattened(): - client = OnlineReturnPolicyServiceClient( - 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/onlineReturnPolicies/sample2'} - - # 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_online_return_policy(**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/accounts/v1beta/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) - - -def test_delete_online_return_policy_rest_flattened_error(transport: str = 'rest'): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policy( - online_return_policy.DeleteOnlineReturnPolicyRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OnlineReturnPolicyServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = OnlineReturnPolicyServiceClient( - 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 = OnlineReturnPolicyServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = OnlineReturnPolicyServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = OnlineReturnPolicyServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.OnlineReturnPolicyServiceGrpcTransport, - transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, - transports.OnlineReturnPolicyServiceRestTransport, -]) -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 = OnlineReturnPolicyServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = OnlineReturnPolicyServiceClient( - 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_get_online_return_policy_empty_call_grpc(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - call.return_value = online_return_policy.OnlineReturnPolicy() - client.get_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.GetOnlineReturnPolicyRequest() - - 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_list_online_return_policies_empty_call_grpc(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - client.list_online_return_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() - - 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_create_online_return_policy_empty_call_grpc(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - client.create_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - - 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_update_online_return_policy_empty_call_grpc(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - client.update_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - - 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_online_return_policy_empty_call_grpc(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: - call.return_value = None - client.delete_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = OnlineReturnPolicyServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = OnlineReturnPolicyServiceAsyncClient( - 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_get_online_return_policy_empty_call_grpc_asyncio(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) - await client.get_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.GetOnlineReturnPolicyRequest() - - 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_list_online_return_policies_empty_call_grpc_asyncio(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', - )) - await client.list_online_return_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() - - 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_create_online_return_policy_empty_call_grpc_asyncio(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) - await client.create_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - - 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_update_online_return_policy_empty_call_grpc_asyncio(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) - await client.update_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - - 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_online_return_policy_empty_call_grpc_asyncio(): - client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = OnlineReturnPolicyServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_online_return_policy_rest_bad_request(request_type=online_return_policy.GetOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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.get_online_return_policy(request) - - -@pytest.mark.parametrize("request_type", [ - online_return_policy.GetOnlineReturnPolicyRequest, - dict, -]) -def test_get_online_return_policy_rest_call_success(request_type): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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 = online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - ) - - # 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 = online_return_policy.OnlineReturnPolicy.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.get_online_return_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_online_return_policy_rest_interceptors(null_interceptor): - transport = transports.OnlineReturnPolicyServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) - client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_get_online_return_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = online_return_policy.GetOnlineReturnPolicyRequest.pb(online_return_policy.GetOnlineReturnPolicyRequest()) - 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 = online_return_policy.OnlineReturnPolicy.to_json(online_return_policy.OnlineReturnPolicy()) - req.return_value.content = return_value - - request = online_return_policy.GetOnlineReturnPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = online_return_policy.OnlineReturnPolicy() - post_with_metadata.return_value = online_return_policy.OnlineReturnPolicy(), metadata - - client.get_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_online_return_policies_rest_bad_request(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_online_return_policies(request) - - -@pytest.mark.parametrize("request_type", [ - online_return_policy.ListOnlineReturnPoliciesRequest, - dict, -]) -def test_list_online_return_policies_rest_call_success(request_type): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = online_return_policy.ListOnlineReturnPoliciesResponse( - 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 = online_return_policy.ListOnlineReturnPoliciesResponse.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_online_return_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_online_return_policies_rest_interceptors(null_interceptor): - transport = transports.OnlineReturnPolicyServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) - client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_list_online_return_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = online_return_policy.ListOnlineReturnPoliciesRequest.pb(online_return_policy.ListOnlineReturnPoliciesRequest()) - 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 = online_return_policy.ListOnlineReturnPoliciesResponse.to_json(online_return_policy.ListOnlineReturnPoliciesResponse()) - req.return_value.content = return_value - - request = online_return_policy.ListOnlineReturnPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - post_with_metadata.return_value = online_return_policy.ListOnlineReturnPoliciesResponse(), metadata - - client.list_online_return_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_online_return_policy_rest_bad_request(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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.create_online_return_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gsma_online_return_policy.CreateOnlineReturnPolicyRequest, - dict, -]) -def test_create_online_return_policy_rest_call_success(request_type): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["online_return_policy"] = {'name': 'name_value', 'return_policy_id': 'return_policy_id_value', 'label': 'label_value', 'countries': ['countries_value1', 'countries_value2'], 'policy': {'type_': 1, 'days': 433}, 'seasonal_overrides': [{'return_days': 1200, 'return_until_date': {'year': 433, 'month': 550, 'day': 318}, 'label': 'label_value', 'start_date': {}, 'end_date': {}}], 'restocking_fee': {'fixed_fee': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'micro_percent': 1386}, 'return_methods': [1], 'item_conditions': [1], 'return_shipping_fee': {'type_': 1, 'fixed_fee': {}}, 'return_policy_uri': 'return_policy_uri_value', 'accept_defective_only': True, 'process_refund_days': 2034, 'accept_exchange': True, 'return_label_source': 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.meta.fields["online_return_policy"] - - 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["online_return_policy"].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["online_return_policy"][field])): - del request_init["online_return_policy"][field][i][subfield] - else: - del request_init["online_return_policy"][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 = gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - ) - - # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.create_online_return_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_online_return_policy_rest_interceptors(null_interceptor): - transport = transports.OnlineReturnPolicyServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) - client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_create_online_return_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb(gsma_online_return_policy.CreateOnlineReturnPolicyRequest()) - 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 = gsma_online_return_policy.OnlineReturnPolicy.to_json(gsma_online_return_policy.OnlineReturnPolicy()) - req.return_value.content = return_value - - request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gsma_online_return_policy.OnlineReturnPolicy() - post_with_metadata.return_value = gsma_online_return_policy.OnlineReturnPolicy(), metadata - - client.create_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_online_return_policy_rest_bad_request(request_type=gsma_online_return_policy.UpdateOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'online_return_policy': {'name': 'accounts/sample1/onlineReturnPolicies/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.update_online_return_policy(request) - - -@pytest.mark.parametrize("request_type", [ - gsma_online_return_policy.UpdateOnlineReturnPolicyRequest, - dict, -]) -def test_update_online_return_policy_rest_call_success(request_type): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'online_return_policy': {'name': 'accounts/sample1/onlineReturnPolicies/sample2'}} - request_init["online_return_policy"] = {'name': 'accounts/sample1/onlineReturnPolicies/sample2', 'return_policy_id': 'return_policy_id_value', 'label': 'label_value', 'countries': ['countries_value1', 'countries_value2'], 'policy': {'type_': 1, 'days': 433}, 'seasonal_overrides': [{'return_days': 1200, 'return_until_date': {'year': 433, 'month': 550, 'day': 318}, 'label': 'label_value', 'start_date': {}, 'end_date': {}}], 'restocking_fee': {'fixed_fee': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'micro_percent': 1386}, 'return_methods': [1], 'item_conditions': [1], 'return_shipping_fee': {'type_': 1, 'fixed_fee': {}}, 'return_policy_uri': 'return_policy_uri_value', 'accept_defective_only': True, 'process_refund_days': 2034, 'accept_exchange': True, 'return_label_source': 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 = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.meta.fields["online_return_policy"] - - 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["online_return_policy"].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["online_return_policy"][field])): - del request_init["online_return_policy"][field][i][subfield] - else: - del request_init["online_return_policy"][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 = gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - ) - - # 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 = gsma_online_return_policy.OnlineReturnPolicy.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.update_online_return_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' - assert response.accept_defective_only is True - assert response.process_refund_days == 2034 - assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_online_return_policy_rest_interceptors(null_interceptor): - transport = transports.OnlineReturnPolicyServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) - client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_update_online_return_policy") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_update_online_return_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_update_online_return_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest.pb(gsma_online_return_policy.UpdateOnlineReturnPolicyRequest()) - 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 = gsma_online_return_policy.OnlineReturnPolicy.to_json(gsma_online_return_policy.OnlineReturnPolicy()) - req.return_value.content = return_value - - request = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gsma_online_return_policy.OnlineReturnPolicy() - post_with_metadata.return_value = gsma_online_return_policy.OnlineReturnPolicy(), metadata - - client.update_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_online_return_policy_rest_bad_request(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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.delete_online_return_policy(request) - - -@pytest.mark.parametrize("request_type", [ - online_return_policy.DeleteOnlineReturnPolicyRequest, - dict, -]) -def test_delete_online_return_policy_rest_call_success(request_type): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/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 = 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_online_return_policy(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_online_return_policy_rest_interceptors(null_interceptor): - transport = transports.OnlineReturnPolicyServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) - client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "pre_delete_online_return_policy") as pre: - pre.assert_not_called() - pb_message = online_return_policy.DeleteOnlineReturnPolicyRequest.pb(online_return_policy.DeleteOnlineReturnPolicyRequest()) - 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 = online_return_policy.DeleteOnlineReturnPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = OnlineReturnPolicyServiceClient( - 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_get_online_return_policy_empty_call_rest(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - client.get_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.GetOnlineReturnPolicyRequest() - - 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_list_online_return_policies_empty_call_rest(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: - client.list_online_return_policies(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.ListOnlineReturnPoliciesRequest() - - 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_create_online_return_policy_empty_call_rest(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - client.create_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - - 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_update_online_return_policy_empty_call_rest(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_online_return_policy), - '__call__') as call: - client.update_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_online_return_policy.UpdateOnlineReturnPolicyRequest() - - 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_online_return_policy_empty_call_rest(): - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: - client.delete_online_return_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = online_return_policy.DeleteOnlineReturnPolicyRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.OnlineReturnPolicyServiceGrpcTransport, - ) - -def test_online_return_policy_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.OnlineReturnPolicyServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_online_return_policy_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.OnlineReturnPolicyServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_online_return_policy', - 'list_online_return_policies', - 'create_online_return_policy', - 'update_online_return_policy', - 'delete_online_return_policy', - ) - 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_online_return_policy_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_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OnlineReturnPolicyServiceTransport( - 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_online_return_policy_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_accounts_v1beta.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.OnlineReturnPolicyServiceTransport() - adc.assert_called_once() - - -def test_online_return_policy_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) - OnlineReturnPolicyServiceClient() - 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.OnlineReturnPolicyServiceGrpcTransport, - transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, - ], -) -def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, - transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, - transports.OnlineReturnPolicyServiceRestTransport, - ], -) -def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, grpc_helpers), - (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) -def test_online_return_policy_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_online_return_policy_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.OnlineReturnPolicyServiceRestTransport ( - 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_online_return_policy_service_host_no_port(transport_name): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policy_service_host_with_port(transport_name): - client = OnlineReturnPolicyServiceClient( - 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_online_return_policy_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = OnlineReturnPolicyServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = OnlineReturnPolicyServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_online_return_policy._session - session2 = client2.transport.get_online_return_policy._session - assert session1 != session2 - session1 = client1.transport.list_online_return_policies._session - session2 = client2.transport.list_online_return_policies._session - assert session1 != session2 - session1 = client1.transport.create_online_return_policy._session - session2 = client2.transport.create_online_return_policy._session - assert session1 != session2 - session1 = client1.transport.update_online_return_policy._session - session2 = client2.transport.update_online_return_policy._session - assert session1 != session2 - session1 = client1.transport.delete_online_return_policy._session - session2 = client2.transport.delete_online_return_policy._session - assert session1 != session2 -def test_online_return_policy_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OnlineReturnPolicyServiceGrpcTransport( - 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_online_return_policy_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport( - 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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) -def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) -def test_online_return_policy_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_online_return_policy_path(): - account = "squid" - return_policy = "clam" - expected = "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) - actual = OnlineReturnPolicyServiceClient.online_return_policy_path(account, return_policy) - assert expected == actual - - -def test_parse_online_return_policy_path(): - expected = { - "account": "whelk", - "return_policy": "octopus", - } - path = OnlineReturnPolicyServiceClient.online_return_policy_path(**expected) - - # Check that the path construction is reversible. - actual = OnlineReturnPolicyServiceClient.parse_online_return_policy_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OnlineReturnPolicyServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = OnlineReturnPolicyServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = OnlineReturnPolicyServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = OnlineReturnPolicyServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = OnlineReturnPolicyServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = OnlineReturnPolicyServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = OnlineReturnPolicyServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = OnlineReturnPolicyServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = OnlineReturnPolicyServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = OnlineReturnPolicyServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = OnlineReturnPolicyServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = OnlineReturnPolicyServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = OnlineReturnPolicyServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = OnlineReturnPolicyServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = OnlineReturnPolicyServiceClient.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.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: - client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = OnlineReturnPolicyServiceClient.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 = OnlineReturnPolicyServiceClient( - 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 = OnlineReturnPolicyServiceAsyncClient( - 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 = OnlineReturnPolicyServiceClient( - 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 = OnlineReturnPolicyServiceClient( - 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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py deleted file mode 100644 index b30cc1dc4bae..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_programs_service.py +++ /dev/null @@ -1,4435 +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.shopping.merchant_accounts_v1beta.services.programs_service import ProgramsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.programs_service import ProgramsServiceClient -from google.shopping.merchant_accounts_v1beta.services.programs_service import pagers -from google.shopping.merchant_accounts_v1beta.services.programs_service import transports -from google.shopping.merchant_accounts_v1beta.types import programs -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 ProgramsServiceClient._get_default_mtls_endpoint(None) is None - assert ProgramsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ProgramsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ProgramsServiceClient._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 ProgramsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProgramsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ProgramsServiceClient._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 ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, False) is None - assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ProgramsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProgramsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ProgramsServiceClient._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 ProgramsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ProgramsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ProgramsServiceClient._get_universe_domain(None, None) == ProgramsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ProgramsServiceClient._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 = ProgramsServiceClient(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 = ProgramsServiceClient(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", [ - (ProgramsServiceClient, "grpc"), - (ProgramsServiceAsyncClient, "grpc_asyncio"), - (ProgramsServiceClient, "rest"), -]) -def test_programs_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.ProgramsServiceGrpcTransport, "grpc"), - (transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProgramsServiceRestTransport, "rest"), -]) -def test_programs_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", [ - (ProgramsServiceClient, "grpc"), - (ProgramsServiceAsyncClient, "grpc_asyncio"), - (ProgramsServiceClient, "rest"), -]) -def test_programs_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_programs_service_client_get_transport_class(): - transport = ProgramsServiceClient.get_transport_class() - available_transports = [ - transports.ProgramsServiceGrpcTransport, - transports.ProgramsServiceRestTransport, - ] - assert transport in available_transports - - transport = ProgramsServiceClient.get_transport_class("grpc") - assert transport == transports.ProgramsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), -]) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) -def test_programs_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(ProgramsServiceClient, '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(ProgramsServiceClient, '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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "true"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "false"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "true"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_programs_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", [ - ProgramsServiceClient, ProgramsServiceAsyncClient -]) -@mock.patch.object(ProgramsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceAsyncClient)) -def test_programs_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", [ - ProgramsServiceClient, ProgramsServiceAsyncClient -]) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) -def test_programs_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ProgramsServiceClient._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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), -]) -def test_programs_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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", None), -]) -def test_programs_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_programs_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.programs_service.transports.ProgramsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProgramsServiceClient( - 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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_programs_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", [ - programs.GetProgramRequest, - dict, -]) -def test_get_program(request_type, transport: str = 'grpc'): - client = ProgramsServiceClient( - 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.get_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - ) - response = client.get_program(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = programs.GetProgramRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -def test_get_program_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 = ProgramsServiceClient( - 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 = programs.GetProgramRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_program(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == programs.GetProgramRequest( - name='name_value', - ) - -def test_get_program_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 = ProgramsServiceClient( - 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.get_program in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_program] = mock_rpc - request = {} - client.get_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_program(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_get_program_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 = ProgramsServiceAsyncClient( - 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.get_program in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_program] = mock_rpc - - request = {} - await client.get_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_program(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_get_program_async(transport: str = 'grpc_asyncio', request_type=programs.GetProgramRequest): - client = ProgramsServiceAsyncClient( - 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.get_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) - response = await client.get_program(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = programs.GetProgramRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -@pytest.mark.asyncio -async def test_get_program_async_from_dict(): - await test_get_program_async(request_type=dict) - -def test_get_program_field_headers(): - client = ProgramsServiceClient( - 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 = programs.GetProgramRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - call.return_value = programs.Program() - client.get_program(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_get_program_field_headers_async(): - client = ProgramsServiceAsyncClient( - 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 = programs.GetProgramRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) - await client.get_program(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_get_program_flattened(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_program( - 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_get_program_flattened_error(): - client = ProgramsServiceClient( - 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.get_program( - programs.GetProgramRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_program_flattened_async(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_program( - 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_get_program_flattened_error_async(): - client = ProgramsServiceAsyncClient( - 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.get_program( - programs.GetProgramRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - programs.ListProgramsRequest, - dict, -]) -def test_list_programs(request_type, transport: str = 'grpc'): - client = ProgramsServiceClient( - 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_programs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.ListProgramsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_programs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = programs.ListProgramsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProgramsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_programs_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 = ProgramsServiceClient( - 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 = programs.ListProgramsRequest( - 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_programs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_programs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == programs.ListProgramsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_programs_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 = ProgramsServiceClient( - 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_programs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_programs] = mock_rpc - request = {} - client.list_programs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_programs(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_programs_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 = ProgramsServiceAsyncClient( - 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_programs 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_programs] = mock_rpc - - request = {} - await client.list_programs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_programs(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_programs_async(transport: str = 'grpc_asyncio', request_type=programs.ListProgramsRequest): - client = ProgramsServiceAsyncClient( - 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_programs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_programs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = programs.ListProgramsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProgramsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_programs_async_from_dict(): - await test_list_programs_async(request_type=dict) - -def test_list_programs_field_headers(): - client = ProgramsServiceClient( - 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 = programs.ListProgramsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - call.return_value = programs.ListProgramsResponse() - client.list_programs(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_programs_field_headers_async(): - client = ProgramsServiceAsyncClient( - 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 = programs.ListProgramsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) - await client.list_programs(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_programs_flattened(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.ListProgramsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_programs( - 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_programs_flattened_error(): - client = ProgramsServiceClient( - 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_programs( - programs.ListProgramsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_programs_flattened_async(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.ListProgramsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_programs( - 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_programs_flattened_error_async(): - client = ProgramsServiceAsyncClient( - 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_programs( - programs.ListProgramsRequest(), - parent='parent_value', - ) - - -def test_list_programs_pager(transport_name: str = "grpc"): - client = ProgramsServiceClient( - 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_programs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - programs.Program(), - ], - next_page_token='abc', - ), - programs.ListProgramsResponse( - programs=[], - next_page_token='def', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - ], - next_page_token='ghi', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_programs(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, programs.Program) - for i in results) -def test_list_programs_pages(transport_name: str = "grpc"): - client = ProgramsServiceClient( - 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_programs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - programs.Program(), - ], - next_page_token='abc', - ), - programs.ListProgramsResponse( - programs=[], - next_page_token='def', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - ], - next_page_token='ghi', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - ], - ), - RuntimeError, - ) - pages = list(client.list_programs(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_programs_async_pager(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - programs.Program(), - ], - next_page_token='abc', - ), - programs.ListProgramsResponse( - programs=[], - next_page_token='def', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - ], - next_page_token='ghi', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_programs(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, programs.Program) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_programs_async_pages(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - programs.Program(), - ], - next_page_token='abc', - ), - programs.ListProgramsResponse( - programs=[], - next_page_token='def', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - ], - next_page_token='ghi', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - ], - ), - 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_programs(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", [ - programs.EnableProgramRequest, - dict, -]) -def test_enable_program(request_type, transport: str = 'grpc'): - client = ProgramsServiceClient( - 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.enable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - ) - response = client.enable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = programs.EnableProgramRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -def test_enable_program_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 = ProgramsServiceClient( - 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 = programs.EnableProgramRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.enable_program(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == programs.EnableProgramRequest( - name='name_value', - ) - -def test_enable_program_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 = ProgramsServiceClient( - 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.enable_program in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc - request = {} - client.enable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.enable_program(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_enable_program_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 = ProgramsServiceAsyncClient( - 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.enable_program 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.enable_program] = mock_rpc - - request = {} - await client.enable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.enable_program(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_enable_program_async(transport: str = 'grpc_asyncio', request_type=programs.EnableProgramRequest): - client = ProgramsServiceAsyncClient( - 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.enable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) - response = await client.enable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = programs.EnableProgramRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -@pytest.mark.asyncio -async def test_enable_program_async_from_dict(): - await test_enable_program_async(request_type=dict) - -def test_enable_program_field_headers(): - client = ProgramsServiceClient( - 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 = programs.EnableProgramRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - call.return_value = programs.Program() - client.enable_program(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_enable_program_field_headers_async(): - client = ProgramsServiceAsyncClient( - 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 = programs.EnableProgramRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) - await client.enable_program(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_enable_program_flattened(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.enable_program( - 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_enable_program_flattened_error(): - client = ProgramsServiceClient( - 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.enable_program( - programs.EnableProgramRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_enable_program_flattened_async(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.enable_program( - 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_enable_program_flattened_error_async(): - client = ProgramsServiceAsyncClient( - 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.enable_program( - programs.EnableProgramRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - programs.DisableProgramRequest, - dict, -]) -def test_disable_program(request_type, transport: str = 'grpc'): - client = ProgramsServiceClient( - 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.disable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - ) - response = client.disable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = programs.DisableProgramRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -def test_disable_program_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 = ProgramsServiceClient( - 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 = programs.DisableProgramRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.disable_program(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == programs.DisableProgramRequest( - name='name_value', - ) - -def test_disable_program_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 = ProgramsServiceClient( - 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.disable_program in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc - request = {} - client.disable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.disable_program(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_disable_program_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 = ProgramsServiceAsyncClient( - 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.disable_program 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.disable_program] = mock_rpc - - request = {} - await client.disable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.disable_program(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_disable_program_async(transport: str = 'grpc_asyncio', request_type=programs.DisableProgramRequest): - client = ProgramsServiceAsyncClient( - 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.disable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) - response = await client.disable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = programs.DisableProgramRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -@pytest.mark.asyncio -async def test_disable_program_async_from_dict(): - await test_disable_program_async(request_type=dict) - -def test_disable_program_field_headers(): - client = ProgramsServiceClient( - 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 = programs.DisableProgramRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - call.return_value = programs.Program() - client.disable_program(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_disable_program_field_headers_async(): - client = ProgramsServiceAsyncClient( - 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 = programs.DisableProgramRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) - await client.disable_program(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_disable_program_flattened(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.disable_program( - 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_disable_program_flattened_error(): - client = ProgramsServiceClient( - 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.disable_program( - programs.DisableProgramRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_disable_program_flattened_async(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = programs.Program() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.disable_program( - 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_disable_program_flattened_error_async(): - client = ProgramsServiceAsyncClient( - 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.disable_program( - programs.DisableProgramRequest(), - name='name_value', - ) - - -def test_get_program_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 = ProgramsServiceClient( - 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.get_program in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_program] = mock_rpc - - request = {} - client.get_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_program(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_get_program_rest_required_fields(request_type=programs.GetProgramRequest): - transport_class = transports.ProgramsServiceRestTransport - - 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()).get_program._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_program._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 = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = programs.Program() - # 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 = programs.Program.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.get_program(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_program_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_program._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_program_rest_flattened(): - client = ProgramsServiceClient( - 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 = programs.Program() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = programs.Program.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.get_program(**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/accounts/v1beta/{name=accounts/*/programs/*}" % client.transport._host, args[1]) - - -def test_get_program_rest_flattened_error(transport: str = 'rest'): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_program( - programs.GetProgramRequest(), - name='name_value', - ) - - -def test_list_programs_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 = ProgramsServiceClient( - 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_programs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_programs] = mock_rpc - - request = {} - client.list_programs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_programs(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_programs_rest_required_fields(request_type=programs.ListProgramsRequest): - transport_class = transports.ProgramsServiceRestTransport - - 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_programs._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_programs._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 = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = programs.ListProgramsResponse() - # 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 = programs.ListProgramsResponse.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_programs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_programs_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_programs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_programs_rest_flattened(): - client = ProgramsServiceClient( - 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 = programs.ListProgramsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = programs.ListProgramsResponse.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_programs(**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/accounts/v1beta/{parent=accounts/*}/programs" % client.transport._host, args[1]) - - -def test_list_programs_rest_flattened_error(transport: str = 'rest'): - client = ProgramsServiceClient( - 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_programs( - programs.ListProgramsRequest(), - parent='parent_value', - ) - - -def test_list_programs_rest_pager(transport: str = 'rest'): - client = ProgramsServiceClient( - 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 = ( - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - programs.Program(), - ], - next_page_token='abc', - ), - programs.ListProgramsResponse( - programs=[], - next_page_token='def', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - ], - next_page_token='ghi', - ), - programs.ListProgramsResponse( - programs=[ - programs.Program(), - programs.Program(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(programs.ListProgramsResponse.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'} - - pager = client.list_programs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, programs.Program) - for i in results) - - pages = list(client.list_programs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_enable_program_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 = ProgramsServiceClient( - 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.enable_program in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc - - request = {} - client.enable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.enable_program(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_enable_program_rest_required_fields(request_type=programs.EnableProgramRequest): - transport_class = transports.ProgramsServiceRestTransport - - 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()).enable_program._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()).enable_program._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 = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = programs.Program() - # 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 = programs.Program.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.enable_program(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_enable_program_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.enable_program._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_enable_program_rest_flattened(): - client = ProgramsServiceClient( - 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 = programs.Program() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = programs.Program.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.enable_program(**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/accounts/v1beta/{name=accounts/*/programs/*}:enable" % client.transport._host, args[1]) - - -def test_enable_program_rest_flattened_error(transport: str = 'rest'): - client = ProgramsServiceClient( - 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.enable_program( - programs.EnableProgramRequest(), - name='name_value', - ) - - -def test_disable_program_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 = ProgramsServiceClient( - 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.disable_program in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc - - request = {} - client.disable_program(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.disable_program(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_disable_program_rest_required_fields(request_type=programs.DisableProgramRequest): - transport_class = transports.ProgramsServiceRestTransport - - 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()).disable_program._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()).disable_program._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 = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = programs.Program() - # 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 = programs.Program.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.disable_program(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_disable_program_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.disable_program._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_disable_program_rest_flattened(): - client = ProgramsServiceClient( - 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 = programs.Program() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = programs.Program.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.disable_program(**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/accounts/v1beta/{name=accounts/*/programs/*}:disable" % client.transport._host, args[1]) - - -def test_disable_program_rest_flattened_error(transport: str = 'rest'): - client = ProgramsServiceClient( - 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.disable_program( - programs.DisableProgramRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProgramsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProgramsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProgramsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProgramsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProgramsServiceClient( - 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 = ProgramsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProgramsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProgramsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProgramsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProgramsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProgramsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProgramsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProgramsServiceGrpcTransport, - transports.ProgramsServiceGrpcAsyncIOTransport, - transports.ProgramsServiceRestTransport, -]) -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 = ProgramsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ProgramsServiceClient( - 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_get_program_empty_call_grpc(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - call.return_value = programs.Program() - client.get_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.GetProgramRequest() - - 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_list_programs_empty_call_grpc(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - call.return_value = programs.ListProgramsResponse() - client.list_programs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.ListProgramsRequest() - - 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_enable_program_empty_call_grpc(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - call.return_value = programs.Program() - client.enable_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.EnableProgramRequest() - - 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_disable_program_empty_call_grpc(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - call.return_value = programs.Program() - client.disable_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.DisableProgramRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ProgramsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ProgramsServiceAsyncClient( - 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_get_program_empty_call_grpc_asyncio(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) - await client.get_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.GetProgramRequest() - - 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_list_programs_empty_call_grpc_asyncio(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( - next_page_token='next_page_token_value', - )) - await client.list_programs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.ListProgramsRequest() - - 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_enable_program_empty_call_grpc_asyncio(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) - await client.enable_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.EnableProgramRequest() - - 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_disable_program_empty_call_grpc_asyncio(): - client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) - await client.disable_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.DisableProgramRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ProgramsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_program_rest_bad_request(request_type=programs.GetProgramRequest): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/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.get_program(request) - - -@pytest.mark.parametrize("request_type", [ - programs.GetProgramRequest, - dict, -]) -def test_get_program_rest_call_success(request_type): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_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 = programs.Program.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.get_program(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_program_rest_interceptors(null_interceptor): - transport = transports.ProgramsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) - client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_get_program") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_get_program_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_get_program") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = programs.GetProgramRequest.pb(programs.GetProgramRequest()) - 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 = programs.Program.to_json(programs.Program()) - req.return_value.content = return_value - - request = programs.GetProgramRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = programs.Program() - post_with_metadata.return_value = programs.Program(), metadata - - client.get_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_programs_rest_bad_request(request_type=programs.ListProgramsRequest): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_programs(request) - - -@pytest.mark.parametrize("request_type", [ - programs.ListProgramsRequest, - dict, -]) -def test_list_programs_rest_call_success(request_type): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = programs.ListProgramsResponse( - 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 = programs.ListProgramsResponse.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_programs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProgramsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_programs_rest_interceptors(null_interceptor): - transport = transports.ProgramsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) - client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_list_programs") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_list_programs_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_list_programs") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = programs.ListProgramsRequest.pb(programs.ListProgramsRequest()) - 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 = programs.ListProgramsResponse.to_json(programs.ListProgramsResponse()) - req.return_value.content = return_value - - request = programs.ListProgramsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = programs.ListProgramsResponse() - post_with_metadata.return_value = programs.ListProgramsResponse(), metadata - - client.list_programs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_enable_program_rest_bad_request(request_type=programs.EnableProgramRequest): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/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.enable_program(request) - - -@pytest.mark.parametrize("request_type", [ - programs.EnableProgramRequest, - dict, -]) -def test_enable_program_rest_call_success(request_type): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_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 = programs.Program.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.enable_program(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_program_rest_interceptors(null_interceptor): - transport = transports.ProgramsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) - client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_enable_program") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_enable_program_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_enable_program") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = programs.EnableProgramRequest.pb(programs.EnableProgramRequest()) - 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 = programs.Program.to_json(programs.Program()) - req.return_value.content = return_value - - request = programs.EnableProgramRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = programs.Program() - post_with_metadata.return_value = programs.Program(), metadata - - client.enable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_disable_program_rest_bad_request(request_type=programs.DisableProgramRequest): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/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.disable_program(request) - - -@pytest.mark.parametrize("request_type", [ - programs.DisableProgramRequest, - dict, -]) -def test_disable_program_rest_call_success(request_type): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/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 = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_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 = programs.Program.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.disable_program(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' - assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_program_rest_interceptors(null_interceptor): - transport = transports.ProgramsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) - client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_disable_program") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_disable_program_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_disable_program") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = programs.DisableProgramRequest.pb(programs.DisableProgramRequest()) - 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 = programs.Program.to_json(programs.Program()) - req.return_value.content = return_value - - request = programs.DisableProgramRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = programs.Program() - post_with_metadata.return_value = programs.Program(), metadata - - client.disable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = ProgramsServiceClient( - 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_get_program_empty_call_rest(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - client.get_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.GetProgramRequest() - - 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_list_programs_empty_call_rest(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: - client.list_programs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.ListProgramsRequest() - - 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_enable_program_empty_call_rest(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: - client.enable_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.EnableProgramRequest() - - 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_disable_program_empty_call_rest(): - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: - client.disable_program(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = programs.DisableProgramRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProgramsServiceGrpcTransport, - ) - -def test_programs_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProgramsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_programs_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.programs_service.transports.ProgramsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProgramsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_program', - 'list_programs', - 'enable_program', - 'disable_program', - ) - 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_programs_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_accounts_v1beta.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProgramsServiceTransport( - 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_programs_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_accounts_v1beta.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProgramsServiceTransport() - adc.assert_called_once() - - -def test_programs_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) - ProgramsServiceClient() - 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.ProgramsServiceGrpcTransport, - transports.ProgramsServiceGrpcAsyncIOTransport, - ], -) -def test_programs_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.ProgramsServiceGrpcTransport, - transports.ProgramsServiceGrpcAsyncIOTransport, - transports.ProgramsServiceRestTransport, - ], -) -def test_programs_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.ProgramsServiceGrpcTransport, grpc_helpers), - (transports.ProgramsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) -def test_programs_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_programs_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.ProgramsServiceRestTransport ( - 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_programs_service_host_no_port(transport_name): - client = ProgramsServiceClient( - 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_programs_service_host_with_port(transport_name): - client = ProgramsServiceClient( - 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_programs_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ProgramsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ProgramsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_program._session - session2 = client2.transport.get_program._session - assert session1 != session2 - session1 = client1.transport.list_programs._session - session2 = client2.transport.list_programs._session - assert session1 != session2 - session1 = client1.transport.enable_program._session - session2 = client2.transport.enable_program._session - assert session1 != session2 - session1 = client1.transport.disable_program._session - session2 = client2.transport.disable_program._session - assert session1 != session2 -def test_programs_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProgramsServiceGrpcTransport( - 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_programs_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProgramsServiceGrpcAsyncIOTransport( - 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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) -def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) -def test_programs_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_program_path(): - account = "squid" - program = "clam" - expected = "accounts/{account}/programs/{program}".format(account=account, program=program, ) - actual = ProgramsServiceClient.program_path(account, program) - assert expected == actual - - -def test_parse_program_path(): - expected = { - "account": "whelk", - "program": "octopus", - } - path = ProgramsServiceClient.program_path(**expected) - - # Check that the path construction is reversible. - actual = ProgramsServiceClient.parse_program_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProgramsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = ProgramsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProgramsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProgramsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = ProgramsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProgramsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProgramsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = ProgramsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProgramsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ProgramsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = ProgramsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProgramsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProgramsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = ProgramsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProgramsServiceClient.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.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: - client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ProgramsServiceClient.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 = ProgramsServiceClient( - 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 = ProgramsServiceAsyncClient( - 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 = ProgramsServiceClient( - 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 = ProgramsServiceClient( - 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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py deleted file mode 100644 index 1d304a338ce6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_regions_service.py +++ /dev/null @@ -1,5216 +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 field_mask_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.regions_service import RegionsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.regions_service import RegionsServiceClient -from google.shopping.merchant_accounts_v1beta.services.regions_service import pagers -from google.shopping.merchant_accounts_v1beta.services.regions_service import transports -from google.shopping.merchant_accounts_v1beta.types import regions -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 RegionsServiceClient._get_default_mtls_endpoint(None) is None - assert RegionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RegionsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - RegionsServiceClient._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 RegionsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RegionsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - RegionsServiceClient._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 RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, False) is None - assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = RegionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert RegionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - RegionsServiceClient._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 RegionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RegionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RegionsServiceClient._get_universe_domain(None, None) == RegionsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - RegionsServiceClient._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 = RegionsServiceClient(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 = RegionsServiceClient(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", [ - (RegionsServiceClient, "grpc"), - (RegionsServiceAsyncClient, "grpc_asyncio"), - (RegionsServiceClient, "rest"), -]) -def test_regions_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.RegionsServiceGrpcTransport, "grpc"), - (transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RegionsServiceRestTransport, "rest"), -]) -def test_regions_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", [ - (RegionsServiceClient, "grpc"), - (RegionsServiceAsyncClient, "grpc_asyncio"), - (RegionsServiceClient, "rest"), -]) -def test_regions_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_regions_service_client_get_transport_class(): - transport = RegionsServiceClient.get_transport_class() - available_transports = [ - transports.RegionsServiceGrpcTransport, - transports.RegionsServiceRestTransport, - ] - assert transport in available_transports - - transport = RegionsServiceClient.get_transport_class("grpc") - assert transport == transports.RegionsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), -]) -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) -def test_regions_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(RegionsServiceClient, '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(RegionsServiceClient, '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", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "true"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "false"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "true"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_regions_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", [ - RegionsServiceClient, RegionsServiceAsyncClient -]) -@mock.patch.object(RegionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceAsyncClient)) -def test_regions_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", [ - RegionsServiceClient, RegionsServiceAsyncClient -]) -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) -def test_regions_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = RegionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = RegionsServiceClient._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", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), -]) -def test_regions_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", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", None), -]) -def test_regions_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_regions_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.regions_service.transports.RegionsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RegionsServiceClient( - 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", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_regions_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", [ - regions.GetRegionRequest, - dict, -]) -def test_get_region(request_type, transport: str = 'grpc'): - client = RegionsServiceClient( - 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.get_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region( - name='name_value', - display_name='display_name_value', - ) - response = client.get_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regions.GetRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_get_region_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 = RegionsServiceClient( - 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 = regions.GetRegionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_region(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regions.GetRegionRequest( - name='name_value', - ) - -def test_get_region_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 = RegionsServiceClient( - 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.get_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_region] = mock_rpc - request = {} - client.get_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_region(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_get_region_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 = RegionsServiceAsyncClient( - 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.get_region in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_region] = mock_rpc - - request = {} - await client.get_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_region(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_get_region_async(transport: str = 'grpc_asyncio', request_type=regions.GetRegionRequest): - client = RegionsServiceAsyncClient( - 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.get_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) - response = await client.get_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regions.GetRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_get_region_async_from_dict(): - await test_get_region_async(request_type=dict) - -def test_get_region_field_headers(): - client = RegionsServiceClient( - 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 = regions.GetRegionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - call.return_value = regions.Region() - client.get_region(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_get_region_field_headers_async(): - client = RegionsServiceAsyncClient( - 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 = regions.GetRegionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) - await client.get_region(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_get_region_flattened(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_region( - 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_get_region_flattened_error(): - client = RegionsServiceClient( - 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.get_region( - regions.GetRegionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_region_flattened_async(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_region( - 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_get_region_flattened_error_async(): - client = RegionsServiceAsyncClient( - 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.get_region( - regions.GetRegionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - regions.CreateRegionRequest, - dict, -]) -def test_create_region(request_type, transport: str = 'grpc'): - client = RegionsServiceClient( - 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.create_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region( - name='name_value', - display_name='display_name_value', - ) - response = client.create_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regions.CreateRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_create_region_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 = RegionsServiceClient( - 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 = regions.CreateRegionRequest( - parent='parent_value', - region_id='region_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_region(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regions.CreateRegionRequest( - parent='parent_value', - region_id='region_id_value', - ) - -def test_create_region_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 = RegionsServiceClient( - 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.create_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_region] = mock_rpc - request = {} - client.create_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_region(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_create_region_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 = RegionsServiceAsyncClient( - 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.create_region in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_region] = mock_rpc - - request = {} - await client.create_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_region(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_create_region_async(transport: str = 'grpc_asyncio', request_type=regions.CreateRegionRequest): - client = RegionsServiceAsyncClient( - 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.create_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) - response = await client.create_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regions.CreateRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_create_region_async_from_dict(): - await test_create_region_async(request_type=dict) - -def test_create_region_field_headers(): - client = RegionsServiceClient( - 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 = regions.CreateRegionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - call.return_value = regions.Region() - client.create_region(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_create_region_field_headers_async(): - client = RegionsServiceAsyncClient( - 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 = regions.CreateRegionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) - await client.create_region(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_create_region_flattened(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_region( - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_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 - arg = args[0].region - mock_val = regions.Region(name='name_value') - assert arg == mock_val - arg = args[0].region_id - mock_val = 'region_id_value' - assert arg == mock_val - - -def test_create_region_flattened_error(): - client = RegionsServiceClient( - 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.create_region( - regions.CreateRegionRequest(), - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', - ) - -@pytest.mark.asyncio -async def test_create_region_flattened_async(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_region( - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_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 - arg = args[0].region - mock_val = regions.Region(name='name_value') - assert arg == mock_val - arg = args[0].region_id - mock_val = 'region_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_region_flattened_error_async(): - client = RegionsServiceAsyncClient( - 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.create_region( - regions.CreateRegionRequest(), - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - regions.UpdateRegionRequest, - dict, -]) -def test_update_region(request_type, transport: str = 'grpc'): - client = RegionsServiceClient( - 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.update_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region( - name='name_value', - display_name='display_name_value', - ) - response = client.update_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regions.UpdateRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -def test_update_region_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 = RegionsServiceClient( - 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 = regions.UpdateRegionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_region(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regions.UpdateRegionRequest( - ) - -def test_update_region_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 = RegionsServiceClient( - 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.update_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_region] = mock_rpc - request = {} - client.update_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_region(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_update_region_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 = RegionsServiceAsyncClient( - 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.update_region in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_region] = mock_rpc - - request = {} - await client.update_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_region(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_update_region_async(transport: str = 'grpc_asyncio', request_type=regions.UpdateRegionRequest): - client = RegionsServiceAsyncClient( - 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.update_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) - response = await client.update_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regions.UpdateRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.asyncio -async def test_update_region_async_from_dict(): - await test_update_region_async(request_type=dict) - -def test_update_region_field_headers(): - client = RegionsServiceClient( - 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 = regions.UpdateRegionRequest() - - request.region.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - call.return_value = regions.Region() - client.update_region(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', - 'region.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_region_field_headers_async(): - client = RegionsServiceAsyncClient( - 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 = regions.UpdateRegionRequest() - - request.region.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) - await client.update_region(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', - 'region.name=name_value', - ) in kw['metadata'] - - -def test_update_region_flattened(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_region( - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].region - mock_val = regions.Region(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_region_flattened_error(): - client = RegionsServiceClient( - 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.update_region( - regions.UpdateRegionRequest(), - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_region_flattened_async(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.Region() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_region( - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].region - mock_val = regions.Region(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_region_flattened_error_async(): - client = RegionsServiceAsyncClient( - 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.update_region( - regions.UpdateRegionRequest(), - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - regions.DeleteRegionRequest, - dict, -]) -def test_delete_region(request_type, transport: str = 'grpc'): - client = RegionsServiceClient( - 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_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regions.DeleteRegionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_region_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 = RegionsServiceClient( - 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 = regions.DeleteRegionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_region(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regions.DeleteRegionRequest( - name='name_value', - ) - -def test_delete_region_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 = RegionsServiceClient( - 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_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_region] = mock_rpc - request = {} - client.delete_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_region(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_region_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 = RegionsServiceAsyncClient( - 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_region 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_region] = mock_rpc - - request = {} - await client.delete_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_region(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_region_async(transport: str = 'grpc_asyncio', request_type=regions.DeleteRegionRequest): - client = RegionsServiceAsyncClient( - 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_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_region(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regions.DeleteRegionRequest() - 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_region_async_from_dict(): - await test_delete_region_async(request_type=dict) - -def test_delete_region_field_headers(): - client = RegionsServiceClient( - 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 = regions.DeleteRegionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: - call.return_value = None - client.delete_region(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_region_field_headers_async(): - client = RegionsServiceAsyncClient( - 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 = regions.DeleteRegionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_region(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_region_flattened(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__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_region( - 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_region_flattened_error(): - client = RegionsServiceClient( - 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_region( - regions.DeleteRegionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_region_flattened_async(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__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_region( - 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_region_flattened_error_async(): - client = RegionsServiceAsyncClient( - 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_region( - regions.DeleteRegionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - regions.ListRegionsRequest, - dict, -]) -def test_list_regions(request_type, transport: str = 'grpc'): - client = RegionsServiceClient( - 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_regions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.ListRegionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_regions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = regions.ListRegionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_regions_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 = RegionsServiceClient( - 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 = regions.ListRegionsRequest( - 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_regions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_regions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == regions.ListRegionsRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_regions_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 = RegionsServiceClient( - 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_regions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_regions] = mock_rpc - request = {} - client.list_regions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_regions(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_regions_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 = RegionsServiceAsyncClient( - 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_regions 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_regions] = mock_rpc - - request = {} - await client.list_regions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_regions(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_regions_async(transport: str = 'grpc_asyncio', request_type=regions.ListRegionsRequest): - client = RegionsServiceAsyncClient( - 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_regions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_regions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = regions.ListRegionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_regions_async_from_dict(): - await test_list_regions_async(request_type=dict) - -def test_list_regions_field_headers(): - client = RegionsServiceClient( - 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 = regions.ListRegionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - call.return_value = regions.ListRegionsResponse() - client.list_regions(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_regions_field_headers_async(): - client = RegionsServiceAsyncClient( - 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 = regions.ListRegionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) - await client.list_regions(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_regions_flattened(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.ListRegionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_regions( - 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_regions_flattened_error(): - client = RegionsServiceClient( - 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_regions( - regions.ListRegionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_regions_flattened_async(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = regions.ListRegionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_regions( - 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_regions_flattened_error_async(): - client = RegionsServiceAsyncClient( - 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_regions( - regions.ListRegionsRequest(), - parent='parent_value', - ) - - -def test_list_regions_pager(transport_name: str = "grpc"): - client = RegionsServiceClient( - 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_regions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - regions.Region(), - ], - next_page_token='abc', - ), - regions.ListRegionsResponse( - regions=[], - next_page_token='def', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - ], - next_page_token='ghi', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_regions(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, regions.Region) - for i in results) -def test_list_regions_pages(transport_name: str = "grpc"): - client = RegionsServiceClient( - 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_regions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - regions.Region(), - ], - next_page_token='abc', - ), - regions.ListRegionsResponse( - regions=[], - next_page_token='def', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - ], - next_page_token='ghi', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - ], - ), - RuntimeError, - ) - pages = list(client.list_regions(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_regions_async_pager(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - regions.Region(), - ], - next_page_token='abc', - ), - regions.ListRegionsResponse( - regions=[], - next_page_token='def', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - ], - next_page_token='ghi', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_regions(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, regions.Region) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_regions_async_pages(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - regions.Region(), - ], - next_page_token='abc', - ), - regions.ListRegionsResponse( - regions=[], - next_page_token='def', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - ], - next_page_token='ghi', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - ], - ), - 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_regions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_region_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 = RegionsServiceClient( - 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.get_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_region] = mock_rpc - - request = {} - client.get_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_region(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_get_region_rest_required_fields(request_type=regions.GetRegionRequest): - transport_class = transports.RegionsServiceRestTransport - - 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()).get_region._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_region._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 = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regions.Region() - # 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 = regions.Region.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.get_region(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_region_rest_flattened(): - client = RegionsServiceClient( - 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 = regions.Region() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/regions/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = regions.Region.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.get_region(**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/accounts/v1beta/{name=accounts/*/regions/*}" % client.transport._host, args[1]) - - -def test_get_region_rest_flattened_error(transport: str = 'rest'): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_region( - regions.GetRegionRequest(), - name='name_value', - ) - - -def test_create_region_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 = RegionsServiceClient( - 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.create_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_region] = mock_rpc - - request = {} - client.create_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_region(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_create_region_rest_required_fields(request_type=regions.CreateRegionRequest): - transport_class = transports.RegionsServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["region_id"] = "" - 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 - assert "regionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "regionId" in jsonified_request - assert jsonified_request["regionId"] == request_init["region_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["regionId"] = 'region_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("region_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "regionId" in jsonified_request - assert jsonified_request["regionId"] == 'region_id_value' - - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regions.Region() - # 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 = regions.Region.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.create_region(request) - - expected_params = [ - ( - "regionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(("regionId", )) & set(("parent", "regionId", "region", ))) - - -def test_create_region_rest_flattened(): - client = RegionsServiceClient( - 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 = regions.Region() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_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 = regions.Region.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.create_region(**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/accounts/v1beta/{parent=accounts/*}/regions" % client.transport._host, args[1]) - - -def test_create_region_rest_flattened_error(transport: str = 'rest'): - client = RegionsServiceClient( - 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.create_region( - regions.CreateRegionRequest(), - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', - ) - - -def test_update_region_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 = RegionsServiceClient( - 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.update_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_region] = mock_rpc - - request = {} - client.update_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_region(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_update_region_rest_required_fields(request_type=regions.UpdateRegionRequest): - transport_class = transports.RegionsServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regions.Region() - # 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': "patch", - '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 = regions.Region.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.update_region(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("region", ))) - - -def test_update_region_rest_flattened(): - client = RegionsServiceClient( - 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 = regions.Region() - - # get arguments that satisfy an http rule for this method - sample_request = {'region': {'name': 'accounts/sample1/regions/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = regions.Region.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.update_region(**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/accounts/v1beta/{region.name=accounts/*/regions/*}" % client.transport._host, args[1]) - - -def test_update_region_rest_flattened_error(transport: str = 'rest'): - client = RegionsServiceClient( - 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.update_region( - regions.UpdateRegionRequest(), - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_region_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 = RegionsServiceClient( - 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_region in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_region] = mock_rpc - - request = {} - client.delete_region(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_region(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_region_rest_required_fields(request_type=regions.DeleteRegionRequest): - transport_class = transports.RegionsServiceRestTransport - - 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_region._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_region._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 = RegionsServiceClient( - 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_region(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_region_rest_flattened(): - client = RegionsServiceClient( - 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/regions/sample2'} - - # 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_region(**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/accounts/v1beta/{name=accounts/*/regions/*}" % client.transport._host, args[1]) - - -def test_delete_region_rest_flattened_error(transport: str = 'rest'): - client = RegionsServiceClient( - 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_region( - regions.DeleteRegionRequest(), - name='name_value', - ) - - -def test_list_regions_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 = RegionsServiceClient( - 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_regions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_regions] = mock_rpc - - request = {} - client.list_regions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_regions(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_regions_rest_required_fields(request_type=regions.ListRegionsRequest): - transport_class = transports.RegionsServiceRestTransport - - 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_regions._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_regions._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 = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = regions.ListRegionsResponse() - # 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 = regions.ListRegionsResponse.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_regions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_regions_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_regions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_regions_rest_flattened(): - client = RegionsServiceClient( - 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 = regions.ListRegionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = regions.ListRegionsResponse.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_regions(**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/accounts/v1beta/{parent=accounts/*}/regions" % client.transport._host, args[1]) - - -def test_list_regions_rest_flattened_error(transport: str = 'rest'): - client = RegionsServiceClient( - 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_regions( - regions.ListRegionsRequest(), - parent='parent_value', - ) - - -def test_list_regions_rest_pager(transport: str = 'rest'): - client = RegionsServiceClient( - 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 = ( - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - regions.Region(), - ], - next_page_token='abc', - ), - regions.ListRegionsResponse( - regions=[], - next_page_token='def', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - ], - next_page_token='ghi', - ), - regions.ListRegionsResponse( - regions=[ - regions.Region(), - regions.Region(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(regions.ListRegionsResponse.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'} - - pager = client.list_regions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, regions.Region) - for i in results) - - pages = list(client.list_regions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RegionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RegionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RegionsServiceClient( - 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 = RegionsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RegionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegionsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RegionsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegionsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RegionsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RegionsServiceGrpcTransport, - transports.RegionsServiceGrpcAsyncIOTransport, - transports.RegionsServiceRestTransport, -]) -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 = RegionsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = RegionsServiceClient( - 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_get_region_empty_call_grpc(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - call.return_value = regions.Region() - client.get_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.GetRegionRequest() - - 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_create_region_empty_call_grpc(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - call.return_value = regions.Region() - client.create_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.CreateRegionRequest() - - 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_update_region_empty_call_grpc(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - call.return_value = regions.Region() - client.update_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.UpdateRegionRequest() - - 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_region_empty_call_grpc(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: - call.return_value = None - client.delete_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.DeleteRegionRequest() - - 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_list_regions_empty_call_grpc(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - call.return_value = regions.ListRegionsResponse() - client.list_regions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.ListRegionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = RegionsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = RegionsServiceAsyncClient( - 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_get_region_empty_call_grpc_asyncio(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) - await client.get_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.GetRegionRequest() - - 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_create_region_empty_call_grpc_asyncio(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) - await client.create_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.CreateRegionRequest() - - 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_update_region_empty_call_grpc_asyncio(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) - await client.update_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.UpdateRegionRequest() - - 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_region_empty_call_grpc_asyncio(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.DeleteRegionRequest() - - 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_list_regions_empty_call_grpc_asyncio(): - client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( - next_page_token='next_page_token_value', - )) - await client.list_regions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.ListRegionsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = RegionsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_region_rest_bad_request(request_type=regions.GetRegionRequest): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/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.get_region(request) - - -@pytest.mark.parametrize("request_type", [ - regions.GetRegionRequest, - dict, -]) -def test_get_region_rest_call_success(request_type): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/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 = regions.Region( - name='name_value', - display_name='display_name_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 = regions.Region.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.get_region(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_region_rest_interceptors(null_interceptor): - transport = transports.RegionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) - client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_get_region") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_get_region_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_get_region") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = regions.GetRegionRequest.pb(regions.GetRegionRequest()) - 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 = regions.Region.to_json(regions.Region()) - req.return_value.content = return_value - - request = regions.GetRegionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regions.Region() - post_with_metadata.return_value = regions.Region(), metadata - - client.get_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_region_rest_bad_request(request_type=regions.CreateRegionRequest): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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.create_region(request) - - -@pytest.mark.parametrize("request_type", [ - regions.CreateRegionRequest, - dict, -]) -def test_create_region_rest_call_success(request_type): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["region"] = {'name': 'name_value', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} - # 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 = regions.CreateRegionRequest.meta.fields["region"] - - 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["region"].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["region"][field])): - del request_init["region"][field][i][subfield] - else: - del request_init["region"][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 = regions.Region( - name='name_value', - display_name='display_name_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 = regions.Region.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.create_region(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_region_rest_interceptors(null_interceptor): - transport = transports.RegionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) - client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_create_region") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_create_region_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_create_region") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = regions.CreateRegionRequest.pb(regions.CreateRegionRequest()) - 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 = regions.Region.to_json(regions.Region()) - req.return_value.content = return_value - - request = regions.CreateRegionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regions.Region() - post_with_metadata.return_value = regions.Region(), metadata - - client.create_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_region_rest_bad_request(request_type=regions.UpdateRegionRequest): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'region': {'name': 'accounts/sample1/regions/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.update_region(request) - - -@pytest.mark.parametrize("request_type", [ - regions.UpdateRegionRequest, - dict, -]) -def test_update_region_rest_call_success(request_type): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'region': {'name': 'accounts/sample1/regions/sample2'}} - request_init["region"] = {'name': 'accounts/sample1/regions/sample2', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} - # 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 = regions.UpdateRegionRequest.meta.fields["region"] - - 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["region"].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["region"][field])): - del request_init["region"][field][i][subfield] - else: - del request_init["region"][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 = regions.Region( - name='name_value', - display_name='display_name_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 = regions.Region.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.update_region(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_region_rest_interceptors(null_interceptor): - transport = transports.RegionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) - client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_update_region") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_update_region_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_update_region") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = regions.UpdateRegionRequest.pb(regions.UpdateRegionRequest()) - 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 = regions.Region.to_json(regions.Region()) - req.return_value.content = return_value - - request = regions.UpdateRegionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regions.Region() - post_with_metadata.return_value = regions.Region(), metadata - - client.update_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_region_rest_bad_request(request_type=regions.DeleteRegionRequest): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/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.delete_region(request) - - -@pytest.mark.parametrize("request_type", [ - regions.DeleteRegionRequest, - dict, -]) -def test_delete_region_rest_call_success(request_type): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/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 = 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_region(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_region_rest_interceptors(null_interceptor): - transport = transports.RegionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) - client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "pre_delete_region") as pre: - pre.assert_not_called() - pb_message = regions.DeleteRegionRequest.pb(regions.DeleteRegionRequest()) - 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 = regions.DeleteRegionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_list_regions_rest_bad_request(request_type=regions.ListRegionsRequest): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_regions(request) - - -@pytest.mark.parametrize("request_type", [ - regions.ListRegionsRequest, - dict, -]) -def test_list_regions_rest_call_success(request_type): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = regions.ListRegionsResponse( - 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 = regions.ListRegionsResponse.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_regions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRegionsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_regions_rest_interceptors(null_interceptor): - transport = transports.RegionsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) - client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_list_regions") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_list_regions_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_list_regions") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = regions.ListRegionsRequest.pb(regions.ListRegionsRequest()) - 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 = regions.ListRegionsResponse.to_json(regions.ListRegionsResponse()) - req.return_value.content = return_value - - request = regions.ListRegionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = regions.ListRegionsResponse() - post_with_metadata.return_value = regions.ListRegionsResponse(), metadata - - client.list_regions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = RegionsServiceClient( - 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_get_region_empty_call_rest(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - client.get_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.GetRegionRequest() - - 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_create_region_empty_call_rest(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - client.create_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.CreateRegionRequest() - - 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_update_region_empty_call_rest(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - client.update_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.UpdateRegionRequest() - - 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_region_empty_call_rest(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: - client.delete_region(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.DeleteRegionRequest() - - 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_list_regions_empty_call_rest(): - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: - client.list_regions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = regions.ListRegionsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RegionsServiceGrpcTransport, - ) - -def test_regions_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RegionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_regions_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.regions_service.transports.RegionsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RegionsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_region', - 'create_region', - 'update_region', - 'delete_region', - 'list_regions', - ) - 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_regions_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_accounts_v1beta.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegionsServiceTransport( - 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_regions_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_accounts_v1beta.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegionsServiceTransport() - adc.assert_called_once() - - -def test_regions_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) - RegionsServiceClient() - 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.RegionsServiceGrpcTransport, - transports.RegionsServiceGrpcAsyncIOTransport, - ], -) -def test_regions_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.RegionsServiceGrpcTransport, - transports.RegionsServiceGrpcAsyncIOTransport, - transports.RegionsServiceRestTransport, - ], -) -def test_regions_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.RegionsServiceGrpcTransport, grpc_helpers), - (transports.RegionsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) -def test_regions_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_regions_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.RegionsServiceRestTransport ( - 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_regions_service_host_no_port(transport_name): - client = RegionsServiceClient( - 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_regions_service_host_with_port(transport_name): - client = RegionsServiceClient( - 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_regions_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RegionsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RegionsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_region._session - session2 = client2.transport.get_region._session - assert session1 != session2 - session1 = client1.transport.create_region._session - session2 = client2.transport.create_region._session - assert session1 != session2 - session1 = client1.transport.update_region._session - session2 = client2.transport.update_region._session - assert session1 != session2 - session1 = client1.transport.delete_region._session - session2 = client2.transport.delete_region._session - assert session1 != session2 - session1 = client1.transport.list_regions._session - session2 = client2.transport.list_regions._session - assert session1 != session2 -def test_regions_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegionsServiceGrpcTransport( - 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_regions_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegionsServiceGrpcAsyncIOTransport( - 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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) -def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) -def test_regions_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = RegionsServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = RegionsServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.parse_account_path(path) - assert expected == actual - -def test_region_path(): - account = "whelk" - region = "octopus" - expected = "accounts/{account}/regions/{region}".format(account=account, region=region, ) - actual = RegionsServiceClient.region_path(account, region) - assert expected == actual - - -def test_parse_region_path(): - expected = { - "account": "oyster", - "region": "nudibranch", - } - path = RegionsServiceClient.region_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.parse_region_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RegionsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = RegionsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = RegionsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = RegionsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RegionsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = RegionsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = RegionsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = RegionsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.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 = RegionsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = RegionsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RegionsServiceClient.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.RegionsServiceTransport, '_prep_wrapped_messages') as prep: - client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RegionsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RegionsServiceClient.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 = RegionsServiceClient( - 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 = RegionsServiceAsyncClient( - 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 = RegionsServiceClient( - 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 = RegionsServiceClient( - 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", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py deleted file mode 100644 index f42327173207..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_shipping_settings_service.py +++ /dev/null @@ -1,2733 +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.shopping.merchant_accounts_v1beta.services.shipping_settings_service import ShippingSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service import ShippingSettingsServiceClient -from google.shopping.merchant_accounts_v1beta.services.shipping_settings_service import transports -from google.shopping.merchant_accounts_v1beta.types import shippingsettings -from google.shopping.type.types import types -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 ShippingSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, False) is None - assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ShippingSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ShippingSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ShippingSettingsServiceClient._get_universe_domain(None, None) == ShippingSettingsServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient(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 = ShippingSettingsServiceClient(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", [ - (ShippingSettingsServiceClient, "grpc"), - (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), - (ShippingSettingsServiceClient, "rest"), -]) -def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, "grpc"), - (transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ShippingSettingsServiceRestTransport, "rest"), -]) -def test_shipping_settings_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", [ - (ShippingSettingsServiceClient, "grpc"), - (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), - (ShippingSettingsServiceClient, "rest"), -]) -def test_shipping_settings_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_shipping_settings_service_client_get_transport_class(): - transport = ShippingSettingsServiceClient.get_transport_class() - available_transports = [ - transports.ShippingSettingsServiceGrpcTransport, - transports.ShippingSettingsServiceRestTransport, - ] - assert transport in available_transports - - transport = ShippingSettingsServiceClient.get_transport_class("grpc") - assert transport == transports.ShippingSettingsServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) -def test_shipping_settings_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(ShippingSettingsServiceClient, '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(ShippingSettingsServiceClient, '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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "true"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "false"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "true"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_shipping_settings_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", [ - ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient -]) -@mock.patch.object(ShippingSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceAsyncClient)) -def test_shipping_settings_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", [ - ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient -]) -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) -def test_shipping_settings_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ShippingSettingsServiceClient._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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), -]) -def test_shipping_settings_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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", None), -]) -def test_shipping_settings_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_shipping_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ShippingSettingsServiceClient( - 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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_shipping_settings_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", [ - shippingsettings.GetShippingSettingsRequest, - dict, -]) -def test_get_shipping_settings(request_type, transport: str = 'grpc'): - client = ShippingSettingsServiceClient( - 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.get_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - ) - response = client.get_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = shippingsettings.GetShippingSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - - -def test_get_shipping_settings_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 = ShippingSettingsServiceClient( - 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 = shippingsettings.GetShippingSettingsRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_shipping_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == shippingsettings.GetShippingSettingsRequest( - name='name_value', - ) - -def test_get_shipping_settings_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 = ShippingSettingsServiceClient( - 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.get_shipping_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc - request = {} - client.get_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_shipping_settings(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_get_shipping_settings_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 = ShippingSettingsServiceAsyncClient( - 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.get_shipping_settings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_shipping_settings] = mock_rpc - - request = {} - await client.get_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_shipping_settings(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_get_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.GetShippingSettingsRequest): - client = ShippingSettingsServiceAsyncClient( - 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.get_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) - response = await client.get_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = shippingsettings.GetShippingSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_get_shipping_settings_async_from_dict(): - await test_get_shipping_settings_async(request_type=dict) - -def test_get_shipping_settings_field_headers(): - client = ShippingSettingsServiceClient( - 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 = shippingsettings.GetShippingSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - call.return_value = shippingsettings.ShippingSettings() - client.get_shipping_settings(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_get_shipping_settings_field_headers_async(): - client = ShippingSettingsServiceAsyncClient( - 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 = shippingsettings.GetShippingSettingsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) - await client.get_shipping_settings(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_get_shipping_settings_flattened(): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = shippingsettings.ShippingSettings() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_shipping_settings( - 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_get_shipping_settings_flattened_error(): - client = ShippingSettingsServiceClient( - 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.get_shipping_settings( - shippingsettings.GetShippingSettingsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_shipping_settings_flattened_async(): - client = ShippingSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = shippingsettings.ShippingSettings() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_shipping_settings( - 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_get_shipping_settings_flattened_error_async(): - client = ShippingSettingsServiceAsyncClient( - 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.get_shipping_settings( - shippingsettings.GetShippingSettingsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - shippingsettings.InsertShippingSettingsRequest, - dict, -]) -def test_insert_shipping_settings(request_type, transport: str = 'grpc'): - client = ShippingSettingsServiceClient( - 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_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - ) - response = client.insert_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = shippingsettings.InsertShippingSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - - -def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( - 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 = shippingsettings.InsertShippingSettingsRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.insert_shipping_settings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == shippingsettings.InsertShippingSettingsRequest( - parent='parent_value', - ) - -def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( - 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_shipping_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_shipping_settings] = mock_rpc - request = {} - client.insert_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_shipping_settings(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_shipping_settings_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 = ShippingSettingsServiceAsyncClient( - 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_shipping_settings 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_shipping_settings] = mock_rpc - - request = {} - await client.insert_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.insert_shipping_settings(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_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.InsertShippingSettingsRequest): - client = ShippingSettingsServiceAsyncClient( - 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_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) - response = await client.insert_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = shippingsettings.InsertShippingSettingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.asyncio -async def test_insert_shipping_settings_async_from_dict(): - await test_insert_shipping_settings_async(request_type=dict) - -def test_insert_shipping_settings_field_headers(): - client = ShippingSettingsServiceClient( - 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 = shippingsettings.InsertShippingSettingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: - call.return_value = shippingsettings.ShippingSettings() - client.insert_shipping_settings(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_shipping_settings_field_headers_async(): - client = ShippingSettingsServiceAsyncClient( - 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 = shippingsettings.InsertShippingSettingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) - await client.insert_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_get_shipping_settings_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 = ShippingSettingsServiceClient( - 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.get_shipping_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc - - request = {} - client.get_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_shipping_settings(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_get_shipping_settings_rest_required_fields(request_type=shippingsettings.GetShippingSettingsRequest): - transport_class = transports.ShippingSettingsServiceRestTransport - - 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()).get_shipping_settings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_shipping_settings._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 = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = shippingsettings.ShippingSettings() - # 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 = shippingsettings.ShippingSettings.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.get_shipping_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_shipping_settings_rest_unset_required_fields(): - transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_shipping_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_shipping_settings_rest_flattened(): - client = ShippingSettingsServiceClient( - 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 = shippingsettings.ShippingSettings() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/shippingSettings'} - - # 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 - # Convert return value to protobuf type - return_value = shippingsettings.ShippingSettings.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.get_shipping_settings(**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/accounts/v1beta/{name=accounts/*/shippingSettings}" % client.transport._host, args[1]) - - -def test_get_shipping_settings_rest_flattened_error(transport: str = 'rest'): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_shipping_settings( - shippingsettings.GetShippingSettingsRequest(), - name='name_value', - ) - - -def test_insert_shipping_settings_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 = ShippingSettingsServiceClient( - 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_shipping_settings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_shipping_settings] = mock_rpc - - request = {} - client.insert_shipping_settings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.insert_shipping_settings(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_shipping_settings_rest_required_fields(request_type=shippingsettings.InsertShippingSettingsRequest): - transport_class = transports.ShippingSettingsServiceRestTransport - - 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_shipping_settings._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_shipping_settings._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 = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = shippingsettings.ShippingSettings() - # 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 = shippingsettings.ShippingSettings.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_shipping_settings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_insert_shipping_settings_rest_unset_required_fields(): - transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.insert_shipping_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "shippingSetting", ))) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ShippingSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ShippingSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ShippingSettingsServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ShippingSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ShippingSettingsServiceClient( - 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 = ShippingSettingsServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ShippingSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ShippingSettingsServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ShippingSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ShippingSettingsServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ShippingSettingsServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ShippingSettingsServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ShippingSettingsServiceGrpcTransport, - transports.ShippingSettingsServiceGrpcAsyncIOTransport, - transports.ShippingSettingsServiceRestTransport, -]) -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 = ShippingSettingsServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ShippingSettingsServiceClient( - 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_get_shipping_settings_empty_call_grpc(): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - call.return_value = shippingsettings.ShippingSettings() - client.get_shipping_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = shippingsettings.GetShippingSettingsRequest() - - 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_shipping_settings_empty_call_grpc(): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: - call.return_value = shippingsettings.ShippingSettings() - client.insert_shipping_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = shippingsettings.InsertShippingSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ShippingSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ShippingSettingsServiceAsyncClient( - 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_get_shipping_settings_empty_call_grpc_asyncio(): - client = ShippingSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) - await client.get_shipping_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = shippingsettings.GetShippingSettingsRequest() - - 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_shipping_settings_empty_call_grpc_asyncio(): - client = ShippingSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) - await client.insert_shipping_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = shippingsettings.InsertShippingSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ShippingSettingsServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_shipping_settings_rest_bad_request(request_type=shippingsettings.GetShippingSettingsRequest): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/shippingSettings'} - 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.get_shipping_settings(request) - - -@pytest.mark.parametrize("request_type", [ - shippingsettings.GetShippingSettingsRequest, - dict, -]) -def test_get_shipping_settings_rest_call_success(request_type): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/shippingSettings'} - request = request_type(**request_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 = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_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 = shippingsettings.ShippingSettings.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.get_shipping_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_shipping_settings_rest_interceptors(null_interceptor): - transport = transports.ShippingSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), - ) - client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings") as post, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_get_shipping_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = shippingsettings.GetShippingSettingsRequest.pb(shippingsettings.GetShippingSettingsRequest()) - 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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) - req.return_value.content = return_value - - request = shippingsettings.GetShippingSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = shippingsettings.ShippingSettings() - post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata - - client.get_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_insert_shipping_settings_rest_bad_request(request_type=shippingsettings.InsertShippingSettingsRequest): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_shipping_settings(request) - - -@pytest.mark.parametrize("request_type", [ - shippingsettings.InsertShippingSettingsRequest, - dict, -]) -def test_insert_shipping_settings_rest_call_success(request_type): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["shipping_setting"] = {'name': 'name_value', 'services': [{'service_name': 'service_name_value', 'active': True, 'delivery_countries': ['delivery_countries_value1', 'delivery_countries_value2'], 'currency_code': 'currency_code_value', 'delivery_time': {'min_transit_days': 1720, 'max_transit_days': 1722, 'cutoff_time': {'hour': 446, 'minute': 658, 'time_zone': 'time_zone_value'}, 'min_handling_days': 1784, 'max_handling_days': 1786, 'transit_time_table': {'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'transit_time_labels': ['transit_time_labels_value1', 'transit_time_labels_value2'], 'rows': [{'values': [{'min_transit_days': 1720, 'max_transit_days': 1722}]}]}, 'handling_business_day_config': {'business_days': [1]}, 'transit_business_day_config': {}, 'warehouse_based_delivery_times': [{'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'warehouse': 'warehouse_value'}]}, 'rate_groups': [{'applicable_shipping_labels': ['applicable_shipping_labels_value1', 'applicable_shipping_labels_value2'], 'single_value': {'no_shipping': True, 'flat_rate': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'price_percentage': 'price_percentage_value', 'carrier_rate': 'carrier_rate_value', 'subtable': 'subtable_value'}, 'main_table': {'name': 'name_value', 'row_headers': {'prices': {}, 'weights': [{'amount_micros': 1408, 'unit': 1}], 'number_of_items': ['number_of_items_value1', 'number_of_items_value2'], 'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'locations': [{'location_ids': ['location_ids_value1', 'location_ids_value2']}]}, 'column_headers': {}, 'rows': [{'cells': {}}]}, 'subtables': {}, 'carrier_rates': [{'name': 'name_value', 'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'origin_postal_code': 'origin_postal_code_value', 'percentage_adjustment': 'percentage_adjustment_value', 'flat_adjustment': {}}], 'name': 'name_value'}], 'shipment_type': 1, 'minimum_order_value': {}, 'minimum_order_value_table': {'store_code_set_with_movs': [{'store_codes': ['store_codes_value1', 'store_codes_value2'], 'value': {}}]}, 'store_config': {'store_service_type': 1, 'store_codes': ['store_codes_value1', 'store_codes_value2'], 'cutoff_config': {'local_cutoff_time': {'hour': 446, 'minute': 658}, 'store_close_offset_hours': 2584, 'no_delivery_post_cutoff': True}, 'service_radius': {'value': 541, 'unit': 1}}, 'loyalty_programs': [{'program_label': 'program_label_value', 'loyalty_program_tiers': [{'tier_label': 'tier_label_value'}]}]}], 'warehouses': [{'name': 'name_value', 'shipping_address': {'street_address': 'street_address_value', 'city': 'city_value', 'administrative_area': 'administrative_area_value', 'postal_code': 'postal_code_value', 'region_code': 'region_code_value'}, 'cutoff_time': {'hour': 446, 'minute': 658}, 'handling_days': 1365, 'business_day_config': {}}], 'etag': 'etag_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 = shippingsettings.InsertShippingSettingsRequest.meta.fields["shipping_setting"] - - 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["shipping_setting"].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["shipping_setting"][field])): - del request_init["shipping_setting"][field][i][subfield] - else: - del request_init["shipping_setting"][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 = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_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 = shippingsettings.ShippingSettings.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_shipping_settings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_shipping_settings_rest_interceptors(null_interceptor): - transport = transports.ShippingSettingsServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), - ) - client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings") as post, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_insert_shipping_settings") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = shippingsettings.InsertShippingSettingsRequest.pb(shippingsettings.InsertShippingSettingsRequest()) - 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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) - req.return_value.content = return_value - - request = shippingsettings.InsertShippingSettingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = shippingsettings.ShippingSettings() - post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata - - client.insert_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = ShippingSettingsServiceClient( - 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_get_shipping_settings_empty_call_rest(): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - client.get_shipping_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = shippingsettings.GetShippingSettingsRequest() - - 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_shipping_settings_empty_call_rest(): - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: - client.insert_shipping_settings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = shippingsettings.InsertShippingSettingsRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ShippingSettingsServiceGrpcTransport, - ) - -def test_shipping_settings_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ShippingSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_shipping_settings_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ShippingSettingsServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_shipping_settings', - 'insert_shipping_settings', - ) - 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_shipping_settings_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_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ShippingSettingsServiceTransport( - 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_shipping_settings_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_accounts_v1beta.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ShippingSettingsServiceTransport() - adc.assert_called_once() - - -def test_shipping_settings_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) - ShippingSettingsServiceClient() - 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.ShippingSettingsServiceGrpcTransport, - transports.ShippingSettingsServiceGrpcAsyncIOTransport, - ], -) -def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, - transports.ShippingSettingsServiceGrpcAsyncIOTransport, - transports.ShippingSettingsServiceRestTransport, - ], -) -def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, grpc_helpers), - (transports.ShippingSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) -def test_shipping_settings_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_shipping_settings_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.ShippingSettingsServiceRestTransport ( - 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_shipping_settings_service_host_no_port(transport_name): - client = ShippingSettingsServiceClient( - 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_shipping_settings_service_host_with_port(transport_name): - client = ShippingSettingsServiceClient( - 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_shipping_settings_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ShippingSettingsServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ShippingSettingsServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_shipping_settings._session - session2 = client2.transport.get_shipping_settings._session - assert session1 != session2 - session1 = client1.transport.insert_shipping_settings._session - session2 = client2.transport.insert_shipping_settings._session - assert session1 != session2 -def test_shipping_settings_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ShippingSettingsServiceGrpcTransport( - 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_shipping_settings_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ShippingSettingsServiceGrpcAsyncIOTransport( - 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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) -def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) -def test_shipping_settings_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_shipping_settings_path(): - account = "squid" - expected = "accounts/{account}/shippingSettings".format(account=account, ) - actual = ShippingSettingsServiceClient.shipping_settings_path(account) - assert expected == actual - - -def test_parse_shipping_settings_path(): - expected = { - "account": "clam", - } - path = ShippingSettingsServiceClient.shipping_settings_path(**expected) - - # Check that the path construction is reversible. - actual = ShippingSettingsServiceClient.parse_shipping_settings_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ShippingSettingsServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ShippingSettingsServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ShippingSettingsServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ShippingSettingsServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ShippingSettingsServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ShippingSettingsServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ShippingSettingsServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ShippingSettingsServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ShippingSettingsServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ShippingSettingsServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ShippingSettingsServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ShippingSettingsServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ShippingSettingsServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ShippingSettingsServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ShippingSettingsServiceClient.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.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: - client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ShippingSettingsServiceClient.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 = ShippingSettingsServiceClient( - 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 = ShippingSettingsServiceAsyncClient( - 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 = ShippingSettingsServiceClient( - 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 = ShippingSettingsServiceClient( - 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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py deleted file mode 100644 index 643f85170d3b..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_agreement_state_service.py +++ /dev/null @@ -1,2854 +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.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service import transports -from google.shopping.merchant_accounts_v1beta.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1beta.types import termsofservicekind -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 TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(None) is None - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, False) is None - assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, None) == TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - TermsOfServiceAgreementStateServiceClient._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 = TermsOfServiceAgreementStateServiceClient(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 = TermsOfServiceAgreementStateServiceClient(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", [ - (TermsOfServiceAgreementStateServiceClient, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, "rest"), -]) -def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -def test_terms_of_service_agreement_state_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", [ - (TermsOfServiceAgreementStateServiceClient, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, "rest"), -]) -def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_service_client_get_transport_class(): - transport = TermsOfServiceAgreementStateServiceClient.get_transport_class() - available_transports = [ - transports.TermsOfServiceAgreementStateServiceGrpcTransport, - transports.TermsOfServiceAgreementStateServiceRestTransport, - ] - assert transport in available_transports - - transport = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc") - assert transport == transports.TermsOfServiceAgreementStateServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) -def test_terms_of_service_agreement_state_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(TermsOfServiceAgreementStateServiceClient, '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(TermsOfServiceAgreementStateServiceClient, '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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "true"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "false"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "true"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_terms_of_service_agreement_state_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", [ - TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceAsyncClient)) -def test_terms_of_service_agreement_state_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", [ - TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) -def test_terms_of_service_agreement_state_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TermsOfServiceAgreementStateServiceClient._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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -def test_terms_of_service_agreement_state_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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", None), -]) -def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TermsOfServiceAgreementStateServiceClient( - 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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_terms_of_service_agreement_state_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", [ - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, - dict, -]) -def test_get_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): - client = TermsOfServiceAgreementStateServiceClient( - 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.get_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - ) - response = client.get_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - - -def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( - 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_terms_of_service_agreement_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( - name='name_value', - ) - -def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( - 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.get_terms_of_service_agreement_state in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc - request = {} - client.get_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceAsyncClient( - 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.get_terms_of_service_agreement_state in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service_agreement_state] = mock_rpc - - request = {} - await client.get_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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.get_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) - response = await client.get_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - - -@pytest.mark.asyncio -async def test_get_terms_of_service_agreement_state_async_from_dict(): - await test_get_terms_of_service_agreement_state_async(request_type=dict) - -def test_get_terms_of_service_agreement_state_field_headers(): - client = TermsOfServiceAgreementStateServiceClient( - 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_field_headers_async(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) - await client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_flattened(): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_terms_of_service_agreement_state( - 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_get_terms_of_service_agreement_state_flattened_error(): - client = TermsOfServiceAgreementStateServiceClient( - 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.get_terms_of_service_agreement_state( - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_terms_of_service_agreement_state_flattened_async(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_terms_of_service_agreement_state( - 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_get_terms_of_service_agreement_state_flattened_error_async(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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.get_terms_of_service_agreement_state( - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, - dict, -]) -def test_retrieve_for_application_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): - client = TermsOfServiceAgreementStateServiceClient( - 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.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - ) - response = client.retrieve_for_application_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - - -def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( - 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.retrieve_for_application_terms_of_service_agreement_state(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent='parent_value', - ) - -def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( - 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.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc - request = {} - client.retrieve_for_application_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceAsyncClient( - 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.retrieve_for_application_terms_of_service_agreement_state 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.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc - - request = {} - await client.retrieve_for_application_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) - response = await client.retrieve_for_application_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - - -@pytest.mark.asyncio -async def test_retrieve_for_application_terms_of_service_agreement_state_async_from_dict(): - await test_retrieve_for_application_terms_of_service_agreement_state_async(request_type=dict) - -def test_retrieve_for_application_terms_of_service_agreement_state_field_headers(): - client = TermsOfServiceAgreementStateServiceClient( - 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_field_headers_async(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) - await client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_flattened(): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.retrieve_for_application_terms_of_service_agreement_state( - 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error(): - client = TermsOfServiceAgreementStateServiceClient( - 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.retrieve_for_application_terms_of_service_agreement_state( - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_retrieve_for_application_terms_of_service_agreement_state_flattened_async(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.retrieve_for_application_terms_of_service_agreement_state( - 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error_async(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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.retrieve_for_application_terms_of_service_agreement_state( - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), - parent='parent_value', - ) - - -def test_get_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( - 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.get_terms_of_service_agreement_state in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc - - request = {} - client.get_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_terms_of_service_agreement_state(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_get_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport - - 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()).get_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_terms_of_service_agreement_state_rest_unset_required_fields(): - transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_terms_of_service_agreement_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_terms_of_service_agreement_state_rest_flattened(): - client = TermsOfServiceAgreementStateServiceClient( - 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 = termsofserviceagreementstate.TermsOfServiceAgreementState() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/termsOfServiceAgreementStates/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(**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/accounts/v1beta/{name=accounts/*/termsOfServiceAgreementStates/*}" % client.transport._host, args[1]) - - -def test_get_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_terms_of_service_agreement_state( - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), - name='name_value', - ) - - -def test_retrieve_for_application_terms_of_service_agreement_state_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 = TermsOfServiceAgreementStateServiceClient( - 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.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc - - request = {} - client.retrieve_for_application_terms_of_service_agreement_state(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.retrieve_for_application_terms_of_service_agreement_state(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_retrieve_for_application_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport - - 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()).retrieve_for_application_terms_of_service_agreement_state._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()).retrieve_for_application_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_retrieve_for_application_terms_of_service_agreement_state_rest_unset_required_fields(): - transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened(): - client = TermsOfServiceAgreementStateServiceClient( - 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 = termsofserviceagreementstate.TermsOfServiceAgreementState() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(**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/accounts/v1beta/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication" % client.transport._host, args[1]) - - -def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): - client = TermsOfServiceAgreementStateServiceClient( - 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.retrieve_for_application_terms_of_service_agreement_state( - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TermsOfServiceAgreementStateServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TermsOfServiceAgreementStateServiceClient( - 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 = TermsOfServiceAgreementStateServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TermsOfServiceAgreementStateServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TermsOfServiceAgreementStateServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TermsOfServiceAgreementStateServiceGrpcTransport, - transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, - transports.TermsOfServiceAgreementStateServiceRestTransport, -]) -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 = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = TermsOfServiceAgreementStateServiceClient( - 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_get_terms_of_service_agreement_state_empty_call_grpc(): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - client.get_terms_of_service_agreement_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - - 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_grpc(): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - client.retrieve_for_application_terms_of_service_agreement_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = TermsOfServiceAgreementStateServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - 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_get_terms_of_service_agreement_state_empty_call_grpc_asyncio(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) - await client.get_terms_of_service_agreement_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - - 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_grpc_asyncio(): - client = TermsOfServiceAgreementStateServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) - await client.retrieve_for_application_terms_of_service_agreement_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = TermsOfServiceAgreementStateServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/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.get_terms_of_service_agreement_state(request) - - -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, - dict, -]) -def test_get_terms_of_service_agreement_state_rest_call_success(request_type): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/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 = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - ) - - # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.get_terms_of_service_agreement_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_terms_of_service_agreement_state_rest_interceptors(null_interceptor): - transport = transports.TermsOfServiceAgreementStateServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), - ) - client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state") as post, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_get_terms_of_service_agreement_state") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest()) - 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) - req.return_value.content = return_value - - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata - - client.get_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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.retrieve_for_application_terms_of_service_agreement_state(request) - - -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, - dict, -]) -def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_success(request_type): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - ) - - # 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.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.retrieve_for_application_terms_of_service_agreement_state(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_retrieve_for_application_terms_of_service_agreement_state_rest_interceptors(null_interceptor): - transport = transports.TermsOfServiceAgreementStateServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), - ) - client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state") as post, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_retrieve_for_application_terms_of_service_agreement_state") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest()) - 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) - req.return_value.content = return_value - - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata - - client.retrieve_for_application_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = TermsOfServiceAgreementStateServiceClient( - 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_get_terms_of_service_agreement_state_empty_call_rest(): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - client.get_terms_of_service_agreement_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - - 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_retrieve_for_application_terms_of_service_agreement_state_empty_call_rest(): - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - client.retrieve_for_application_terms_of_service_agreement_state(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TermsOfServiceAgreementStateServiceGrpcTransport, - ) - -def test_terms_of_service_agreement_state_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TermsOfServiceAgreementStateServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_terms_of_service_agreement_state_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TermsOfServiceAgreementStateServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_terms_of_service_agreement_state', - 'retrieve_for_application_terms_of_service_agreement_state', - ) - 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_terms_of_service_agreement_state_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_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TermsOfServiceAgreementStateServiceTransport( - 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_terms_of_service_agreement_state_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_accounts_v1beta.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TermsOfServiceAgreementStateServiceTransport() - adc.assert_called_once() - - -def test_terms_of_service_agreement_state_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) - TermsOfServiceAgreementStateServiceClient() - 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.TermsOfServiceAgreementStateServiceGrpcTransport, - transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, - ], -) -def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, - transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, - transports.TermsOfServiceAgreementStateServiceRestTransport, - ], -) -def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, grpc_helpers), - (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) -def test_terms_of_service_agreement_state_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_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceRestTransport ( - 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_terms_of_service_agreement_state_service_host_no_port(transport_name): - client = TermsOfServiceAgreementStateServiceClient( - 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_terms_of_service_agreement_state_service_host_with_port(transport_name): - client = TermsOfServiceAgreementStateServiceClient( - 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_terms_of_service_agreement_state_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = TermsOfServiceAgreementStateServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = TermsOfServiceAgreementStateServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_terms_of_service_agreement_state._session - session2 = client2.transport.get_terms_of_service_agreement_state._session - assert session1 != session2 - session1 = client1.transport.retrieve_for_application_terms_of_service_agreement_state._session - session2 = client2.transport.retrieve_for_application_terms_of_service_agreement_state._session - assert session1 != session2 -def test_terms_of_service_agreement_state_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( - 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_terms_of_service_agreement_state_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( - 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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) -def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) -def test_terms_of_service_agreement_state_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = TermsOfServiceAgreementStateServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = TermsOfServiceAgreementStateServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_account_path(path) - assert expected == actual - -def test_terms_of_service_path(): - version = "whelk" - expected = "termsOfService/{version}".format(version=version, ) - actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(version) - assert expected == actual - - -def test_parse_terms_of_service_path(): - expected = { - "version": "octopus", - } - path = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path(path) - assert expected == actual - -def test_terms_of_service_agreement_state_path(): - account = "oyster" - identifier = "nudibranch" - expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) - actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(account, identifier) - assert expected == actual - - -def test_parse_terms_of_service_agreement_state_path(): - expected = { - "account": "cuttlefish", - "identifier": "mussel", - } - path = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = TermsOfServiceAgreementStateServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = TermsOfServiceAgreementStateServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TermsOfServiceAgreementStateServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = TermsOfServiceAgreementStateServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = TermsOfServiceAgreementStateServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = TermsOfServiceAgreementStateServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = TermsOfServiceAgreementStateServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = TermsOfServiceAgreementStateServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.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.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: - client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = TermsOfServiceAgreementStateServiceClient.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 = TermsOfServiceAgreementStateServiceClient( - 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 = TermsOfServiceAgreementStateServiceAsyncClient( - 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 = TermsOfServiceAgreementStateServiceClient( - 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 = TermsOfServiceAgreementStateServiceClient( - 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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py deleted file mode 100644 index efa214562c18..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_terms_of_service_service.py +++ /dev/null @@ -1,3331 +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.shopping.merchant_accounts_v1beta.services.terms_of_service_service import TermsOfServiceServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service import TermsOfServiceServiceClient -from google.shopping.merchant_accounts_v1beta.services.terms_of_service_service import transports -from google.shopping.merchant_accounts_v1beta.types import termsofservice -from google.shopping.merchant_accounts_v1beta.types import termsofservicekind -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 TermsOfServiceServiceClient._get_default_mtls_endpoint(None) is None - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, False) is None - assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert TermsOfServiceServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert TermsOfServiceServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert TermsOfServiceServiceClient._get_universe_domain(None, None) == TermsOfServiceServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient(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 = TermsOfServiceServiceClient(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", [ - (TermsOfServiceServiceClient, "grpc"), - (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceServiceClient, "rest"), -]) -def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, "grpc"), - (transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TermsOfServiceServiceRestTransport, "rest"), -]) -def test_terms_of_service_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", [ - (TermsOfServiceServiceClient, "grpc"), - (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceServiceClient, "rest"), -]) -def test_terms_of_service_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_terms_of_service_service_client_get_transport_class(): - transport = TermsOfServiceServiceClient.get_transport_class() - available_transports = [ - transports.TermsOfServiceServiceGrpcTransport, - transports.TermsOfServiceServiceRestTransport, - ] - assert transport in available_transports - - transport = TermsOfServiceServiceClient.get_transport_class("grpc") - assert transport == transports.TermsOfServiceServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), -]) -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) -def test_terms_of_service_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(TermsOfServiceServiceClient, '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(TermsOfServiceServiceClient, '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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "true"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "false"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "true"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_terms_of_service_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", [ - TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceAsyncClient)) -def test_terms_of_service_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", [ - TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) -def test_terms_of_service_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = TermsOfServiceServiceClient._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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), -]) -def test_terms_of_service_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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", None), -]) -def test_terms_of_service_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_terms_of_service_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = TermsOfServiceServiceClient( - 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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_terms_of_service_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", [ - termsofservice.GetTermsOfServiceRequest, - dict, -]) -def test_get_terms_of_service(request_type, transport: str = 'grpc'): - client = TermsOfServiceServiceClient( - 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.get_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - ) - response = client.get_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = termsofservice.GetTermsOfServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' - assert response.external is True - - -def test_get_terms_of_service_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 = TermsOfServiceServiceClient( - 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 = termsofservice.GetTermsOfServiceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_terms_of_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == termsofservice.GetTermsOfServiceRequest( - name='name_value', - ) - -def test_get_terms_of_service_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 = TermsOfServiceServiceClient( - 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.get_terms_of_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc - request = {} - client.get_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_terms_of_service(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_get_terms_of_service_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 = TermsOfServiceServiceAsyncClient( - 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.get_terms_of_service in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service] = mock_rpc - - request = {} - await client.get_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_terms_of_service(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_get_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.GetTermsOfServiceRequest): - client = TermsOfServiceServiceAsyncClient( - 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.get_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) - response = await client.get_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = termsofservice.GetTermsOfServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' - assert response.external is True - - -@pytest.mark.asyncio -async def test_get_terms_of_service_async_from_dict(): - await test_get_terms_of_service_async(request_type=dict) - -def test_get_terms_of_service_field_headers(): - client = TermsOfServiceServiceClient( - 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 = termsofservice.GetTermsOfServiceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - call.return_value = termsofservice.TermsOfService() - client.get_terms_of_service(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_get_terms_of_service_field_headers_async(): - client = TermsOfServiceServiceAsyncClient( - 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 = termsofservice.GetTermsOfServiceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) - await client.get_terms_of_service(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_get_terms_of_service_flattened(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofservice.TermsOfService() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_terms_of_service( - 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_get_terms_of_service_flattened_error(): - client = TermsOfServiceServiceClient( - 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.get_terms_of_service( - termsofservice.GetTermsOfServiceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_terms_of_service_flattened_async(): - client = TermsOfServiceServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofservice.TermsOfService() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_terms_of_service( - 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_get_terms_of_service_flattened_error_async(): - client = TermsOfServiceServiceAsyncClient( - 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.get_terms_of_service( - termsofservice.GetTermsOfServiceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - termsofservice.RetrieveLatestTermsOfServiceRequest, - dict, -]) -def test_retrieve_latest_terms_of_service(request_type, transport: str = 'grpc'): - client = TermsOfServiceServiceClient( - 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.retrieve_latest_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - ) - response = client.retrieve_latest_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = termsofservice.RetrieveLatestTermsOfServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' - assert response.external is True - - -def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( - 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 = termsofservice.RetrieveLatestTermsOfServiceRequest( - region_code='region_code_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.retrieve_latest_terms_of_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == termsofservice.RetrieveLatestTermsOfServiceRequest( - region_code='region_code_value', - ) - -def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( - 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.retrieve_latest_terms_of_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc - request = {} - client.retrieve_latest_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceAsyncClient( - 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.retrieve_latest_terms_of_service 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.retrieve_latest_terms_of_service] = mock_rpc - - request = {} - await client.retrieve_latest_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): - client = TermsOfServiceServiceAsyncClient( - 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.retrieve_latest_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) - response = await client.retrieve_latest_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = termsofservice.RetrieveLatestTermsOfServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' - assert response.external is True - - -@pytest.mark.asyncio -async def test_retrieve_latest_terms_of_service_async_from_dict(): - await test_retrieve_latest_terms_of_service_async(request_type=dict) - - -@pytest.mark.parametrize("request_type", [ - termsofservice.AcceptTermsOfServiceRequest, - dict, -]) -def test_accept_terms_of_service(request_type, transport: str = 'grpc'): - client = TermsOfServiceServiceClient( - 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.accept_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.accept_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = termsofservice.AcceptTermsOfServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( - 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 = termsofservice.AcceptTermsOfServiceRequest( - name='name_value', - account='account_value', - region_code='region_code_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.accept_terms_of_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == termsofservice.AcceptTermsOfServiceRequest( - name='name_value', - account='account_value', - region_code='region_code_value', - ) - -def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( - 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.accept_terms_of_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc - request = {} - client.accept_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.accept_terms_of_service(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_accept_terms_of_service_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 = TermsOfServiceServiceAsyncClient( - 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.accept_terms_of_service 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.accept_terms_of_service] = mock_rpc - - request = {} - await client.accept_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.accept_terms_of_service(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_accept_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.AcceptTermsOfServiceRequest): - client = TermsOfServiceServiceAsyncClient( - 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.accept_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.accept_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = termsofservice.AcceptTermsOfServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_accept_terms_of_service_async_from_dict(): - await test_accept_terms_of_service_async(request_type=dict) - -def test_accept_terms_of_service_field_headers(): - client = TermsOfServiceServiceClient( - 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 = termsofservice.AcceptTermsOfServiceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - call.return_value = None - client.accept_terms_of_service(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_accept_terms_of_service_field_headers_async(): - client = TermsOfServiceServiceAsyncClient( - 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 = termsofservice.AcceptTermsOfServiceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.accept_terms_of_service(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_accept_terms_of_service_flattened(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__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.accept_terms_of_service( - 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_accept_terms_of_service_flattened_error(): - client = TermsOfServiceServiceClient( - 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.accept_terms_of_service( - termsofservice.AcceptTermsOfServiceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_accept_terms_of_service_flattened_async(): - client = TermsOfServiceServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__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.accept_terms_of_service( - 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_accept_terms_of_service_flattened_error_async(): - client = TermsOfServiceServiceAsyncClient( - 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.accept_terms_of_service( - termsofservice.AcceptTermsOfServiceRequest(), - name='name_value', - ) - - -def test_get_terms_of_service_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 = TermsOfServiceServiceClient( - 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.get_terms_of_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc - - request = {} - client.get_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_terms_of_service(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_get_terms_of_service_rest_required_fields(request_type=termsofservice.GetTermsOfServiceRequest): - transport_class = transports.TermsOfServiceServiceRestTransport - - 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()).get_terms_of_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service._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 = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = termsofservice.TermsOfService() - # 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 = termsofservice.TermsOfService.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.get_terms_of_service(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_terms_of_service_rest_unset_required_fields(): - transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_terms_of_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_terms_of_service_rest_flattened(): - client = TermsOfServiceServiceClient( - 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 = termsofservice.TermsOfService() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'termsOfService/sample1'} - - # 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 - # Convert return value to protobuf type - return_value = termsofservice.TermsOfService.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.get_terms_of_service(**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/accounts/v1beta/{name=termsOfService/*}" % client.transport._host, args[1]) - - -def test_get_terms_of_service_rest_flattened_error(transport: str = 'rest'): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_terms_of_service( - termsofservice.GetTermsOfServiceRequest(), - name='name_value', - ) - - -def test_retrieve_latest_terms_of_service_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 = TermsOfServiceServiceClient( - 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.retrieve_latest_terms_of_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc - - request = {} - client.retrieve_latest_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.retrieve_latest_terms_of_service(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_retrieve_latest_terms_of_service_rest_required_fields(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): - transport_class = transports.TermsOfServiceServiceRestTransport - - request_init = {} - request_init["region_code"] = "" - 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 - assert "regionCode" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "regionCode" in jsonified_request - assert jsonified_request["regionCode"] == request_init["region_code"] - - jsonified_request["regionCode"] = 'region_code_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("kind", "region_code", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "regionCode" in jsonified_request - assert jsonified_request["regionCode"] == 'region_code_value' - - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = termsofservice.TermsOfService() - # 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 = termsofservice.TermsOfService.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.retrieve_latest_terms_of_service(request) - - expected_params = [ - ( - "regionCode", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_retrieve_latest_terms_of_service_rest_unset_required_fields(): - transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.retrieve_latest_terms_of_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(("kind", "regionCode", )) & set(("regionCode", "kind", ))) - - -def test_accept_terms_of_service_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 = TermsOfServiceServiceClient( - 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.accept_terms_of_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc - - request = {} - client.accept_terms_of_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.accept_terms_of_service(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_accept_terms_of_service_rest_required_fields(request_type=termsofservice.AcceptTermsOfServiceRequest): - transport_class = transports.TermsOfServiceServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["account"] = "" - request_init["region_code"] = "" - 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 - assert "account" not in jsonified_request - assert "regionCode" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "account" in jsonified_request - assert jsonified_request["account"] == request_init["account"] - assert "regionCode" in jsonified_request - assert jsonified_request["regionCode"] == request_init["region_code"] - - jsonified_request["name"] = 'name_value' - jsonified_request["account"] = 'account_value' - jsonified_request["regionCode"] = 'region_code_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("account", "region_code", )) - 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 "account" in jsonified_request - assert jsonified_request["account"] == 'account_value' - assert "regionCode" in jsonified_request - assert jsonified_request["regionCode"] == 'region_code_value' - - client = TermsOfServiceServiceClient( - 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': "get", - '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.accept_terms_of_service(request) - - expected_params = [ - ( - "account", - "", - ), - ( - "regionCode", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_accept_terms_of_service_rest_unset_required_fields(): - transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.accept_terms_of_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(("account", "regionCode", )) & set(("name", "account", "regionCode", ))) - - -def test_accept_terms_of_service_rest_flattened(): - client = TermsOfServiceServiceClient( - 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': 'termsOfService/sample1'} - - # 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.accept_terms_of_service(**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/accounts/v1beta/{name=termsOfService/*}:accept" % client.transport._host, args[1]) - - -def test_accept_terms_of_service_rest_flattened_error(transport: str = 'rest'): - client = TermsOfServiceServiceClient( - 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.accept_terms_of_service( - termsofservice.AcceptTermsOfServiceRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.TermsOfServiceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.TermsOfServiceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TermsOfServiceServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.TermsOfServiceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = TermsOfServiceServiceClient( - 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 = TermsOfServiceServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.TermsOfServiceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = TermsOfServiceServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.TermsOfServiceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = TermsOfServiceServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.TermsOfServiceServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.TermsOfServiceServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.TermsOfServiceServiceGrpcTransport, - transports.TermsOfServiceServiceGrpcAsyncIOTransport, - transports.TermsOfServiceServiceRestTransport, -]) -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 = TermsOfServiceServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = TermsOfServiceServiceClient( - 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_get_terms_of_service_empty_call_grpc(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - call.return_value = termsofservice.TermsOfService() - client.get_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.GetTermsOfServiceRequest() - - 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_retrieve_latest_terms_of_service_empty_call_grpc(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: - call.return_value = termsofservice.TermsOfService() - client.retrieve_latest_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() - - 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_accept_terms_of_service_empty_call_grpc(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - call.return_value = None - client.accept_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.AcceptTermsOfServiceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = TermsOfServiceServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = TermsOfServiceServiceAsyncClient( - 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_get_terms_of_service_empty_call_grpc_asyncio(): - client = TermsOfServiceServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) - await client.get_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.GetTermsOfServiceRequest() - - 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_retrieve_latest_terms_of_service_empty_call_grpc_asyncio(): - client = TermsOfServiceServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) - await client.retrieve_latest_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() - - 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_accept_terms_of_service_empty_call_grpc_asyncio(): - client = TermsOfServiceServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.accept_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.AcceptTermsOfServiceRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = TermsOfServiceServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_terms_of_service_rest_bad_request(request_type=termsofservice.GetTermsOfServiceRequest): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} - 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.get_terms_of_service(request) - - -@pytest.mark.parametrize("request_type", [ - termsofservice.GetTermsOfServiceRequest, - dict, -]) -def test_get_terms_of_service_rest_call_success(request_type): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - ) - - # 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 = termsofservice.TermsOfService.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.get_terms_of_service(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' - assert response.external is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_terms_of_service_rest_interceptors(null_interceptor): - transport = transports.TermsOfServiceServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), - ) - client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service") as post, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_get_terms_of_service") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = termsofservice.GetTermsOfServiceRequest.pb(termsofservice.GetTermsOfServiceRequest()) - 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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) - req.return_value.content = return_value - - request = termsofservice.GetTermsOfServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = termsofservice.TermsOfService() - post_with_metadata.return_value = termsofservice.TermsOfService(), metadata - - client.get_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_retrieve_latest_terms_of_service_rest_bad_request(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # 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.retrieve_latest_terms_of_service(request) - - -@pytest.mark.parametrize("request_type", [ - termsofservice.RetrieveLatestTermsOfServiceRequest, - dict, -]) -def test_retrieve_latest_terms_of_service_rest_call_success(request_type): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - ) - - # 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 = termsofservice.TermsOfService.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.retrieve_latest_terms_of_service(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' - assert response.external is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_retrieve_latest_terms_of_service_rest_interceptors(null_interceptor): - transport = transports.TermsOfServiceServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), - ) - client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service") as post, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_retrieve_latest_terms_of_service") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = termsofservice.RetrieveLatestTermsOfServiceRequest.pb(termsofservice.RetrieveLatestTermsOfServiceRequest()) - 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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) - req.return_value.content = return_value - - request = termsofservice.RetrieveLatestTermsOfServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = termsofservice.TermsOfService() - post_with_metadata.return_value = termsofservice.TermsOfService(), metadata - - client.retrieve_latest_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_accept_terms_of_service_rest_bad_request(request_type=termsofservice.AcceptTermsOfServiceRequest): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} - 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.accept_terms_of_service(request) - - -@pytest.mark.parametrize("request_type", [ - termsofservice.AcceptTermsOfServiceRequest, - dict, -]) -def test_accept_terms_of_service_rest_call_success(request_type): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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.accept_terms_of_service(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_accept_terms_of_service_rest_interceptors(null_interceptor): - transport = transports.TermsOfServiceServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), - ) - client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "pre_accept_terms_of_service") as pre: - pre.assert_not_called() - pb_message = termsofservice.AcceptTermsOfServiceRequest.pb(termsofservice.AcceptTermsOfServiceRequest()) - 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 = termsofservice.AcceptTermsOfServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.accept_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - -def test_initialize_client_w_rest(): - client = TermsOfServiceServiceClient( - 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_get_terms_of_service_empty_call_rest(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - client.get_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.GetTermsOfServiceRequest() - - 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_retrieve_latest_terms_of_service_empty_call_rest(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: - client.retrieve_latest_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.RetrieveLatestTermsOfServiceRequest() - - 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_accept_terms_of_service_empty_call_rest(): - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - client.accept_terms_of_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = termsofservice.AcceptTermsOfServiceRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.TermsOfServiceServiceGrpcTransport, - ) - -def test_terms_of_service_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.TermsOfServiceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_terms_of_service_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.TermsOfServiceServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_terms_of_service', - 'retrieve_latest_terms_of_service', - 'accept_terms_of_service', - ) - 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_terms_of_service_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_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TermsOfServiceServiceTransport( - 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_terms_of_service_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_accounts_v1beta.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.TermsOfServiceServiceTransport() - adc.assert_called_once() - - -def test_terms_of_service_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) - TermsOfServiceServiceClient() - 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.TermsOfServiceServiceGrpcTransport, - transports.TermsOfServiceServiceGrpcAsyncIOTransport, - ], -) -def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, - transports.TermsOfServiceServiceGrpcAsyncIOTransport, - transports.TermsOfServiceServiceRestTransport, - ], -) -def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, grpc_helpers), - (transports.TermsOfServiceServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) -def test_terms_of_service_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_terms_of_service_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.TermsOfServiceServiceRestTransport ( - 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_terms_of_service_service_host_no_port(transport_name): - client = TermsOfServiceServiceClient( - 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_terms_of_service_service_host_with_port(transport_name): - client = TermsOfServiceServiceClient( - 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_terms_of_service_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = TermsOfServiceServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = TermsOfServiceServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_terms_of_service._session - session2 = client2.transport.get_terms_of_service._session - assert session1 != session2 - session1 = client1.transport.retrieve_latest_terms_of_service._session - session2 = client2.transport.retrieve_latest_terms_of_service._session - assert session1 != session2 - session1 = client1.transport.accept_terms_of_service._session - session2 = client2.transport.accept_terms_of_service._session - assert session1 != session2 -def test_terms_of_service_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TermsOfServiceServiceGrpcTransport( - 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_terms_of_service_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.TermsOfServiceServiceGrpcAsyncIOTransport( - 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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) -def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) -def test_terms_of_service_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = TermsOfServiceServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = TermsOfServiceServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_account_path(path) - assert expected == actual - -def test_terms_of_service_path(): - version = "whelk" - expected = "termsOfService/{version}".format(version=version, ) - actual = TermsOfServiceServiceClient.terms_of_service_path(version) - assert expected == actual - - -def test_parse_terms_of_service_path(): - expected = { - "version": "octopus", - } - path = TermsOfServiceServiceClient.terms_of_service_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_terms_of_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TermsOfServiceServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = TermsOfServiceServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = TermsOfServiceServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = TermsOfServiceServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TermsOfServiceServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = TermsOfServiceServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = TermsOfServiceServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = TermsOfServiceServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = TermsOfServiceServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = TermsOfServiceServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.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.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: - client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = TermsOfServiceServiceClient.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 = TermsOfServiceServiceClient( - 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 = TermsOfServiceServiceAsyncClient( - 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 = TermsOfServiceServiceClient( - 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 = TermsOfServiceServiceClient( - 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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport), -]) -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-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py b/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py deleted file mode 100644 index 089adfcb70e6..000000000000 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/tests/unit/gapic/merchant_accounts_v1beta/test_user_service.py +++ /dev/null @@ -1,5226 +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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1beta.services.user_service import UserServiceAsyncClient -from google.shopping.merchant_accounts_v1beta.services.user_service import UserServiceClient -from google.shopping.merchant_accounts_v1beta.services.user_service import pagers -from google.shopping.merchant_accounts_v1beta.services.user_service import transports -from google.shopping.merchant_accounts_v1beta.types import accessright -from google.shopping.merchant_accounts_v1beta.types import user -from google.shopping.merchant_accounts_v1beta.types import user as gsma_user -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 UserServiceClient._get_default_mtls_endpoint(None) is None - assert UserServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert UserServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert UserServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert UserServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - UserServiceClient._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 UserServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert UserServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert UserServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - UserServiceClient._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 UserServiceClient._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 UserServiceClient._get_client_cert_source(None, False) is None - assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert UserServiceClient._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 UserServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = UserServiceClient._DEFAULT_UNIVERSE - default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert UserServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == UserServiceClient.DEFAULT_MTLS_ENDPOINT - assert UserServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert UserServiceClient._get_api_endpoint(None, None, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT - assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT - assert UserServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert UserServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - UserServiceClient._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 UserServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert UserServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert UserServiceClient._get_universe_domain(None, None) == UserServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - UserServiceClient._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 = UserServiceClient(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 = UserServiceClient(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", [ - (UserServiceClient, "grpc"), - (UserServiceAsyncClient, "grpc_asyncio"), - (UserServiceClient, "rest"), -]) -def test_user_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.UserServiceGrpcTransport, "grpc"), - (transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.UserServiceRestTransport, "rest"), -]) -def test_user_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", [ - (UserServiceClient, "grpc"), - (UserServiceAsyncClient, "grpc_asyncio"), - (UserServiceClient, "rest"), -]) -def test_user_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_user_service_client_get_transport_class(): - transport = UserServiceClient.get_transport_class() - available_transports = [ - transports.UserServiceGrpcTransport, - transports.UserServiceRestTransport, - ] - assert transport in available_transports - - transport = UserServiceClient.get_transport_class("grpc") - assert transport == transports.UserServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserServiceClient, transports.UserServiceRestTransport, "rest"), -]) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) -def test_user_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(UserServiceClient, '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(UserServiceClient, '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", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "true"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "false"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (UserServiceClient, transports.UserServiceRestTransport, "rest", "true"), - (UserServiceClient, transports.UserServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_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", [ - UserServiceClient, UserServiceAsyncClient -]) -@mock.patch.object(UserServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceAsyncClient)) -def test_user_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", [ - UserServiceClient, UserServiceAsyncClient -]) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) -def test_user_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = UserServiceClient._DEFAULT_UNIVERSE - default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = UserServiceClient._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", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserServiceClient, transports.UserServiceRestTransport, "rest"), -]) -def test_user_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", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (UserServiceClient, transports.UserServiceRestTransport, "rest", None), -]) -def test_user_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_user_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1beta.services.user_service.transports.UserServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserServiceClient( - 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", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_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", [ - user.GetUserRequest, - dict, -]) -def test_get_user(request_type, transport: str = 'grpc'): - client = UserServiceClient( - 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.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - ) - response = client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = user.GetUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, user.User) - assert response.name == 'name_value' - assert response.state == user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -def test_get_user_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 = UserServiceClient( - 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 = user.GetUserRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user.GetUserRequest( - name='name_value', - ) - -def test_get_user_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 = UserServiceClient( - 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.get_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_user] = mock_rpc - request = {} - client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user(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_get_user_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 = UserServiceAsyncClient( - 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.get_user in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_user] = mock_rpc - - request = {} - await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_user(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_get_user_async(transport: str = 'grpc_asyncio', request_type=user.GetUserRequest): - client = UserServiceAsyncClient( - 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.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) - response = await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = user.GetUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, user.User) - assert response.name == 'name_value' - assert response.state == user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -@pytest.mark.asyncio -async def test_get_user_async_from_dict(): - await test_get_user_async(request_type=dict) - -def test_get_user_field_headers(): - client = UserServiceClient( - 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 = user.GetUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value = user.User() - client.get_user(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_get_user_field_headers_async(): - client = UserServiceAsyncClient( - 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 = user.GetUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) - await client.get_user(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_get_user_flattened(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user.User() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_user( - 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_get_user_flattened_error(): - client = UserServiceClient( - 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.get_user( - user.GetUserRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_user_flattened_async(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user.User() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_user( - 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_get_user_flattened_error_async(): - client = UserServiceAsyncClient( - 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.get_user( - user.GetUserRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gsma_user.CreateUserRequest, - dict, -]) -def test_create_user(request_type, transport: str = 'grpc'): - client = UserServiceClient( - 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.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - ) - response = client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gsma_user.CreateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' - assert response.state == gsma_user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -def test_create_user_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 = UserServiceClient( - 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 = gsma_user.CreateUserRequest( - parent='parent_value', - user_id='user_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gsma_user.CreateUserRequest( - parent='parent_value', - user_id='user_id_value', - ) - -def test_create_user_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 = UserServiceClient( - 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.create_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_user] = mock_rpc - request = {} - client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user(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_create_user_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 = UserServiceAsyncClient( - 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.create_user in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_user] = mock_rpc - - request = {} - await client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_user(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_create_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.CreateUserRequest): - client = UserServiceAsyncClient( - 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.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) - response = await client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gsma_user.CreateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' - assert response.state == gsma_user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -@pytest.mark.asyncio -async def test_create_user_async_from_dict(): - await test_create_user_async(request_type=dict) - -def test_create_user_field_headers(): - client = UserServiceClient( - 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 = gsma_user.CreateUserRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value = gsma_user.User() - client.create_user(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_create_user_field_headers_async(): - client = UserServiceAsyncClient( - 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 = gsma_user.CreateUserRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) - await client.create_user(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_create_user_flattened(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_user.User() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_user( - parent='parent_value', - user=gsma_user.User(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user - mock_val = gsma_user.User(name='name_value') - assert arg == mock_val - - -def test_create_user_flattened_error(): - client = UserServiceClient( - 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.create_user( - gsma_user.CreateUserRequest(), - parent='parent_value', - user=gsma_user.User(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_user_flattened_async(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_user.User() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_user( - parent='parent_value', - user=gsma_user.User(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].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].user - mock_val = gsma_user.User(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_user_flattened_error_async(): - client = UserServiceAsyncClient( - 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.create_user( - gsma_user.CreateUserRequest(), - parent='parent_value', - user=gsma_user.User(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - user.DeleteUserRequest, - dict, -]) -def test_delete_user(request_type, transport: str = 'grpc'): - client = UserServiceClient( - 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_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = user.DeleteUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_user_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 = UserServiceClient( - 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 = user.DeleteUserRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user.DeleteUserRequest( - name='name_value', - ) - -def test_delete_user_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 = UserServiceClient( - 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_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_user] = mock_rpc - request = {} - client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user(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_user_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 = UserServiceAsyncClient( - 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_user 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_user] = mock_rpc - - request = {} - await client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_user(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_user_async(transport: str = 'grpc_asyncio', request_type=user.DeleteUserRequest): - client = UserServiceAsyncClient( - 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_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = user.DeleteUserRequest() - 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_user_async_from_dict(): - await test_delete_user_async(request_type=dict) - -def test_delete_user_field_headers(): - client = UserServiceClient( - 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 = user.DeleteUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value = None - client.delete_user(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_user_field_headers_async(): - client = UserServiceAsyncClient( - 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 = user.DeleteUserRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(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_user_flattened(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__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_user( - 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_user_flattened_error(): - client = UserServiceClient( - 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_user( - user.DeleteUserRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_user_flattened_async(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__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_user( - 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_user_flattened_error_async(): - client = UserServiceAsyncClient( - 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_user( - user.DeleteUserRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - gsma_user.UpdateUserRequest, - dict, -]) -def test_update_user(request_type, transport: str = 'grpc'): - client = UserServiceClient( - 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.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - ) - response = client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = gsma_user.UpdateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' - assert response.state == gsma_user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -def test_update_user_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 = UserServiceClient( - 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 = gsma_user.UpdateUserRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_user(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == gsma_user.UpdateUserRequest( - ) - -def test_update_user_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 = UserServiceClient( - 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.update_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_user] = mock_rpc - request = {} - client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user(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_update_user_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 = UserServiceAsyncClient( - 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.update_user in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_user] = mock_rpc - - request = {} - await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_user(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_update_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.UpdateUserRequest): - client = UserServiceAsyncClient( - 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.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) - response = await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = gsma_user.UpdateUserRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' - assert response.state == gsma_user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -@pytest.mark.asyncio -async def test_update_user_async_from_dict(): - await test_update_user_async(request_type=dict) - -def test_update_user_field_headers(): - client = UserServiceClient( - 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 = gsma_user.UpdateUserRequest() - - request.user.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value = gsma_user.User() - client.update_user(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', - 'user.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_user_field_headers_async(): - client = UserServiceAsyncClient( - 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 = gsma_user.UpdateUserRequest() - - request.user.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) - await client.update_user(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', - 'user.name=name_value', - ) in kw['metadata'] - - -def test_update_user_flattened(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_user.User() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_user( - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].user - mock_val = gsma_user.User(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_user_flattened_error(): - client = UserServiceClient( - 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.update_user( - gsma_user.UpdateUserRequest(), - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_user_flattened_async(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gsma_user.User() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_user( - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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].user - mock_val = gsma_user.User(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_user_flattened_error_async(): - client = UserServiceAsyncClient( - 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.update_user( - gsma_user.UpdateUserRequest(), - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - user.ListUsersRequest, - dict, -]) -def test_list_users(request_type, transport: str = 'grpc'): - client = UserServiceClient( - 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_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user.ListUsersResponse( - next_page_token='next_page_token_value', - ) - response = client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = user.ListUsersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_users_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 = UserServiceClient( - 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 = user.ListUsersRequest( - 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_users), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_users(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user.ListUsersRequest( - parent='parent_value', - page_token='page_token_value', - ) - -def test_list_users_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 = UserServiceClient( - 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_users in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_users] = mock_rpc - request = {} - client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_users(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_users_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 = UserServiceAsyncClient( - 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_users 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_users] = mock_rpc - - request = {} - await client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_users(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_users_async(transport: str = 'grpc_asyncio', request_type=user.ListUsersRequest): - client = UserServiceAsyncClient( - 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_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = user.ListUsersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_users_async_from_dict(): - await test_list_users_async(request_type=dict) - -def test_list_users_field_headers(): - client = UserServiceClient( - 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 = user.ListUsersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - call.return_value = user.ListUsersResponse() - client.list_users(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_users_field_headers_async(): - client = UserServiceAsyncClient( - 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 = user.ListUsersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) - await client.list_users(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_users_flattened(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user.ListUsersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_users( - 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_users_flattened_error(): - client = UserServiceClient( - 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_users( - user.ListUsersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_users_flattened_async(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user.ListUsersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_users( - 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_users_flattened_error_async(): - client = UserServiceAsyncClient( - 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_users( - user.ListUsersRequest(), - parent='parent_value', - ) - - -def test_list_users_pager(transport_name: str = "grpc"): - client = UserServiceClient( - 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_users), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - user.User(), - ], - next_page_token='abc', - ), - user.ListUsersResponse( - users=[], - next_page_token='def', - ), - user.ListUsersResponse( - users=[ - user.User(), - ], - next_page_token='ghi', - ), - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_users(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, user.User) - for i in results) -def test_list_users_pages(transport_name: str = "grpc"): - client = UserServiceClient( - 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_users), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - user.User(), - ], - next_page_token='abc', - ), - user.ListUsersResponse( - users=[], - next_page_token='def', - ), - user.ListUsersResponse( - users=[ - user.User(), - ], - next_page_token='ghi', - ), - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - ], - ), - RuntimeError, - ) - pages = list(client.list_users(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_users_async_pager(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - user.User(), - ], - next_page_token='abc', - ), - user.ListUsersResponse( - users=[], - next_page_token='def', - ), - user.ListUsersResponse( - users=[ - user.User(), - ], - next_page_token='ghi', - ), - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_users(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, user.User) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_users_async_pages(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - user.User(), - ], - next_page_token='abc', - ), - user.ListUsersResponse( - users=[], - next_page_token='def', - ), - user.ListUsersResponse( - users=[ - user.User(), - ], - next_page_token='ghi', - ), - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - ], - ), - 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_users(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_user_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 = UserServiceClient( - 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.get_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_user] = mock_rpc - - request = {} - client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_user(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_get_user_rest_required_fields(request_type=user.GetUserRequest): - transport_class = transports.UserServiceRestTransport - - 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()).get_user._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_user._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 = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = user.User() - # 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 = user.User.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.get_user(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_user_rest_flattened(): - client = UserServiceClient( - 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 = user.User() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/users/sample2'} - - # 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 - # Convert return value to protobuf type - return_value = user.User.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.get_user(**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/accounts/v1beta/{name=accounts/*/users/*}" % client.transport._host, args[1]) - - -def test_get_user_rest_flattened_error(transport: str = 'rest'): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_user( - user.GetUserRequest(), - name='name_value', - ) - - -def test_create_user_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 = UserServiceClient( - 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.create_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_user] = mock_rpc - - request = {} - client.create_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_user(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_create_user_rest_required_fields(request_type=gsma_user.CreateUserRequest): - transport_class = transports.UserServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["user_id"] = "" - 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 - assert "userId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "userId" in jsonified_request - assert jsonified_request["userId"] == request_init["user_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["userId"] = 'user_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("user_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "userId" in jsonified_request - assert jsonified_request["userId"] == 'user_id_value' - - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gsma_user.User() - # 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 = gsma_user.User.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.create_user(request) - - expected_params = [ - ( - "userId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(("userId", )) & set(("parent", "userId", "user", ))) - - -def test_create_user_rest_flattened(): - client = UserServiceClient( - 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 = gsma_user.User() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - user=gsma_user.User(name='name_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 = gsma_user.User.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.create_user(**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/accounts/v1beta/{parent=accounts/*}/users" % client.transport._host, args[1]) - - -def test_create_user_rest_flattened_error(transport: str = 'rest'): - client = UserServiceClient( - 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.create_user( - gsma_user.CreateUserRequest(), - parent='parent_value', - user=gsma_user.User(name='name_value'), - ) - - -def test_delete_user_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 = UserServiceClient( - 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_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_user] = mock_rpc - - request = {} - client.delete_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_user(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_user_rest_required_fields(request_type=user.DeleteUserRequest): - transport_class = transports.UserServiceRestTransport - - 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_user._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_user._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 = UserServiceClient( - 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_user(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_delete_user_rest_flattened(): - client = UserServiceClient( - 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/users/sample2'} - - # 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_user(**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/accounts/v1beta/{name=accounts/*/users/*}" % client.transport._host, args[1]) - - -def test_delete_user_rest_flattened_error(transport: str = 'rest'): - client = UserServiceClient( - 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_user( - user.DeleteUserRequest(), - name='name_value', - ) - - -def test_update_user_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 = UserServiceClient( - 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.update_user in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_user] = mock_rpc - - request = {} - client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_user(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_update_user_rest_required_fields(request_type=gsma_user.UpdateUserRequest): - transport_class = transports.UserServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gsma_user.User() - # 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': "patch", - '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 = gsma_user.User.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.update_user(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("user", "updateMask", ))) - - -def test_update_user_rest_flattened(): - client = UserServiceClient( - 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 = gsma_user.User() - - # get arguments that satisfy an http rule for this method - sample_request = {'user': {'name': 'accounts/sample1/users/sample2'}} - - # get truthy value for each flattened field - mock_args = dict( - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_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 = gsma_user.User.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.update_user(**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/accounts/v1beta/{user.name=accounts/*/users/*}" % client.transport._host, args[1]) - - -def test_update_user_rest_flattened_error(transport: str = 'rest'): - client = UserServiceClient( - 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.update_user( - gsma_user.UpdateUserRequest(), - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_list_users_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 = UserServiceClient( - 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_users in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_users] = mock_rpc - - request = {} - client.list_users(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_users(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_users_rest_required_fields(request_type=user.ListUsersRequest): - transport_class = transports.UserServiceRestTransport - - 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_users._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_users._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 = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = user.ListUsersResponse() - # 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 = user.ListUsersResponse.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_users(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_users_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_users._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_users_rest_flattened(): - client = UserServiceClient( - 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 = user.ListUsersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} - - # 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 = user.ListUsersResponse.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_users(**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/accounts/v1beta/{parent=accounts/*}/users" % client.transport._host, args[1]) - - -def test_list_users_rest_flattened_error(transport: str = 'rest'): - client = UserServiceClient( - 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_users( - user.ListUsersRequest(), - parent='parent_value', - ) - - -def test_list_users_rest_pager(transport: str = 'rest'): - client = UserServiceClient( - 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 = ( - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - user.User(), - ], - next_page_token='abc', - ), - user.ListUsersResponse( - users=[], - next_page_token='def', - ), - user.ListUsersResponse( - users=[ - user.User(), - ], - next_page_token='ghi', - ), - user.ListUsersResponse( - users=[ - user.User(), - user.User(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(user.ListUsersResponse.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'} - - pager = client.list_users(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, user.User) - for i in results) - - pages = list(client.list_users(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserServiceClient( - 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 = UserServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserServiceGrpcTransport, - transports.UserServiceGrpcAsyncIOTransport, - transports.UserServiceRestTransport, -]) -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 = UserServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = UserServiceClient( - 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_get_user_empty_call_grpc(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value = user.User() - client.get_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.GetUserRequest() - - 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_create_user_empty_call_grpc(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value = gsma_user.User() - client.create_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_user.CreateUserRequest() - - 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_user_empty_call_grpc(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - call.return_value = None - client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.DeleteUserRequest() - - 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_update_user_empty_call_grpc(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value = gsma_user.User() - client.update_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_user.UpdateUserRequest() - - 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_list_users_empty_call_grpc(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - call.return_value = user.ListUsersResponse() - client.list_users(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.ListUsersRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = UserServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = UserServiceAsyncClient( - 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_get_user_empty_call_grpc_asyncio(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) - await client.get_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.GetUserRequest() - - 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_create_user_empty_call_grpc_asyncio(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) - await client.create_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_user.CreateUserRequest() - - 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_user_empty_call_grpc_asyncio(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.DeleteUserRequest() - - 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_update_user_empty_call_grpc_asyncio(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) - await client.update_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_user.UpdateUserRequest() - - 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_list_users_empty_call_grpc_asyncio(): - client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( - next_page_token='next_page_token_value', - )) - await client.list_users(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.ListUsersRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = UserServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_get_user_rest_bad_request(request_type=user.GetUserRequest): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/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.get_user(request) - - -@pytest.mark.parametrize("request_type", [ - user.GetUserRequest, - dict, -]) -def test_get_user_rest_call_success(request_type): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/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 = user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - ) - - # 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 = user.User.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.get_user(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user.User) - assert response.name == 'name_value' - assert response.state == user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_user_rest_interceptors(null_interceptor): - transport = transports.UserServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) - client = UserServiceClient(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.UserServiceRestInterceptor, "post_get_user") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_get_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_get_user") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = user.GetUserRequest.pb(user.GetUserRequest()) - 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 = user.User.to_json(user.User()) - req.return_value.content = return_value - - request = user.GetUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user.User() - post_with_metadata.return_value = user.User(), metadata - - client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_user_rest_bad_request(request_type=gsma_user.CreateUserRequest): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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.create_user(request) - - -@pytest.mark.parametrize("request_type", [ - gsma_user.CreateUserRequest, - dict, -]) -def test_create_user_rest_call_success(request_type): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["user"] = {'name': 'name_value', 'state': 1, 'access_rights': [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 = gsma_user.CreateUserRequest.meta.fields["user"] - - 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["user"].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["user"][field])): - del request_init["user"][field][i][subfield] - else: - del request_init["user"][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 = gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - ) - - # 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 = gsma_user.User.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.create_user(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' - assert response.state == gsma_user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_user_rest_interceptors(null_interceptor): - transport = transports.UserServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) - client = UserServiceClient(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.UserServiceRestInterceptor, "post_create_user") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_create_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_create_user") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gsma_user.CreateUserRequest.pb(gsma_user.CreateUserRequest()) - 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 = gsma_user.User.to_json(gsma_user.User()) - req.return_value.content = return_value - - request = gsma_user.CreateUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gsma_user.User() - post_with_metadata.return_value = gsma_user.User(), metadata - - client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_user_rest_bad_request(request_type=user.DeleteUserRequest): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/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.delete_user(request) - - -@pytest.mark.parametrize("request_type", [ - user.DeleteUserRequest, - dict, -]) -def test_delete_user_rest_call_success(request_type): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/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 = 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_user(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_user_rest_interceptors(null_interceptor): - transport = transports.UserServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) - client = UserServiceClient(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.UserServiceRestInterceptor, "pre_delete_user") as pre: - pre.assert_not_called() - pb_message = user.DeleteUserRequest.pb(user.DeleteUserRequest()) - 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 = user.DeleteUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_update_user_rest_bad_request(request_type=gsma_user.UpdateUserRequest): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'user': {'name': 'accounts/sample1/users/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.update_user(request) - - -@pytest.mark.parametrize("request_type", [ - gsma_user.UpdateUserRequest, - dict, -]) -def test_update_user_rest_call_success(request_type): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'user': {'name': 'accounts/sample1/users/sample2'}} - request_init["user"] = {'name': 'accounts/sample1/users/sample2', 'state': 1, 'access_rights': [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 = gsma_user.UpdateUserRequest.meta.fields["user"] - - 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["user"].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["user"][field])): - del request_init["user"][field][i][subfield] - else: - del request_init["user"][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 = gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - ) - - # 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 = gsma_user.User.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.update_user(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' - assert response.state == gsma_user.User.State.PENDING - assert response.access_rights == [accessright.AccessRight.STANDARD] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_user_rest_interceptors(null_interceptor): - transport = transports.UserServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) - client = UserServiceClient(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.UserServiceRestInterceptor, "post_update_user") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_update_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_update_user") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = gsma_user.UpdateUserRequest.pb(gsma_user.UpdateUserRequest()) - 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 = gsma_user.User.to_json(gsma_user.User()) - req.return_value.content = return_value - - request = gsma_user.UpdateUserRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gsma_user.User() - post_with_metadata.return_value = gsma_user.User(), metadata - - client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_users_rest_bad_request(request_type=user.ListUsersRequest): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - 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_users(request) - - -@pytest.mark.parametrize("request_type", [ - user.ListUsersRequest, - dict, -]) -def test_list_users_rest_call_success(request_type): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = user.ListUsersResponse( - 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 = user.ListUsersResponse.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_users(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_users_rest_interceptors(null_interceptor): - transport = transports.UserServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) - client = UserServiceClient(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.UserServiceRestInterceptor, "post_list_users") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_list_users_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_list_users") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = user.ListUsersRequest.pb(user.ListUsersRequest()) - 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 = user.ListUsersResponse.to_json(user.ListUsersResponse()) - req.return_value.content = return_value - - request = user.ListUsersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user.ListUsersResponse() - post_with_metadata.return_value = user.ListUsersResponse(), metadata - - client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - -def test_initialize_client_w_rest(): - client = UserServiceClient( - 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_get_user_empty_call_rest(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - client.get_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.GetUserRequest() - - 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_create_user_empty_call_rest(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - client.create_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_user.CreateUserRequest() - - 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_user_empty_call_rest(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: - client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.DeleteUserRequest() - - 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_update_user_empty_call_rest(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - client.update_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = gsma_user.UpdateUserRequest() - - 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_list_users_empty_call_rest(): - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: - client.list_users(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = user.ListUsersRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserServiceGrpcTransport, - ) - -def test_user_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1beta.services.user_service.transports.UserServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_user', - 'create_user', - 'delete_user', - 'update_user', - 'list_users', - ) - 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_user_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_accounts_v1beta.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserServiceTransport( - 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_user_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_accounts_v1beta.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserServiceTransport() - adc.assert_called_once() - - -def test_user_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) - UserServiceClient() - 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.UserServiceGrpcTransport, - transports.UserServiceGrpcAsyncIOTransport, - ], -) -def test_user_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.UserServiceGrpcTransport, - transports.UserServiceGrpcAsyncIOTransport, - transports.UserServiceRestTransport, - ], -) -def test_user_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.UserServiceGrpcTransport, grpc_helpers), - (transports.UserServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) -def test_user_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_user_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.UserServiceRestTransport ( - 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_user_service_host_no_port(transport_name): - client = UserServiceClient( - 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_user_service_host_with_port(transport_name): - client = UserServiceClient( - 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_user_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = UserServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = UserServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_user._session - session2 = client2.transport.get_user._session - assert session1 != session2 - session1 = client1.transport.create_user._session - session2 = client2.transport.create_user._session - assert session1 != session2 - session1 = client1.transport.delete_user._session - session2 = client2.transport.delete_user._session - assert session1 != session2 - session1 = client1.transport.update_user._session - session2 = client2.transport.update_user._session - assert session1 != session2 - session1 = client1.transport.list_users._session - session2 = client2.transport.list_users._session - assert session1 != session2 -def test_user_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserServiceGrpcTransport( - 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_user_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserServiceGrpcAsyncIOTransport( - 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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) -def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) -def test_user_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_account_path(): - account = "squid" - expected = "accounts/{account}".format(account=account, ) - actual = UserServiceClient.account_path(account) - assert expected == actual - - -def test_parse_account_path(): - expected = { - "account": "clam", - } - path = UserServiceClient.account_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.parse_account_path(path) - assert expected == actual - -def test_user_path(): - account = "whelk" - email = "octopus" - expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) - actual = UserServiceClient.user_path(account, email) - assert expected == actual - - -def test_parse_user_path(): - expected = { - "account": "oyster", - "email": "nudibranch", - } - path = UserServiceClient.user_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.parse_user_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = UserServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = UserServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = UserServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = UserServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = UserServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.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 = UserServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = UserServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserServiceClient.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.UserServiceTransport, '_prep_wrapped_messages') as prep: - client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserServiceClient.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 = UserServiceClient( - 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 = UserServiceAsyncClient( - 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 = UserServiceClient( - 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 = UserServiceClient( - 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", [ - (UserServiceClient, transports.UserServiceGrpcTransport), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport), -]) -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-accounts/docs/index.rst b/packages/google-shopping-merchant-accounts/docs/index.rst index 12d31a16b828..c36b168fe4cf 100644 --- a/packages/google-shopping-merchant-accounts/docs/index.rst +++ b/packages/google-shopping-merchant-accounts/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Merchant API. +By default, you will get version ``merchant_accounts_v1beta``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference merchant_accounts_v1beta/services_ merchant_accounts_v1beta/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + merchant_accounts_v1/services_ + merchant_accounts_v1/types_ + Changelog --------- diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_issue_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/account_issue_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_issue_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/account_issue_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_relationships_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/account_relationships_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_relationships_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/account_relationships_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_services_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/account_services_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/account_services_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/account_services_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/accounts_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/accounts_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/accounts_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/accounts_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/autofeed_settings_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/autofeed_settings_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/autofeed_settings_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/autofeed_settings_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/automatic_improvements_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/automatic_improvements_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/automatic_improvements_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/automatic_improvements_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_identity_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/business_identity_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_identity_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/business_identity_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_info_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/business_info_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/business_info_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/business_info_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/checkout_settings_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/checkout_settings_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/checkout_settings_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/checkout_settings_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/developer_registration_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/developer_registration_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/developer_registration_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/developer_registration_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/email_preferences_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/email_preferences_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/email_preferences_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/email_preferences_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/gbp_accounts_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/gbp_accounts_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/gbp_accounts_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/gbp_accounts_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/homepage_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/homepage_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/homepage_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/homepage_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/lfp_providers_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/lfp_providers_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/lfp_providers_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/lfp_providers_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/omnichannel_settings_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/omnichannel_settings_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/omnichannel_settings_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/omnichannel_settings_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/online_return_policy_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/online_return_policy_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/online_return_policy_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/online_return_policy_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/programs_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/programs_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/programs_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/programs_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/regions_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/regions_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/regions_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/regions_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/services_.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/services_.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/services_.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/services_.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/shipping_settings_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/shipping_settings_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/shipping_settings_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/shipping_settings_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/terms_of_service_agreement_state_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/terms_of_service_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/terms_of_service_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/terms_of_service_service.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/types_.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/types_.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/types_.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/types_.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/user_service.rst b/packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/user_service.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/docs/merchant_accounts_v1/user_service.rst rename to packages/google-shopping-merchant-accounts/docs/merchant_accounts_v1/user_service.rst diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts/gapic_version.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts/gapic_version.py index 694729f5d88b..20a9cd975b02 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts/gapic_version.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/__init__.py new file mode 100644 index 000000000000..02beaa647d4b --- /dev/null +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/__init__.py @@ -0,0 +1,482 @@ +# -*- 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_accounts_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.account_issue_service import ( + AccountIssueServiceAsyncClient, + AccountIssueServiceClient, +) +from .services.account_relationships_service import ( + AccountRelationshipsServiceAsyncClient, + AccountRelationshipsServiceClient, +) +from .services.account_services_service import ( + AccountServicesServiceAsyncClient, + AccountServicesServiceClient, +) +from .services.accounts_service import AccountsServiceAsyncClient, AccountsServiceClient +from .services.autofeed_settings_service import ( + AutofeedSettingsServiceAsyncClient, + AutofeedSettingsServiceClient, +) +from .services.automatic_improvements_service import ( + AutomaticImprovementsServiceAsyncClient, + AutomaticImprovementsServiceClient, +) +from .services.business_identity_service import ( + BusinessIdentityServiceAsyncClient, + BusinessIdentityServiceClient, +) +from .services.business_info_service import ( + BusinessInfoServiceAsyncClient, + BusinessInfoServiceClient, +) +from .services.checkout_settings_service import ( + CheckoutSettingsServiceAsyncClient, + CheckoutSettingsServiceClient, +) +from .services.developer_registration_service import ( + DeveloperRegistrationServiceAsyncClient, + DeveloperRegistrationServiceClient, +) +from .services.email_preferences_service import ( + EmailPreferencesServiceAsyncClient, + EmailPreferencesServiceClient, +) +from .services.gbp_accounts_service import ( + GbpAccountsServiceAsyncClient, + GbpAccountsServiceClient, +) +from .services.homepage_service import HomepageServiceAsyncClient, HomepageServiceClient +from .services.lfp_providers_service import ( + LfpProvidersServiceAsyncClient, + LfpProvidersServiceClient, +) +from .services.omnichannel_settings_service import ( + OmnichannelSettingsServiceAsyncClient, + OmnichannelSettingsServiceClient, +) +from .services.online_return_policy_service import ( + OnlineReturnPolicyServiceAsyncClient, + OnlineReturnPolicyServiceClient, +) +from .services.programs_service import ProgramsServiceAsyncClient, ProgramsServiceClient +from .services.regions_service import RegionsServiceAsyncClient, RegionsServiceClient +from .services.shipping_settings_service import ( + ShippingSettingsServiceAsyncClient, + ShippingSettingsServiceClient, +) +from .services.terms_of_service_agreement_state_service import ( + TermsOfServiceAgreementStateServiceAsyncClient, + TermsOfServiceAgreementStateServiceClient, +) +from .services.terms_of_service_service import ( + TermsOfServiceServiceAsyncClient, + TermsOfServiceServiceClient, +) +from .services.user_service import UserServiceAsyncClient, UserServiceClient +from .types.accessright import AccessRight +from .types.accountissue import ( + AccountIssue, + ListAccountIssuesRequest, + ListAccountIssuesResponse, +) +from .types.accountrelationships import ( + AccountRelationship, + GetAccountRelationshipRequest, + ListAccountRelationshipsRequest, + ListAccountRelationshipsResponse, + UpdateAccountRelationshipRequest, +) +from .types.accounts import ( + Account, + CreateAndConfigureAccountRequest, + DeleteAccountRequest, + GetAccountRequest, + ListAccountsRequest, + ListAccountsResponse, + ListSubAccountsRequest, + ListSubAccountsResponse, + UpdateAccountRequest, +) +from .types.accountservices import ( + AccountAggregation, + AccountManagement, + AccountService, + ApproveAccountServiceRequest, + CampaignsManagement, + GetAccountServiceRequest, + Handshake, + ListAccountServicesRequest, + ListAccountServicesResponse, + LocalListingManagement, + ProductsManagement, + ProposeAccountServiceRequest, + RejectAccountServiceRequest, +) +from .types.autofeedsettings import ( + AutofeedSettings, + GetAutofeedSettingsRequest, + UpdateAutofeedSettingsRequest, +) +from .types.automaticimprovements import ( + AutomaticImageImprovements, + AutomaticImprovements, + AutomaticItemUpdates, + AutomaticShippingImprovements, + GetAutomaticImprovementsRequest, + UpdateAutomaticImprovementsRequest, +) +from .types.businessidentity import ( + BusinessIdentity, + GetBusinessIdentityRequest, + UpdateBusinessIdentityRequest, +) +from .types.businessinfo import ( + BusinessInfo, + GetBusinessInfoRequest, + UpdateBusinessInfoRequest, +) +from .types.checkoutsettings import ( + CheckoutSettings, + CreateCheckoutSettingsRequest, + DeleteCheckoutSettingsRequest, + GetCheckoutSettingsRequest, + UpdateCheckoutSettingsRequest, + UriSettings, +) +from .types.customerservice import CustomerService +from .types.developerregistration import ( + DeveloperRegistration, + GetDeveloperRegistrationRequest, + RegisterGcpRequest, + UnregisterGcpRequest, +) +from .types.emailpreferences import ( + EmailPreferences, + GetEmailPreferencesRequest, + UpdateEmailPreferencesRequest, +) +from .types.gbpaccounts import ( + GbpAccount, + LinkGbpAccountRequest, + LinkGbpAccountResponse, + ListGbpAccountsRequest, + ListGbpAccountsResponse, +) +from .types.homepage import ( + ClaimHomepageRequest, + GetHomepageRequest, + Homepage, + UnclaimHomepageRequest, + UpdateHomepageRequest, +) +from .types.lfpproviders import ( + FindLfpProvidersRequest, + FindLfpProvidersResponse, + LfpProvider, + LinkLfpProviderRequest, + LinkLfpProviderResponse, +) +from .types.omnichannelsettings import ( + About, + CreateOmnichannelSettingRequest, + GetOmnichannelSettingRequest, + InStock, + InventoryVerification, + LfpLink, + ListOmnichannelSettingsRequest, + ListOmnichannelSettingsResponse, + OmnichannelSetting, + OnDisplayToOrder, + Pickup, + RequestInventoryVerificationRequest, + RequestInventoryVerificationResponse, + ReviewState, + UpdateOmnichannelSettingRequest, +) +from .types.online_return_policy import ( + CreateOnlineReturnPolicyRequest, + DeleteOnlineReturnPolicyRequest, + GetOnlineReturnPolicyRequest, + ListOnlineReturnPoliciesRequest, + ListOnlineReturnPoliciesResponse, + OnlineReturnPolicy, +) +from .types.phoneverificationstate import PhoneVerificationState +from .types.programs import ( + DisableProgramRequest, + EnableProgramRequest, + GetProgramRequest, + ListProgramsRequest, + ListProgramsResponse, + Program, +) +from .types.regions import ( + CreateRegionRequest, + DeleteRegionRequest, + GetRegionRequest, + ListRegionsRequest, + ListRegionsResponse, + Region, + UpdateRegionRequest, +) +from .types.shippingsettings import ( + Address, + BusinessDayConfig, + CarrierRate, + CutoffTime, + DeliveryTime, + Distance, + GetShippingSettingsRequest, + Headers, + InsertShippingSettingsRequest, + LocationIdSet, + MinimumOrderValueTable, + RateGroup, + Row, + Service, + ShippingSettings, + Table, + TransitTable, + Value, + Warehouse, + WarehouseBasedDeliveryTime, + WarehouseCutoffTime, +) +from .types.termsofservice import ( + AcceptTermsOfServiceRequest, + AcceptTermsOfServiceResponse, + GetTermsOfServiceRequest, + RetrieveLatestTermsOfServiceRequest, + TermsOfService, +) +from .types.termsofserviceagreementstate import ( + Accepted, + GetTermsOfServiceAgreementStateRequest, + Required, + RetrieveForApplicationTermsOfServiceAgreementStateRequest, + TermsOfServiceAgreementState, +) +from .types.termsofservicekind import TermsOfServiceKind +from .types.user import ( + CreateUserRequest, + DeleteUserRequest, + GetUserRequest, + ListUsersRequest, + ListUsersResponse, + UpdateUserRequest, + User, +) + +__all__ = ( + "AccountIssueServiceAsyncClient", + "AccountRelationshipsServiceAsyncClient", + "AccountServicesServiceAsyncClient", + "AccountsServiceAsyncClient", + "AutofeedSettingsServiceAsyncClient", + "AutomaticImprovementsServiceAsyncClient", + "BusinessIdentityServiceAsyncClient", + "BusinessInfoServiceAsyncClient", + "CheckoutSettingsServiceAsyncClient", + "DeveloperRegistrationServiceAsyncClient", + "EmailPreferencesServiceAsyncClient", + "GbpAccountsServiceAsyncClient", + "HomepageServiceAsyncClient", + "LfpProvidersServiceAsyncClient", + "OmnichannelSettingsServiceAsyncClient", + "OnlineReturnPolicyServiceAsyncClient", + "ProgramsServiceAsyncClient", + "RegionsServiceAsyncClient", + "ShippingSettingsServiceAsyncClient", + "TermsOfServiceAgreementStateServiceAsyncClient", + "TermsOfServiceServiceAsyncClient", + "UserServiceAsyncClient", + "About", + "AcceptTermsOfServiceRequest", + "AcceptTermsOfServiceResponse", + "Accepted", + "AccessRight", + "Account", + "AccountAggregation", + "AccountIssue", + "AccountIssueServiceClient", + "AccountManagement", + "AccountRelationship", + "AccountRelationshipsServiceClient", + "AccountService", + "AccountServicesServiceClient", + "AccountsServiceClient", + "Address", + "ApproveAccountServiceRequest", + "AutofeedSettings", + "AutofeedSettingsServiceClient", + "AutomaticImageImprovements", + "AutomaticImprovements", + "AutomaticImprovementsServiceClient", + "AutomaticItemUpdates", + "AutomaticShippingImprovements", + "BusinessDayConfig", + "BusinessIdentity", + "BusinessIdentityServiceClient", + "BusinessInfo", + "BusinessInfoServiceClient", + "CampaignsManagement", + "CarrierRate", + "CheckoutSettings", + "CheckoutSettingsServiceClient", + "ClaimHomepageRequest", + "CreateAndConfigureAccountRequest", + "CreateCheckoutSettingsRequest", + "CreateOmnichannelSettingRequest", + "CreateOnlineReturnPolicyRequest", + "CreateRegionRequest", + "CreateUserRequest", + "CustomerService", + "CutoffTime", + "DeleteAccountRequest", + "DeleteCheckoutSettingsRequest", + "DeleteOnlineReturnPolicyRequest", + "DeleteRegionRequest", + "DeleteUserRequest", + "DeliveryTime", + "DeveloperRegistration", + "DeveloperRegistrationServiceClient", + "DisableProgramRequest", + "Distance", + "EmailPreferences", + "EmailPreferencesServiceClient", + "EnableProgramRequest", + "FindLfpProvidersRequest", + "FindLfpProvidersResponse", + "GbpAccount", + "GbpAccountsServiceClient", + "GetAccountRelationshipRequest", + "GetAccountRequest", + "GetAccountServiceRequest", + "GetAutofeedSettingsRequest", + "GetAutomaticImprovementsRequest", + "GetBusinessIdentityRequest", + "GetBusinessInfoRequest", + "GetCheckoutSettingsRequest", + "GetDeveloperRegistrationRequest", + "GetEmailPreferencesRequest", + "GetHomepageRequest", + "GetOmnichannelSettingRequest", + "GetOnlineReturnPolicyRequest", + "GetProgramRequest", + "GetRegionRequest", + "GetShippingSettingsRequest", + "GetTermsOfServiceAgreementStateRequest", + "GetTermsOfServiceRequest", + "GetUserRequest", + "Handshake", + "Headers", + "Homepage", + "HomepageServiceClient", + "InStock", + "InsertShippingSettingsRequest", + "InventoryVerification", + "LfpLink", + "LfpProvider", + "LfpProvidersServiceClient", + "LinkGbpAccountRequest", + "LinkGbpAccountResponse", + "LinkLfpProviderRequest", + "LinkLfpProviderResponse", + "ListAccountIssuesRequest", + "ListAccountIssuesResponse", + "ListAccountRelationshipsRequest", + "ListAccountRelationshipsResponse", + "ListAccountServicesRequest", + "ListAccountServicesResponse", + "ListAccountsRequest", + "ListAccountsResponse", + "ListGbpAccountsRequest", + "ListGbpAccountsResponse", + "ListOmnichannelSettingsRequest", + "ListOmnichannelSettingsResponse", + "ListOnlineReturnPoliciesRequest", + "ListOnlineReturnPoliciesResponse", + "ListProgramsRequest", + "ListProgramsResponse", + "ListRegionsRequest", + "ListRegionsResponse", + "ListSubAccountsRequest", + "ListSubAccountsResponse", + "ListUsersRequest", + "ListUsersResponse", + "LocalListingManagement", + "LocationIdSet", + "MinimumOrderValueTable", + "OmnichannelSetting", + "OmnichannelSettingsServiceClient", + "OnDisplayToOrder", + "OnlineReturnPolicy", + "OnlineReturnPolicyServiceClient", + "PhoneVerificationState", + "Pickup", + "ProductsManagement", + "Program", + "ProgramsServiceClient", + "ProposeAccountServiceRequest", + "RateGroup", + "Region", + "RegionsServiceClient", + "RegisterGcpRequest", + "RejectAccountServiceRequest", + "RequestInventoryVerificationRequest", + "RequestInventoryVerificationResponse", + "Required", + "RetrieveForApplicationTermsOfServiceAgreementStateRequest", + "RetrieveLatestTermsOfServiceRequest", + "ReviewState", + "Row", + "Service", + "ShippingSettings", + "ShippingSettingsServiceClient", + "Table", + "TermsOfService", + "TermsOfServiceAgreementState", + "TermsOfServiceAgreementStateServiceClient", + "TermsOfServiceKind", + "TermsOfServiceServiceClient", + "TransitTable", + "UnclaimHomepageRequest", + "UnregisterGcpRequest", + "UpdateAccountRelationshipRequest", + "UpdateAccountRequest", + "UpdateAutofeedSettingsRequest", + "UpdateAutomaticImprovementsRequest", + "UpdateBusinessIdentityRequest", + "UpdateBusinessInfoRequest", + "UpdateCheckoutSettingsRequest", + "UpdateEmailPreferencesRequest", + "UpdateHomepageRequest", + "UpdateOmnichannelSettingRequest", + "UpdateRegionRequest", + "UpdateUserRequest", + "UriSettings", + "User", + "UserServiceClient", + "Value", + "Warehouse", + "WarehouseBasedDeliveryTime", + "WarehouseCutoffTime", +) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_metadata.json b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/gapic_metadata.json similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/gapic_metadata.json rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/gapic_metadata.json diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/gapic_version.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/gapic_version.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/gapic_version.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/gapic_version.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/py.typed b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/py.typed similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts/py.typed rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/py.typed diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/__init__.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/__init__.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py index 1c1c6dd19914..3938a196361c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AccountIssueServiceClient from .async_client import AccountIssueServiceAsyncClient +from .client import AccountIssueServiceClient __all__ = ( - 'AccountIssueServiceClient', - 'AccountIssueServiceAsyncClient', + "AccountIssueServiceClient", + "AccountIssueServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py index 68442169c311..eee118331b33 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -36,18 +46,21 @@ from google.shopping.merchant_accounts_v1.services.account_issue_service import pagers from google.shopping.merchant_accounts_v1.types import accountissue -from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport + from .client import AccountIssueServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AccountIssueServiceTransport +from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport 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 AccountIssueServiceAsyncClient: """Service to support ``AccountIssueService`` API.""" @@ -63,17 +76,33 @@ class AccountIssueServiceAsyncClient: account_path = staticmethod(AccountIssueServiceClient.account_path) parse_account_path = staticmethod(AccountIssueServiceClient.parse_account_path) account_issue_path = staticmethod(AccountIssueServiceClient.account_issue_path) - parse_account_issue_path = staticmethod(AccountIssueServiceClient.parse_account_issue_path) - common_billing_account_path = staticmethod(AccountIssueServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountIssueServiceClient.parse_common_billing_account_path) + parse_account_issue_path = staticmethod( + AccountIssueServiceClient.parse_account_issue_path + ) + common_billing_account_path = staticmethod( + AccountIssueServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AccountIssueServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(AccountIssueServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountIssueServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountIssueServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountIssueServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + AccountIssueServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AccountIssueServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AccountIssueServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(AccountIssueServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountIssueServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + AccountIssueServiceClient.parse_common_project_path + ) common_location_path = staticmethod(AccountIssueServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountIssueServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + AccountIssueServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -109,7 +138,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: @@ -172,12 +203,20 @@ def universe_domain(self) -> str: get_transport_class = AccountIssueServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = "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, + AccountIssueServiceTransport, + Callable[..., AccountIssueServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the account issue service async client. Args: @@ -232,31 +271,39 @@ 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.accounts_v1.AccountIssueServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", - "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.accounts.v1.AccountIssueService", "credentialsType": None, - } + }, ) - async def list_account_issues(self, - request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesAsyncPager: + async def list_account_issues( + self, + request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesAsyncPager: r"""Lists all account issues of a Merchant Center account. When called on a multi-client account, this method only returns @@ -323,10 +370,14 @@ async def sample_list_account_issues(): # - 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. @@ -340,14 +391,14 @@ async def sample_list_account_issues(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_account_issues] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_account_issues + ] # 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. @@ -381,12 +432,13 @@ async def __aenter__(self) -> "AccountIssueServiceAsyncClient": 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__ = ( - "AccountIssueServiceAsyncClient", -) +__all__ = ("AccountIssueServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py index 978fe2a0c0cc..f1a6d450b582 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,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 @@ -50,7 +63,8 @@ from google.shopping.merchant_accounts_v1.services.account_issue_service import pagers from google.shopping.merchant_accounts_v1.types import accountissue -from .transports.base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, AccountIssueServiceTransport from .transports.grpc import AccountIssueServiceGrpcTransport from .transports.grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport from .transports.rest import AccountIssueServiceRestTransport @@ -63,14 +77,18 @@ class AccountIssueServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AccountIssueServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AccountIssueServiceTransport]] _transport_registry["grpc"] = AccountIssueServiceGrpcTransport _transport_registry["grpc_asyncio"] = AccountIssueServiceGrpcAsyncIOTransport _transport_registry["rest"] = AccountIssueServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountIssueServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AccountIssueServiceTransport]: """Returns an appropriate transport class. Args: @@ -162,8 +180,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountIssueServiceClient: 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) @@ -180,84 +197,118 @@ def transport(self) -> AccountIssueServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def account_issue_path(account: str,issue: str,) -> str: + def account_issue_path( + account: str, + issue: str, + ) -> str: """Returns a fully-qualified account_issue string.""" - return "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) + return "accounts/{account}/issues/{issue}".format( + account=account, + issue=issue, + ) @staticmethod - def parse_account_issue_path(path: str) -> Dict[str,str]: + def parse_account_issue_path(path: str) -> Dict[str, str]: """Parses a account_issue path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/issues/(?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: @@ -289,16 +340,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 @@ -311,7 +368,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 @@ -332,13 +391,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 @@ -361,7 +426,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: @@ -377,17 +444,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = AccountIssueServiceClient._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 = AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = AccountIssueServiceClient._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: @@ -423,15 +498,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 @@ -464,12 +542,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountIssueServiceTransport, Callable[..., AccountIssueServiceTransport]]] = 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, + AccountIssueServiceTransport, + Callable[..., AccountIssueServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the account issue service client. Args: @@ -524,14 +610,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 = AccountIssueServiceClient._read_environment_variables() - self._client_cert_source = AccountIssueServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountIssueServiceClient._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, + ) = AccountIssueServiceClient._read_environment_variables() + self._client_cert_source = AccountIssueServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AccountIssueServiceClient._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 @@ -542,7 +638,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 @@ -551,8 +649,10 @@ def __init__(self, *, if transport_provided: # transport is a AccountIssueServiceTransport 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 " @@ -561,20 +661,30 @@ def __init__(self, *, self._transport = cast(AccountIssueServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AccountIssueServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AccountIssueServiceClient._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[AccountIssueServiceTransport], Callable[..., AccountIssueServiceTransport]] = ( + transport_init: Union[ + Type[AccountIssueServiceTransport], + Callable[..., AccountIssueServiceTransport], + ] = ( AccountIssueServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AccountIssueServiceTransport], transport) @@ -593,28 +703,37 @@ 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.accounts_v1.AccountIssueServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", - "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.accounts.v1.AccountIssueService", "credentialsType": None, - } + }, ) - def list_account_issues(self, - request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesPager: + def list_account_issues( + self, + request: Optional[Union[accountissue.ListAccountIssuesRequest, 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.ListAccountIssuesPager: r"""Lists all account issues of a Merchant Center account. When called on a multi-client account, this method only returns @@ -681,10 +800,14 @@ def sample_list_account_issues(): # - 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. @@ -702,9 +825,7 @@ def sample_list_account_issues(): # 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. @@ -746,16 +867,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__ = ( - "AccountIssueServiceClient", -) +__all__ = ("AccountIssueServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py index 30d1a072306a..33440a2fffda 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_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 ListAccountIssuesPager: 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[..., accountissue.ListAccountIssuesResponse], - request: accountissue.ListAccountIssuesRequest, - response: accountissue.ListAccountIssuesResponse, - *, - 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[..., accountissue.ListAccountIssuesResponse], + request: accountissue.ListAccountIssuesRequest, + response: accountissue.ListAccountIssuesResponse, + *, + 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[accountissue.ListAccountIssuesResponse]: 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[accountissue.AccountIssue]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[accountissue.AccountIssue]: yield from page.account_issues 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 ListAccountIssuesAsyncPager: @@ -112,14 +134,17 @@ class ListAccountIssuesAsyncPager: 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[accountissue.ListAccountIssuesResponse]], - request: accountissue.ListAccountIssuesRequest, - response: accountissue.ListAccountIssuesResponse, - *, - 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[accountissue.ListAccountIssuesResponse]], + request: accountissue.ListAccountIssuesRequest, + response: accountissue.ListAccountIssuesResponse, + *, + 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[accountissue.ListAccountIssuesResponse]: 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[accountissue.AccountIssue]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py index 7a24cf1c8dd1..9e5446d31db1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/__init__.py @@ -19,20 +19,20 @@ from .base import AccountIssueServiceTransport from .grpc import AccountIssueServiceGrpcTransport from .grpc_asyncio import AccountIssueServiceGrpcAsyncIOTransport -from .rest import AccountIssueServiceRestTransport -from .rest import AccountIssueServiceRestInterceptor - +from .rest import AccountIssueServiceRestInterceptor, AccountIssueServiceRestTransport # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AccountIssueServiceTransport]] -_transport_registry['grpc'] = AccountIssueServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountIssueServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountIssueServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[AccountIssueServiceTransport]] +_transport_registry["grpc"] = AccountIssueServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AccountIssueServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AccountIssueServiceRestTransport __all__ = ( - 'AccountIssueServiceTransport', - 'AccountIssueServiceGrpcTransport', - 'AccountIssueServiceGrpcAsyncIOTransport', - 'AccountIssueServiceRestTransport', - 'AccountIssueServiceRestInterceptor', + "AccountIssueServiceTransport", + "AccountIssueServiceGrpcTransport", + "AccountIssueServiceGrpcAsyncIOTransport", + "AccountIssueServiceRestTransport", + "AccountIssueServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py similarity index 69% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py index c113b8e7fc4e..3d7d90bdd2d8 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import accountissue -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__ @@ -38,24 +39,23 @@ class AccountIssueServiceTransport(abc.ABC): """Abstract transport class for AccountIssueService.""" - 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: @@ -91,30 +91,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 @@ -129,24 +137,27 @@ 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_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - Union[ - accountissue.ListAccountIssuesResponse, - Awaitable[accountissue.ListAccountIssuesResponse] - ]]: + def list_account_issues( + self, + ) -> Callable[ + [accountissue.ListAccountIssuesRequest], + Union[ + accountissue.ListAccountIssuesResponse, + Awaitable[accountissue.ListAccountIssuesResponse], + ], + ]: raise NotImplementedError() @property @@ -154,6 +165,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AccountIssueServiceTransport', -) +__all__ = ("AccountIssueServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py similarity index 86% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py index e5c456fba4d1..fd80188ddcd5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import accountissue -from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountIssueServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", "rpcName": client_call_details.method, "response": grpc_response, @@ -113,23 +119,26 @@ class AccountIssueServiceGrpcTransport(AccountIssueServiceTransport): 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: @@ -251,19 +260,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. @@ -298,19 +311,20 @@ 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_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - accountissue.ListAccountIssuesResponse]: + def list_account_issues( + self, + ) -> Callable[ + [accountissue.ListAccountIssuesRequest], accountissue.ListAccountIssuesResponse + ]: r"""Return a callable for the list account issues method over gRPC. Lists all account issues of a Merchant Center account. @@ -332,13 +346,13 @@ def list_account_issues(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_account_issues' not in self._stubs: - self._stubs['list_account_issues'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountIssueService/ListAccountIssues', + if "list_account_issues" not in self._stubs: + self._stubs["list_account_issues"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountIssueService/ListAccountIssues", request_serializer=accountissue.ListAccountIssuesRequest.serialize, response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, ) - return self._stubs['list_account_issues'] + return self._stubs["list_account_issues"] def close(self): self._logged_channel.close() @@ -348,6 +362,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AccountIssueServiceGrpcTransport', -) +__all__ = ("AccountIssueServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py similarity index 85% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py index 482fc58b21a1..95eb7c04aad5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import accountissue -from .base import AccountIssueServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountIssueServiceTransport from .grpc import AccountIssueServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -122,13 +130,15 @@ class AccountIssueServiceGrpcAsyncIOTransport(AccountIssueServiceTransport): _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. @@ -158,24 +168,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: @@ -299,7 +311,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) @@ -314,9 +328,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - Awaitable[accountissue.ListAccountIssuesResponse]]: + def list_account_issues( + self, + ) -> Callable[ + [accountissue.ListAccountIssuesRequest], + Awaitable[accountissue.ListAccountIssuesResponse], + ]: r"""Return a callable for the list account issues method over gRPC. Lists all account issues of a Merchant Center account. @@ -338,16 +355,16 @@ def list_account_issues(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_account_issues' not in self._stubs: - self._stubs['list_account_issues'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountIssueService/ListAccountIssues', + if "list_account_issues" not in self._stubs: + self._stubs["list_account_issues"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountIssueService/ListAccountIssues", request_serializer=accountissue.ListAccountIssuesRequest.serialize, response_deserializer=accountissue.ListAccountIssuesResponse.deserialize, ) - return self._stubs['list_account_issues'] + return self._stubs["list_account_issues"] 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_account_issues: self._wrap_method( self.list_account_issues, @@ -369,6 +386,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'AccountIssueServiceGrpcAsyncIOTransport', -) +__all__ = ("AccountIssueServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py similarity index 75% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py index 5a9fbfaf4a7b..c39cdde3f1d3 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import accountissue - -from .rest_base import _BaseAccountIssueServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAccountIssueServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -90,7 +85,14 @@ def post_list_account_issues(self, response): """ - def pre_list_account_issues(self, request: accountissue.ListAccountIssuesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_list_account_issues( + self, + request: accountissue.ListAccountIssuesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountissue.ListAccountIssuesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_account_issues Override in a subclass to manipulate the request or metadata @@ -98,7 +100,9 @@ def pre_list_account_issues(self, request: accountissue.ListAccountIssuesRequest """ return request, metadata - def post_list_account_issues(self, response: accountissue.ListAccountIssuesResponse) -> accountissue.ListAccountIssuesResponse: + def post_list_account_issues( + self, response: accountissue.ListAccountIssuesResponse + ) -> accountissue.ListAccountIssuesResponse: """Post-rpc interceptor for list_account_issues DEPRECATED. Please use the `post_list_account_issues_with_metadata` @@ -111,7 +115,13 @@ def post_list_account_issues(self, response: accountissue.ListAccountIssuesRespo """ return response - def post_list_account_issues_with_metadata(self, response: accountissue.ListAccountIssuesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountissue.ListAccountIssuesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_account_issues_with_metadata( + self, + response: accountissue.ListAccountIssuesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountissue.ListAccountIssuesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_account_issues Override in a subclass to read or manipulate the response or metadata after it @@ -146,20 +156,21 @@ class AccountIssueServiceRestTransport(_BaseAccountIssueServiceRestTransport): 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[AccountIssueServiceRestInterceptor] = 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[AccountIssueServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -202,16 +213,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 AccountIssueServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _ListAccountIssues(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues, AccountIssueServiceRestStub): + class _ListAccountIssues( + _BaseAccountIssueServiceRestTransport._BaseListAccountIssues, + AccountIssueServiceRestStub, + ): def __hash__(self): return hash("AccountIssueServiceRestTransport.ListAccountIssues") @@ -223,26 +238,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: accountissue.ListAccountIssuesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountissue.ListAccountIssuesResponse: + def __call__( + self, + request: accountissue.ListAccountIssuesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountissue.ListAccountIssuesResponse: r"""Call the list account issues method over HTTP. Args: @@ -261,30 +278,42 @@ def __call__(self, Response message for the ``ListAccountIssues`` method. """ - http_options = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_http_options() + http_options = ( + _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_http_options() + ) - request, metadata = self._interceptor.pre_list_account_issues(request, metadata) - transcoded_request = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_account_issues( + request, metadata + ) + transcoded_request = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountIssueServiceClient.ListAccountIssues", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", "rpcName": "ListAccountIssues", "httpRequest": http_request, @@ -293,7 +322,16 @@ def __call__(self, ) # Send the request - response = AccountIssueServiceRestTransport._ListAccountIssues._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AccountIssueServiceRestTransport._ListAccountIssues._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -308,20 +346,26 @@ def __call__(self, resp = self._interceptor.post_list_account_issues(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_account_issues_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_account_issues_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = accountissue.ListAccountIssuesResponse.to_json(response) + response_payload = accountissue.ListAccountIssuesResponse.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.accounts_v1.AccountIssueServiceClient.list_account_issues", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountIssueService", "rpcName": "ListAccountIssues", "metadata": http_response["headers"], @@ -331,12 +375,14 @@ def __call__(self, return resp @property - def list_account_issues(self) -> Callable[ - [accountissue.ListAccountIssuesRequest], - accountissue.ListAccountIssuesResponse]: + def list_account_issues( + self, + ) -> Callable[ + [accountissue.ListAccountIssuesRequest], accountissue.ListAccountIssuesResponse + ]: # 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._ListAccountIssues(self._session, self._host, self._interceptor) # type: ignore + return self._ListAccountIssues(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -346,6 +392,4 @@ def close(self): self._session.close() -__all__=( - 'AccountIssueServiceRestTransport', -) +__all__ = ("AccountIssueServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py similarity index 70% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py index e5a8f8cbb4b2..1550369b00ae 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_issue_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 AccountIssueServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import accountissue +from .base import DEFAULT_CLIENT_INFO, AccountIssueServiceTransport + class _BaseAccountIssueServiceRestTransport(AccountIssueServiceTransport): """Base REST backend transport for AccountIssueService. @@ -40,14 +38,16 @@ class _BaseAccountIssueServiceRestTransport(AccountIssueServiceTransport): 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseListAccountIssues: 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': '/accounts/v1/{parent=accounts/*}/issues', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/issues", + }, ] return http_options @@ -113,16 +119,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(_BaseAccountIssueServiceRestTransport._BaseListAccountIssues._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( + _BaseAccountIssueServiceRestTransport._BaseListAccountIssues._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseAccountIssueServiceRestTransport', -) +__all__ = ("_BaseAccountIssueServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py index fc0969e77119..b98e62e4835b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AccountRelationshipsServiceClient from .async_client import AccountRelationshipsServiceAsyncClient +from .client import AccountRelationshipsServiceClient __all__ = ( - 'AccountRelationshipsServiceClient', - 'AccountRelationshipsServiceAsyncClient', + "AccountRelationshipsServiceClient", + "AccountRelationshipsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py index 6c7fd12e68b3..546fb8972c90 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,20 +45,26 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.account_relationships_service import pagers + +from google.shopping.merchant_accounts_v1.services.account_relationships_service import ( + pagers, +) from google.shopping.merchant_accounts_v1.types import accountrelationships -from .transports.base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport + from .client import AccountRelationshipsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AccountRelationshipsServiceTransport +from .transports.grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport 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 AccountRelationshipsServiceAsyncClient: """Service to support AccountRelationship API.""" @@ -58,23 +74,51 @@ class AccountRelationshipsServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = AccountRelationshipsServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE account_path = staticmethod(AccountRelationshipsServiceClient.account_path) - parse_account_path = staticmethod(AccountRelationshipsServiceClient.parse_account_path) - account_relationship_path = staticmethod(AccountRelationshipsServiceClient.account_relationship_path) - parse_account_relationship_path = staticmethod(AccountRelationshipsServiceClient.parse_account_relationship_path) - common_billing_account_path = staticmethod(AccountRelationshipsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountRelationshipsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AccountRelationshipsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountRelationshipsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountRelationshipsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountRelationshipsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AccountRelationshipsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountRelationshipsServiceClient.parse_common_project_path) - common_location_path = staticmethod(AccountRelationshipsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountRelationshipsServiceClient.parse_common_location_path) + parse_account_path = staticmethod( + AccountRelationshipsServiceClient.parse_account_path + ) + account_relationship_path = staticmethod( + AccountRelationshipsServiceClient.account_relationship_path + ) + parse_account_relationship_path = staticmethod( + AccountRelationshipsServiceClient.parse_account_relationship_path + ) + common_billing_account_path = staticmethod( + AccountRelationshipsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AccountRelationshipsServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + AccountRelationshipsServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + AccountRelationshipsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AccountRelationshipsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AccountRelationshipsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + AccountRelationshipsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + AccountRelationshipsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + AccountRelationshipsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + AccountRelationshipsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +154,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 +219,20 @@ def universe_domain(self) -> str: get_transport_class = AccountRelationshipsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountRelationshipsServiceTransport, Callable[..., AccountRelationshipsServiceTransport]]] = "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, + AccountRelationshipsServiceTransport, + Callable[..., AccountRelationshipsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the account relationships service async client. Args: @@ -233,31 +287,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.accounts_v1.AccountRelationshipsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", - "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.accounts.v1.AccountRelationshipsService", "credentialsType": None, - } + }, ) - async def get_account_relationship(self, - request: Optional[Union[accountrelationships.GetAccountRelationshipRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountrelationships.AccountRelationship: + async def get_account_relationship( + self, + request: Optional[ + Union[accountrelationships.GetAccountRelationshipRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: r"""Retrieve an account relationship. .. code-block:: python @@ -328,10 +392,14 @@ async def sample_get_account_relationship(): # - 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. @@ -345,14 +413,14 @@ async def sample_get_account_relationship(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_account_relationship] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_account_relationship + ] # 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. @@ -369,15 +437,18 @@ async def sample_get_account_relationship(): # Done; return the response. return response - async def update_account_relationship(self, - request: Optional[Union[accountrelationships.UpdateAccountRelationshipRequest, dict]] = None, - *, - account_relationship: Optional[accountrelationships.AccountRelationship] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountrelationships.AccountRelationship: + async def update_account_relationship( + self, + request: Optional[ + Union[accountrelationships.UpdateAccountRelationshipRequest, dict] + ] = None, + *, + account_relationship: Optional[accountrelationships.AccountRelationship] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: r"""Updates the account relationship. Executing this method requires admin access. @@ -457,14 +528,20 @@ async def sample_update_account_relationship(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [account_relationship, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, accountrelationships.UpdateAccountRelationshipRequest): + if not isinstance( + request, accountrelationships.UpdateAccountRelationshipRequest + ): request = accountrelationships.UpdateAccountRelationshipRequest(request) # If we have keyword arguments corresponding to fields on the @@ -476,14 +553,16 @@ async def sample_update_account_relationship(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_account_relationship] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_account_relationship + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account_relationship.name", request.account_relationship.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("account_relationship.name", request.account_relationship.name),) + ), ) # Validate the universe domain. @@ -500,14 +579,17 @@ async def sample_update_account_relationship(): # Done; return the response. return response - async def list_account_relationships(self, - request: Optional[Union[accountrelationships.ListAccountRelationshipsRequest, 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.ListAccountRelationshipsAsyncPager: + async def list_account_relationships( + self, + request: Optional[ + Union[accountrelationships.ListAccountRelationshipsRequest, 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.ListAccountRelationshipsAsyncPager: r"""List account relationships for the specified account. .. code-block:: python @@ -569,14 +651,20 @@ async def sample_list_account_relationships(): # - 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. - if not isinstance(request, accountrelationships.ListAccountRelationshipsRequest): + if not isinstance( + request, accountrelationships.ListAccountRelationshipsRequest + ): request = accountrelationships.ListAccountRelationshipsRequest(request) # If we have keyword arguments corresponding to fields on the @@ -586,14 +674,14 @@ async def sample_list_account_relationships(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_account_relationships] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_account_relationships + ] # 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. @@ -627,12 +715,13 @@ async def __aenter__(self) -> "AccountRelationshipsServiceAsyncClient": 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__ = ( - "AccountRelationshipsServiceAsyncClient", -) +__all__ = ("AccountRelationshipsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py index f35d0a48eb1e..d76b7b18bcbb 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,9 +62,13 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.account_relationships_service import pagers + +from google.shopping.merchant_accounts_v1.services.account_relationships_service import ( + pagers, +) from google.shopping.merchant_accounts_v1.types import accountrelationships -from .transports.base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, AccountRelationshipsServiceTransport from .transports.grpc import AccountRelationshipsServiceGrpcTransport from .transports.grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport from .transports.rest import AccountRelationshipsServiceRestTransport @@ -64,14 +81,20 @@ class AccountRelationshipsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AccountRelationshipsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AccountRelationshipsServiceTransport]] _transport_registry["grpc"] = AccountRelationshipsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AccountRelationshipsServiceGrpcAsyncIOTransport + _transport_registry[ + "grpc_asyncio" + ] = AccountRelationshipsServiceGrpcAsyncIOTransport _transport_registry["rest"] = AccountRelationshipsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountRelationshipsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AccountRelationshipsServiceTransport]: """Returns an appropriate transport class. Args: @@ -90,7 +113,9 @@ def get_transport_class(cls, return next(iter(cls._transport_registry.values())) -class AccountRelationshipsServiceClient(metaclass=AccountRelationshipsServiceClientMeta): +class AccountRelationshipsServiceClient( + metaclass=AccountRelationshipsServiceClientMeta +): """Service to support AccountRelationship API.""" @staticmethod @@ -163,8 +188,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountRelationshipsServiceClient: 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,84 +205,120 @@ def transport(self) -> AccountRelationshipsServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def account_relationship_path(account: str,relationship: str,) -> str: + def account_relationship_path( + account: str, + relationship: str, + ) -> str: """Returns a fully-qualified account_relationship string.""" - return "accounts/{account}/relationships/{relationship}".format(account=account, relationship=relationship, ) + return "accounts/{account}/relationships/{relationship}".format( + account=account, + relationship=relationship, + ) @staticmethod - def parse_account_relationship_path(path: str) -> Dict[str,str]: + def parse_account_relationship_path(path: str) -> Dict[str, str]: """Parses a account_relationship path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/relationships/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/relationships/(?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: @@ -290,16 +350,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 @@ -312,7 +378,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 @@ -333,13 +401,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 @@ -362,7 +436,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: @@ -378,17 +454,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 = AccountRelationshipsServiceClient._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 = AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + AccountRelationshipsServiceClient._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: @@ -424,15 +510,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 @@ -465,12 +554,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountRelationshipsServiceTransport, Callable[..., AccountRelationshipsServiceTransport]]] = 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, + AccountRelationshipsServiceTransport, + Callable[..., AccountRelationshipsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the account relationships service client. Args: @@ -525,14 +622,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 = AccountRelationshipsServiceClient._read_environment_variables() - self._client_cert_source = AccountRelationshipsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountRelationshipsServiceClient._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, + ) = AccountRelationshipsServiceClient._read_environment_variables() + self._client_cert_source = ( + AccountRelationshipsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = AccountRelationshipsServiceClient._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 @@ -543,7 +652,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 @@ -552,8 +663,10 @@ def __init__(self, *, if transport_provided: # transport is a AccountRelationshipsServiceTransport 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 " @@ -562,23 +675,35 @@ def __init__(self, *, self._transport = cast(AccountRelationshipsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AccountRelationshipsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AccountRelationshipsServiceClient._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[AccountRelationshipsServiceTransport], Callable[..., AccountRelationshipsServiceTransport]] = ( + transport_init: Union[ + Type[AccountRelationshipsServiceTransport], + Callable[..., AccountRelationshipsServiceTransport], + ] = ( AccountRelationshipsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None - else cast(Callable[..., AccountRelationshipsServiceTransport], transport) + else cast( + Callable[..., AccountRelationshipsServiceTransport], transport + ) ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -594,28 +719,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.accounts_v1.AccountRelationshipsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", - "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.accounts.v1.AccountRelationshipsService", "credentialsType": None, - } + }, ) - def get_account_relationship(self, - request: Optional[Union[accountrelationships.GetAccountRelationshipRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountrelationships.AccountRelationship: + def get_account_relationship( + self, + request: Optional[ + Union[accountrelationships.GetAccountRelationshipRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: r"""Retrieve an account relationship. .. code-block:: python @@ -686,10 +822,14 @@ def sample_get_account_relationship(): # - 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. @@ -707,9 +847,7 @@ def sample_get_account_relationship(): # 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. @@ -726,15 +864,18 @@ def sample_get_account_relationship(): # Done; return the response. return response - def update_account_relationship(self, - request: Optional[Union[accountrelationships.UpdateAccountRelationshipRequest, dict]] = None, - *, - account_relationship: Optional[accountrelationships.AccountRelationship] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountrelationships.AccountRelationship: + def update_account_relationship( + self, + request: Optional[ + Union[accountrelationships.UpdateAccountRelationshipRequest, dict] + ] = None, + *, + account_relationship: Optional[accountrelationships.AccountRelationship] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: r"""Updates the account relationship. Executing this method requires admin access. @@ -814,14 +955,20 @@ def sample_update_account_relationship(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [account_relationship, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, accountrelationships.UpdateAccountRelationshipRequest): + if not isinstance( + request, accountrelationships.UpdateAccountRelationshipRequest + ): request = accountrelationships.UpdateAccountRelationshipRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -832,14 +979,16 @@ def sample_update_account_relationship(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_account_relationship] + rpc = self._transport._wrapped_methods[ + self._transport.update_account_relationship + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account_relationship.name", request.account_relationship.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("account_relationship.name", request.account_relationship.name),) + ), ) # Validate the universe domain. @@ -856,14 +1005,17 @@ def sample_update_account_relationship(): # Done; return the response. return response - def list_account_relationships(self, - request: Optional[Union[accountrelationships.ListAccountRelationshipsRequest, 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.ListAccountRelationshipsPager: + def list_account_relationships( + self, + request: Optional[ + Union[accountrelationships.ListAccountRelationshipsRequest, 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.ListAccountRelationshipsPager: r"""List account relationships for the specified account. .. code-block:: python @@ -925,14 +1077,20 @@ def sample_list_account_relationships(): # - 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. - if not isinstance(request, accountrelationships.ListAccountRelationshipsRequest): + if not isinstance( + request, accountrelationships.ListAccountRelationshipsRequest + ): request = accountrelationships.ListAccountRelationshipsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -941,14 +1099,14 @@ def sample_list_account_relationships(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_account_relationships] + rpc = self._transport._wrapped_methods[ + self._transport.list_account_relationships + ] # 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. @@ -990,16 +1148,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__ = ( - "AccountRelationshipsServiceClient", -) +__all__ = ("AccountRelationshipsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py index d05f4807759b..70fb26feab18 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_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 ListAccountRelationshipsPager: 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[..., accountrelationships.ListAccountRelationshipsResponse], - request: accountrelationships.ListAccountRelationshipsRequest, - response: accountrelationships.ListAccountRelationshipsResponse, - *, - 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[..., accountrelationships.ListAccountRelationshipsResponse], + request: accountrelationships.ListAccountRelationshipsRequest, + response: accountrelationships.ListAccountRelationshipsResponse, + *, + 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[accountrelationships.ListAccountRelationshipsRespons 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[accountrelationships.AccountRelationship]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[accountrelationships.AccountRelationship]: yield from page.account_relationships 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 ListAccountRelationshipsAsyncPager: @@ -112,14 +134,19 @@ class ListAccountRelationshipsAsyncPager: 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[accountrelationships.ListAccountRelationshipsResponse]], - request: accountrelationships.ListAccountRelationshipsRequest, - response: accountrelationships.ListAccountRelationshipsResponse, - *, - 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[accountrelationships.ListAccountRelationshipsResponse] + ], + request: accountrelationships.ListAccountRelationshipsRequest, + response: accountrelationships.ListAccountRelationshipsResponse, + *, + 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[accountrelationships.ListAccountRelationshipsResponse]: + async def pages( + self, + ) -> AsyncIterator[accountrelationships.ListAccountRelationshipsResponse]: 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[accountrelationships.AccountRelationship]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py index 4f29f69c39f7..6541855946a5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import AccountRelationshipsServiceTransport from .grpc import AccountRelationshipsServiceGrpcTransport from .grpc_asyncio import AccountRelationshipsServiceGrpcAsyncIOTransport -from .rest import AccountRelationshipsServiceRestTransport -from .rest import AccountRelationshipsServiceRestInterceptor - +from .rest import ( + AccountRelationshipsServiceRestInterceptor, + AccountRelationshipsServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AccountRelationshipsServiceTransport]] -_transport_registry['grpc'] = AccountRelationshipsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountRelationshipsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountRelationshipsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[AccountRelationshipsServiceTransport]] +_transport_registry["grpc"] = AccountRelationshipsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AccountRelationshipsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AccountRelationshipsServiceRestTransport __all__ = ( - 'AccountRelationshipsServiceTransport', - 'AccountRelationshipsServiceGrpcTransport', - 'AccountRelationshipsServiceGrpcAsyncIOTransport', - 'AccountRelationshipsServiceRestTransport', - 'AccountRelationshipsServiceRestInterceptor', + "AccountRelationshipsServiceTransport", + "AccountRelationshipsServiceGrpcTransport", + "AccountRelationshipsServiceGrpcAsyncIOTransport", + "AccountRelationshipsServiceRestTransport", + "AccountRelationshipsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py index 74824d32ffd2..c7f0aa75b360 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import accountrelationships -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__ @@ -38,24 +39,23 @@ class AccountRelationshipsServiceTransport(abc.ABC): """Abstract transport class for AccountRelationshipsService.""" - 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: @@ -91,30 +91,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 @@ -139,42 +147,51 @@ 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 get_account_relationship(self) -> Callable[ - [accountrelationships.GetAccountRelationshipRequest], - Union[ - accountrelationships.AccountRelationship, - Awaitable[accountrelationships.AccountRelationship] - ]]: + def get_account_relationship( + self, + ) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + Union[ + accountrelationships.AccountRelationship, + Awaitable[accountrelationships.AccountRelationship], + ], + ]: raise NotImplementedError() @property - def update_account_relationship(self) -> Callable[ - [accountrelationships.UpdateAccountRelationshipRequest], - Union[ - accountrelationships.AccountRelationship, - Awaitable[accountrelationships.AccountRelationship] - ]]: + def update_account_relationship( + self, + ) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + Union[ + accountrelationships.AccountRelationship, + Awaitable[accountrelationships.AccountRelationship], + ], + ]: raise NotImplementedError() @property - def list_account_relationships(self) -> Callable[ - [accountrelationships.ListAccountRelationshipsRequest], - Union[ - accountrelationships.ListAccountRelationshipsResponse, - Awaitable[accountrelationships.ListAccountRelationshipsResponse] - ]]: + def list_account_relationships( + self, + ) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + Union[ + accountrelationships.ListAccountRelationshipsResponse, + Awaitable[accountrelationships.ListAccountRelationshipsResponse], + ], + ]: raise NotImplementedError() @property @@ -182,6 +199,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AccountRelationshipsServiceTransport', -) +__all__ = ("AccountRelationshipsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py index 93d4b61901e9..d3c844056a43 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import accountrelationships -from .base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountRelationshipsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -113,23 +119,26 @@ class AccountRelationshipsServiceGrpcTransport(AccountRelationshipsServiceTransp 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: @@ -251,19 +260,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. @@ -298,19 +311,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 get_account_relationship(self) -> Callable[ - [accountrelationships.GetAccountRelationshipRequest], - accountrelationships.AccountRelationship]: + def get_account_relationship( + self, + ) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + accountrelationships.AccountRelationship, + ]: r"""Return a callable for the get account relationship method over gRPC. Retrieve an account relationship. @@ -325,18 +340,21 @@ def get_account_relationship(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_account_relationship' not in self._stubs: - self._stubs['get_account_relationship'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/GetAccountRelationship', + if "get_account_relationship" not in self._stubs: + self._stubs["get_account_relationship"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountRelationshipsService/GetAccountRelationship", request_serializer=accountrelationships.GetAccountRelationshipRequest.serialize, response_deserializer=accountrelationships.AccountRelationship.deserialize, ) - return self._stubs['get_account_relationship'] + return self._stubs["get_account_relationship"] @property - def update_account_relationship(self) -> Callable[ - [accountrelationships.UpdateAccountRelationshipRequest], - accountrelationships.AccountRelationship]: + def update_account_relationship( + self, + ) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + accountrelationships.AccountRelationship, + ]: r"""Return a callable for the update account relationship method over gRPC. Updates the account relationship. Executing this @@ -352,18 +370,23 @@ def update_account_relationship(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_account_relationship' not in self._stubs: - self._stubs['update_account_relationship'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/UpdateAccountRelationship', + if "update_account_relationship" not in self._stubs: + self._stubs[ + "update_account_relationship" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountRelationshipsService/UpdateAccountRelationship", request_serializer=accountrelationships.UpdateAccountRelationshipRequest.serialize, response_deserializer=accountrelationships.AccountRelationship.deserialize, ) - return self._stubs['update_account_relationship'] + return self._stubs["update_account_relationship"] @property - def list_account_relationships(self) -> Callable[ - [accountrelationships.ListAccountRelationshipsRequest], - accountrelationships.ListAccountRelationshipsResponse]: + def list_account_relationships( + self, + ) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + accountrelationships.ListAccountRelationshipsResponse, + ]: r"""Return a callable for the list account relationships method over gRPC. List account relationships for the specified account. @@ -378,13 +401,15 @@ def list_account_relationships(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_account_relationships' not in self._stubs: - self._stubs['list_account_relationships'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/ListAccountRelationships', + if "list_account_relationships" not in self._stubs: + self._stubs[ + "list_account_relationships" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountRelationshipsService/ListAccountRelationships", request_serializer=accountrelationships.ListAccountRelationshipsRequest.serialize, response_deserializer=accountrelationships.ListAccountRelationshipsResponse.deserialize, ) - return self._stubs['list_account_relationships'] + return self._stubs["list_account_relationships"] def close(self): self._logged_channel.close() @@ -394,6 +419,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AccountRelationshipsServiceGrpcTransport', -) +__all__ = ("AccountRelationshipsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py index cc85204a38cc..ef56777ec09a 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import accountrelationships -from .base import AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountRelationshipsServiceTransport from .grpc import AccountRelationshipsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -105,7 +113,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request return response -class AccountRelationshipsServiceGrpcAsyncIOTransport(AccountRelationshipsServiceTransport): +class AccountRelationshipsServiceGrpcAsyncIOTransport( + AccountRelationshipsServiceTransport +): """gRPC AsyncIO backend transport for AccountRelationshipsService. Service to support AccountRelationship API. @@ -122,13 +132,15 @@ class AccountRelationshipsServiceGrpcAsyncIOTransport(AccountRelationshipsServic _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. @@ -158,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: @@ -299,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) @@ -314,9 +330,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_account_relationship(self) -> Callable[ - [accountrelationships.GetAccountRelationshipRequest], - Awaitable[accountrelationships.AccountRelationship]]: + def get_account_relationship( + self, + ) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + Awaitable[accountrelationships.AccountRelationship], + ]: r"""Return a callable for the get account relationship method over gRPC. Retrieve an account relationship. @@ -331,18 +350,21 @@ def get_account_relationship(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_account_relationship' not in self._stubs: - self._stubs['get_account_relationship'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/GetAccountRelationship', + if "get_account_relationship" not in self._stubs: + self._stubs["get_account_relationship"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountRelationshipsService/GetAccountRelationship", request_serializer=accountrelationships.GetAccountRelationshipRequest.serialize, response_deserializer=accountrelationships.AccountRelationship.deserialize, ) - return self._stubs['get_account_relationship'] + return self._stubs["get_account_relationship"] @property - def update_account_relationship(self) -> Callable[ - [accountrelationships.UpdateAccountRelationshipRequest], - Awaitable[accountrelationships.AccountRelationship]]: + def update_account_relationship( + self, + ) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + Awaitable[accountrelationships.AccountRelationship], + ]: r"""Return a callable for the update account relationship method over gRPC. Updates the account relationship. Executing this @@ -358,18 +380,23 @@ def update_account_relationship(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_account_relationship' not in self._stubs: - self._stubs['update_account_relationship'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/UpdateAccountRelationship', + if "update_account_relationship" not in self._stubs: + self._stubs[ + "update_account_relationship" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountRelationshipsService/UpdateAccountRelationship", request_serializer=accountrelationships.UpdateAccountRelationshipRequest.serialize, response_deserializer=accountrelationships.AccountRelationship.deserialize, ) - return self._stubs['update_account_relationship'] + return self._stubs["update_account_relationship"] @property - def list_account_relationships(self) -> Callable[ - [accountrelationships.ListAccountRelationshipsRequest], - Awaitable[accountrelationships.ListAccountRelationshipsResponse]]: + def list_account_relationships( + self, + ) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + Awaitable[accountrelationships.ListAccountRelationshipsResponse], + ]: r"""Return a callable for the list account relationships method over gRPC. List account relationships for the specified account. @@ -384,16 +411,18 @@ def list_account_relationships(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_account_relationships' not in self._stubs: - self._stubs['list_account_relationships'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountRelationshipsService/ListAccountRelationships', + if "list_account_relationships" not in self._stubs: + self._stubs[ + "list_account_relationships" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountRelationshipsService/ListAccountRelationships", request_serializer=accountrelationships.ListAccountRelationshipsRequest.serialize, response_deserializer=accountrelationships.ListAccountRelationshipsResponse.deserialize, ) - return self._stubs['list_account_relationships'] + return self._stubs["list_account_relationships"] 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.get_account_relationship: self._wrap_method( self.get_account_relationship, @@ -425,6 +454,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'AccountRelationshipsServiceGrpcAsyncIOTransport', -) +__all__ = ("AccountRelationshipsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py similarity index 63% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py index 7a58a0d4e438..b49e4cf983e0 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import accountrelationships - -from .rest_base import _BaseAccountRelationshipsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAccountRelationshipsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -106,7 +101,15 @@ def post_update_account_relationship(self, response): """ - def pre_get_account_relationship(self, request: accountrelationships.GetAccountRelationshipRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.GetAccountRelationshipRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_account_relationship( + self, + request: accountrelationships.GetAccountRelationshipRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountrelationships.GetAccountRelationshipRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_account_relationship Override in a subclass to manipulate the request or metadata @@ -114,7 +117,9 @@ def pre_get_account_relationship(self, request: accountrelationships.GetAccountR """ return request, metadata - def post_get_account_relationship(self, response: accountrelationships.AccountRelationship) -> accountrelationships.AccountRelationship: + def post_get_account_relationship( + self, response: accountrelationships.AccountRelationship + ) -> accountrelationships.AccountRelationship: """Post-rpc interceptor for get_account_relationship DEPRECATED. Please use the `post_get_account_relationship_with_metadata` @@ -127,7 +132,14 @@ def post_get_account_relationship(self, response: accountrelationships.AccountRe """ return response - def post_get_account_relationship_with_metadata(self, response: accountrelationships.AccountRelationship, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.AccountRelationship, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_account_relationship_with_metadata( + self, + response: accountrelationships.AccountRelationship, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountrelationships.AccountRelationship, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for get_account_relationship Override in a subclass to read or manipulate the response or metadata after it @@ -142,7 +154,14 @@ def post_get_account_relationship_with_metadata(self, response: accountrelations """ return response, metadata - def pre_list_account_relationships(self, request: accountrelationships.ListAccountRelationshipsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.ListAccountRelationshipsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_account_relationships( + self, + request: accountrelationships.ListAccountRelationshipsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountrelationships.ListAccountRelationshipsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_account_relationships Override in a subclass to manipulate the request or metadata @@ -150,7 +169,9 @@ def pre_list_account_relationships(self, request: accountrelationships.ListAccou """ return request, metadata - def post_list_account_relationships(self, response: accountrelationships.ListAccountRelationshipsResponse) -> accountrelationships.ListAccountRelationshipsResponse: + def post_list_account_relationships( + self, response: accountrelationships.ListAccountRelationshipsResponse + ) -> accountrelationships.ListAccountRelationshipsResponse: """Post-rpc interceptor for list_account_relationships DEPRECATED. Please use the `post_list_account_relationships_with_metadata` @@ -163,7 +184,14 @@ def post_list_account_relationships(self, response: accountrelationships.ListAcc """ return response - def post_list_account_relationships_with_metadata(self, response: accountrelationships.ListAccountRelationshipsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.ListAccountRelationshipsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_account_relationships_with_metadata( + self, + response: accountrelationships.ListAccountRelationshipsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountrelationships.ListAccountRelationshipsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_account_relationships Override in a subclass to read or manipulate the response or metadata after it @@ -178,7 +206,14 @@ def post_list_account_relationships_with_metadata(self, response: accountrelatio """ return response, metadata - def pre_update_account_relationship(self, request: accountrelationships.UpdateAccountRelationshipRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.UpdateAccountRelationshipRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_account_relationship( + self, + request: accountrelationships.UpdateAccountRelationshipRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountrelationships.UpdateAccountRelationshipRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_account_relationship Override in a subclass to manipulate the request or metadata @@ -186,7 +221,9 @@ def pre_update_account_relationship(self, request: accountrelationships.UpdateAc """ return request, metadata - def post_update_account_relationship(self, response: accountrelationships.AccountRelationship) -> accountrelationships.AccountRelationship: + def post_update_account_relationship( + self, response: accountrelationships.AccountRelationship + ) -> accountrelationships.AccountRelationship: """Post-rpc interceptor for update_account_relationship DEPRECATED. Please use the `post_update_account_relationship_with_metadata` @@ -199,7 +236,14 @@ def post_update_account_relationship(self, response: accountrelationships.Accoun """ return response - def post_update_account_relationship_with_metadata(self, response: accountrelationships.AccountRelationship, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountrelationships.AccountRelationship, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_account_relationship_with_metadata( + self, + response: accountrelationships.AccountRelationship, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountrelationships.AccountRelationship, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for update_account_relationship Override in a subclass to read or manipulate the response or metadata after it @@ -222,7 +266,9 @@ class AccountRelationshipsServiceRestStub: _interceptor: AccountRelationshipsServiceRestInterceptor -class AccountRelationshipsServiceRestTransport(_BaseAccountRelationshipsServiceRestTransport): +class AccountRelationshipsServiceRestTransport( + _BaseAccountRelationshipsServiceRestTransport +): """REST backend synchronous transport for AccountRelationshipsService. Service to support AccountRelationship API. @@ -234,20 +280,21 @@ class AccountRelationshipsServiceRestTransport(_BaseAccountRelationshipsServiceR 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[AccountRelationshipsServiceRestInterceptor] = 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[AccountRelationshipsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -290,18 +337,24 @@ 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 AccountRelationshipsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetAccountRelationship(_BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship, AccountRelationshipsServiceRestStub): + class _GetAccountRelationship( + _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship, + AccountRelationshipsServiceRestStub, + ): def __hash__(self): - return hash("AccountRelationshipsServiceRestTransport.GetAccountRelationship") + return hash( + "AccountRelationshipsServiceRestTransport.GetAccountRelationship" + ) @staticmethod def _get_response( @@ -311,26 +364,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: accountrelationships.GetAccountRelationshipRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountrelationships.AccountRelationship: + def __call__( + self, + request: accountrelationships.GetAccountRelationshipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: r"""Call the get account relationship method over HTTP. Args: @@ -363,30 +418,42 @@ def __call__(self, """ - http_options = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_http_options() + http_options = ( + _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_http_options() + ) - request, metadata = self._interceptor.pre_get_account_relationship(request, metadata) - transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_account_relationship( + request, metadata + ) + transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountRelationshipsServiceClient.GetAccountRelationship", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": "GetAccountRelationship", "httpRequest": http_request, @@ -395,7 +462,14 @@ def __call__(self, ) # Send the request - response = AccountRelationshipsServiceRestTransport._GetAccountRelationship._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AccountRelationshipsServiceRestTransport._GetAccountRelationship._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -410,20 +484,26 @@ def __call__(self, resp = self._interceptor.post_get_account_relationship(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_account_relationship_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_account_relationship_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = accountrelationships.AccountRelationship.to_json(response) + response_payload = accountrelationships.AccountRelationship.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.accounts_v1.AccountRelationshipsServiceClient.get_account_relationship", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": "GetAccountRelationship", "metadata": http_response["headers"], @@ -432,9 +512,14 @@ def __call__(self, ) return resp - class _ListAccountRelationships(_BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships, AccountRelationshipsServiceRestStub): + class _ListAccountRelationships( + _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships, + AccountRelationshipsServiceRestStub, + ): def __hash__(self): - return hash("AccountRelationshipsServiceRestTransport.ListAccountRelationships") + return hash( + "AccountRelationshipsServiceRestTransport.ListAccountRelationships" + ) @staticmethod def _get_response( @@ -444,72 +529,86 @@ 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: accountrelationships.ListAccountRelationshipsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountrelationships.ListAccountRelationshipsResponse: + def __call__( + self, + request: accountrelationships.ListAccountRelationshipsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.ListAccountRelationshipsResponse: r"""Call the list account - relationships method over HTTP. - - Args: - request (~.accountrelationships.ListAccountRelationshipsRequest): - The request object. Request to list account - relationships. - 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: - ~.accountrelationships.ListAccountRelationshipsResponse: - Response after trying to list account - relationships. + relationships method over HTTP. + + Args: + request (~.accountrelationships.ListAccountRelationshipsRequest): + The request object. Request to list account + relationships. + 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: + ~.accountrelationships.ListAccountRelationshipsResponse: + Response after trying to list account + relationships. """ - http_options = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_http_options() + http_options = ( + _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_http_options() + ) - request, metadata = self._interceptor.pre_list_account_relationships(request, metadata) - transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_account_relationships( + request, metadata + ) + transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountRelationshipsServiceClient.ListAccountRelationships", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": "ListAccountRelationships", "httpRequest": http_request, @@ -518,7 +617,14 @@ def __call__(self, ) # Send the request - response = AccountRelationshipsServiceRestTransport._ListAccountRelationships._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AccountRelationshipsServiceRestTransport._ListAccountRelationships._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -533,20 +639,28 @@ def __call__(self, resp = self._interceptor.post_list_account_relationships(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_account_relationships_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_account_relationships_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = accountrelationships.ListAccountRelationshipsResponse.to_json(response) + response_payload = ( + accountrelationships.ListAccountRelationshipsResponse.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.accounts_v1.AccountRelationshipsServiceClient.list_account_relationships", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": "ListAccountRelationships", "metadata": http_response["headers"], @@ -555,9 +669,14 @@ def __call__(self, ) return resp - class _UpdateAccountRelationship(_BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship, AccountRelationshipsServiceRestStub): + class _UpdateAccountRelationship( + _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship, + AccountRelationshipsServiceRestStub, + ): def __hash__(self): - return hash("AccountRelationshipsServiceRestTransport.UpdateAccountRelationship") + return hash( + "AccountRelationshipsServiceRestTransport.UpdateAccountRelationship" + ) @staticmethod def _get_response( @@ -567,86 +686,102 @@ 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: accountrelationships.UpdateAccountRelationshipRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountrelationships.AccountRelationship: + def __call__( + self, + request: accountrelationships.UpdateAccountRelationshipRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountrelationships.AccountRelationship: r"""Call the update account - relationship method over HTTP. - - Args: - request (~.accountrelationships.UpdateAccountRelationshipRequest): - The request object. Request message for the ``UpdateAccountRelationship`` - 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: - ~.accountrelationships.AccountRelationship: - The ``AccountRelationship`` message defines a formal - connection between a merchant's account and a service - provider's account. This relationship enables the - provider to offer specific services to the business, - such as product management or campaign management. It - specifies the access rights and permissions to the - business's data relevant to those services. - - Establishing an account relationship involves linking - the merchant's account with a provider's account. The - provider could be another Google account (like Google - Ads or Google My Business) or a third-party platform - (such as Shopify or WooCommerce). + relationship method over HTTP. + + Args: + request (~.accountrelationships.UpdateAccountRelationshipRequest): + The request object. Request message for the ``UpdateAccountRelationship`` + 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: + ~.accountrelationships.AccountRelationship: + The ``AccountRelationship`` message defines a formal + connection between a merchant's account and a service + provider's account. This relationship enables the + provider to offer specific services to the business, + such as product management or campaign management. It + specifies the access rights and permissions to the + business's data relevant to those services. + + Establishing an account relationship involves linking + the merchant's account with a provider's account. The + provider could be another Google account (like Google + Ads or Google My Business) or a third-party platform + (such as Shopify or WooCommerce). """ - http_options = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_http_options() + http_options = ( + _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_http_options() + ) - request, metadata = self._interceptor.pre_update_account_relationship(request, metadata) - transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_account_relationship( + request, metadata + ) + transcoded_request = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_transcoded_request( + http_options, request + ) - body = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_request_body_json(transcoded_request) + body = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountRelationshipsServiceClient.UpdateAccountRelationship", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": "UpdateAccountRelationship", "httpRequest": http_request, @@ -655,7 +790,15 @@ def __call__(self, ) # Send the request - response = AccountRelationshipsServiceRestTransport._UpdateAccountRelationship._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AccountRelationshipsServiceRestTransport._UpdateAccountRelationship._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. @@ -670,20 +813,26 @@ def __call__(self, resp = self._interceptor.post_update_account_relationship(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_account_relationship_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_account_relationship_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = accountrelationships.AccountRelationship.to_json(response) + response_payload = accountrelationships.AccountRelationship.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.accounts_v1.AccountRelationshipsServiceClient.update_account_relationship", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountRelationshipsService", "rpcName": "UpdateAccountRelationship", "metadata": http_response["headers"], @@ -693,28 +842,37 @@ def __call__(self, return resp @property - def get_account_relationship(self) -> Callable[ - [accountrelationships.GetAccountRelationshipRequest], - accountrelationships.AccountRelationship]: + def get_account_relationship( + self, + ) -> Callable[ + [accountrelationships.GetAccountRelationshipRequest], + accountrelationships.AccountRelationship, + ]: # 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._GetAccountRelationship(self._session, self._host, self._interceptor) # type: ignore + return self._GetAccountRelationship(self._session, self._host, self._interceptor) # type: ignore @property - def list_account_relationships(self) -> Callable[ - [accountrelationships.ListAccountRelationshipsRequest], - accountrelationships.ListAccountRelationshipsResponse]: + def list_account_relationships( + self, + ) -> Callable[ + [accountrelationships.ListAccountRelationshipsRequest], + accountrelationships.ListAccountRelationshipsResponse, + ]: # 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._ListAccountRelationships(self._session, self._host, self._interceptor) # type: ignore + return self._ListAccountRelationships(self._session, self._host, self._interceptor) # type: ignore @property - def update_account_relationship(self) -> Callable[ - [accountrelationships.UpdateAccountRelationshipRequest], - accountrelationships.AccountRelationship]: + def update_account_relationship( + self, + ) -> Callable[ + [accountrelationships.UpdateAccountRelationshipRequest], + accountrelationships.AccountRelationship, + ]: # 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._UpdateAccountRelationship(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateAccountRelationship(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -724,6 +882,4 @@ def close(self): self._session.close() -__all__=( - 'AccountRelationshipsServiceRestTransport', -) +__all__ = ("AccountRelationshipsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py index a7128850a38e..8e3043bf3858 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_relationships_service/transports/rest_base.py @@ -14,20 +14,20 @@ # 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 AccountRelationshipsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import accountrelationships +from .base import DEFAULT_CLIENT_INFO, AccountRelationshipsServiceTransport -class _BaseAccountRelationshipsServiceRestTransport(AccountRelationshipsServiceTransport): + +class _BaseAccountRelationshipsServiceRestTransport( + AccountRelationshipsServiceTransport +): """Base REST backend transport for AccountRelationshipsService. Note: This class is not meant to be used directly. Use its sync and @@ -40,14 +40,16 @@ class _BaseAccountRelationshipsServiceRestTransport(AccountRelationshipsServiceT 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]): @@ -71,7 +73,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +86,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 _BaseGetAccountRelationship: 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': '/accounts/v1/{name=accounts/*/relationships/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/relationships/*}", + }, ] return http_options @@ -113,11 +121,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(_BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._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( + _BaseAccountRelationshipsServiceRestTransport._BaseGetAccountRelationship._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,35 +140,47 @@ class _BaseListAccountRelationships: 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': '/accounts/v1/{parent=accounts/*}/relationships', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/relationships", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = accountrelationships.ListAccountRelationshipsRequest.pb(request) + pb_request = accountrelationships.ListAccountRelationshipsRequest.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(_BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._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( + _BaseAccountRelationshipsServiceRestTransport._BaseListAccountRelationships._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -163,26 +189,32 @@ class _BaseUpdateAccountRelationship: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{account_relationship.name=accounts/*/relationships/*}', - 'body': 'account_relationship', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{account_relationship.name=accounts/*/relationships/*}", + "body": "account_relationship", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = accountrelationships.UpdateAccountRelationshipRequest.pb(request) + pb_request = accountrelationships.UpdateAccountRelationshipRequest.pb( + request + ) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -191,22 +223,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._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( + _BaseAccountRelationshipsServiceRestTransport._BaseUpdateAccountRelationship._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseAccountRelationshipsServiceRestTransport', -) +__all__ = ("_BaseAccountRelationshipsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py index efc4082a21be..236ca6c7692e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AccountServicesServiceClient from .async_client import AccountServicesServiceAsyncClient +from .client import AccountServicesServiceClient __all__ = ( - 'AccountServicesServiceClient', - 'AccountServicesServiceAsyncClient', + "AccountServicesServiceClient", + "AccountServicesServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py index 58cc86a7124f..6ef5cedfe6c5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/async_client.py @@ -13,41 +13,56 @@ # 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_accounts_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_accounts_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_accounts_v1.services.account_services_service import pagers +from google.shopping.merchant_accounts_v1.services.account_services_service import ( + pagers, +) from google.shopping.merchant_accounts_v1.types import accountservices -from .transports.base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport + from .client import AccountServicesServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AccountServicesServiceTransport +from .transports.grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport 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 AccountServicesServiceAsyncClient: """Service to support AccountService API.""" @@ -62,18 +77,38 @@ class AccountServicesServiceAsyncClient: account_path = staticmethod(AccountServicesServiceClient.account_path) parse_account_path = staticmethod(AccountServicesServiceClient.parse_account_path) - account_service_path = staticmethod(AccountServicesServiceClient.account_service_path) - parse_account_service_path = staticmethod(AccountServicesServiceClient.parse_account_service_path) - common_billing_account_path = staticmethod(AccountServicesServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountServicesServiceClient.parse_common_billing_account_path) + account_service_path = staticmethod( + AccountServicesServiceClient.account_service_path + ) + parse_account_service_path = staticmethod( + AccountServicesServiceClient.parse_account_service_path + ) + common_billing_account_path = staticmethod( + AccountServicesServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AccountServicesServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(AccountServicesServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountServicesServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountServicesServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountServicesServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + AccountServicesServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AccountServicesServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AccountServicesServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(AccountServicesServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountServicesServiceClient.parse_common_project_path) - common_location_path = staticmethod(AccountServicesServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountServicesServiceClient.parse_common_location_path) + parse_common_project_path = staticmethod( + AccountServicesServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + AccountServicesServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + AccountServicesServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -109,7 +144,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: @@ -172,12 +209,20 @@ def universe_domain(self) -> str: get_transport_class = AccountServicesServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountServicesServiceTransport, Callable[..., AccountServicesServiceTransport]]] = "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, + AccountServicesServiceTransport, + Callable[..., AccountServicesServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the account services service async client. Args: @@ -232,31 +277,39 @@ 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.accounts_v1.AccountServicesServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", - "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.accounts.v1.AccountServicesService", "credentialsType": None, - } + }, ) - async def get_account_service(self, - request: Optional[Union[accountservices.GetAccountServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountservices.AccountService: + async def get_account_service( + self, + request: Optional[Union[accountservices.GetAccountServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Retrieve an account service. .. code-block:: python @@ -335,10 +388,14 @@ async def sample_get_account_service(): # - 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. @@ -352,14 +409,14 @@ async def sample_get_account_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_account_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_account_service + ] # 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. @@ -376,14 +433,17 @@ async def sample_get_account_service(): # Done; return the response. return response - async def list_account_services(self, - request: Optional[Union[accountservices.ListAccountServicesRequest, 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.ListAccountServicesAsyncPager: + async def list_account_services( + self, + request: Optional[ + Union[accountservices.ListAccountServicesRequest, 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.ListAccountServicesAsyncPager: r"""List account services for the specified accounts. Supports filtering. @@ -445,10 +505,14 @@ async def sample_list_account_services(): # - 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. @@ -462,14 +526,14 @@ async def sample_list_account_services(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_account_services] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_account_services + ] # 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. @@ -497,16 +561,19 @@ async def sample_list_account_services(): # Done; return the response. return response - async def propose_account_service(self, - request: Optional[Union[accountservices.ProposeAccountServiceRequest, dict]] = None, - *, - parent: Optional[str] = None, - provider: Optional[str] = None, - account_service: Optional[accountservices.AccountService] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountservices.AccountService: + async def propose_account_service( + self, + request: Optional[ + Union[accountservices.ProposeAccountServiceRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + provider: Optional[str] = None, + account_service: Optional[accountservices.AccountService] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Propose an account service. .. code-block:: python @@ -604,10 +671,14 @@ async def sample_propose_account_service(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, provider, account_service] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -625,14 +696,14 @@ async def sample_propose_account_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.propose_account_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.propose_account_service + ] # 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. @@ -649,14 +720,17 @@ async def sample_propose_account_service(): # Done; return the response. return response - async def approve_account_service(self, - request: Optional[Union[accountservices.ApproveAccountServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountservices.AccountService: + async def approve_account_service( + self, + request: Optional[ + Union[accountservices.ApproveAccountServiceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Approve an account service proposal. .. code-block:: python @@ -737,10 +811,14 @@ async def sample_approve_account_service(): # - 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. @@ -754,14 +832,14 @@ async def sample_approve_account_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.approve_account_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.approve_account_service + ] # 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. @@ -778,14 +856,17 @@ async def sample_approve_account_service(): # Done; return the response. return response - async def reject_account_service(self, - request: Optional[Union[accountservices.RejectAccountServiceRequest, dict]] = None, - *, - name: 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 reject_account_service( + self, + request: Optional[ + Union[accountservices.RejectAccountServiceRequest, dict] + ] = None, + *, + name: 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"""Reject an account service (both proposed and approve services can be rejected). @@ -835,10 +916,14 @@ async def sample_reject_account_service(): # - 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. @@ -852,14 +937,14 @@ async def sample_reject_account_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.reject_account_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reject_account_service + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -879,12 +964,13 @@ async def __aenter__(self) -> "AccountServicesServiceAsyncClient": 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__ = ( - "AccountServicesServiceAsyncClient", -) +__all__ = ("AccountServicesServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/client.py index 28ae78a24341..79cd2046aa10 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,15 +54,19 @@ 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_accounts_v1.services.account_services_service import pagers +from google.shopping.merchant_accounts_v1.services.account_services_service import ( + pagers, +) from google.shopping.merchant_accounts_v1.types import accountservices -from .transports.base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, AccountServicesServiceTransport from .transports.grpc import AccountServicesServiceGrpcTransport from .transports.grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport from .transports.rest import AccountServicesServiceRestTransport @@ -63,14 +79,18 @@ class AccountServicesServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AccountServicesServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AccountServicesServiceTransport]] _transport_registry["grpc"] = AccountServicesServiceGrpcTransport _transport_registry["grpc_asyncio"] = AccountServicesServiceGrpcAsyncIOTransport _transport_registry["rest"] = AccountServicesServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountServicesServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AccountServicesServiceTransport]: """Returns an appropriate transport class. Args: @@ -162,8 +182,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountServicesServiceClient: 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) @@ -180,84 +199,118 @@ def transport(self) -> AccountServicesServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def account_service_path(account: str,service: str,) -> str: + def account_service_path( + account: str, + service: str, + ) -> str: """Returns a fully-qualified account_service string.""" - return "accounts/{account}/services/{service}".format(account=account, service=service, ) + return "accounts/{account}/services/{service}".format( + account=account, + service=service, + ) @staticmethod - def parse_account_service_path(path: str) -> Dict[str,str]: + def parse_account_service_path(path: str) -> Dict[str, str]: """Parses a account_service path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/services/(?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: @@ -289,16 +342,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 @@ -311,7 +370,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 @@ -332,13 +393,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 @@ -361,7 +428,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: @@ -377,17 +446,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 = AccountServicesServiceClient._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 = AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + AccountServicesServiceClient._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: @@ -423,15 +502,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 @@ -464,12 +546,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountServicesServiceTransport, Callable[..., AccountServicesServiceTransport]]] = 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, + AccountServicesServiceTransport, + Callable[..., AccountServicesServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the account services service client. Args: @@ -524,14 +614,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 = AccountServicesServiceClient._read_environment_variables() - self._client_cert_source = AccountServicesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountServicesServiceClient._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, + ) = AccountServicesServiceClient._read_environment_variables() + self._client_cert_source = AccountServicesServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AccountServicesServiceClient._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 @@ -542,7 +642,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 @@ -551,8 +653,10 @@ def __init__(self, *, if transport_provided: # transport is a AccountServicesServiceTransport 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 " @@ -561,20 +665,30 @@ def __init__(self, *, self._transport = cast(AccountServicesServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AccountServicesServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AccountServicesServiceClient._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[AccountServicesServiceTransport], Callable[..., AccountServicesServiceTransport]] = ( + transport_init: Union[ + Type[AccountServicesServiceTransport], + Callable[..., AccountServicesServiceTransport], + ] = ( AccountServicesServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AccountServicesServiceTransport], transport) @@ -593,28 +707,37 @@ 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.accounts_v1.AccountServicesServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", - "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.accounts.v1.AccountServicesService", "credentialsType": None, - } + }, ) - def get_account_service(self, - request: Optional[Union[accountservices.GetAccountServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountservices.AccountService: + def get_account_service( + self, + request: Optional[Union[accountservices.GetAccountServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Retrieve an account service. .. code-block:: python @@ -693,10 +816,14 @@ def sample_get_account_service(): # - 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. @@ -714,9 +841,7 @@ def sample_get_account_service(): # 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. @@ -733,14 +858,17 @@ def sample_get_account_service(): # Done; return the response. return response - def list_account_services(self, - request: Optional[Union[accountservices.ListAccountServicesRequest, 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.ListAccountServicesPager: + def list_account_services( + self, + request: Optional[ + Union[accountservices.ListAccountServicesRequest, 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.ListAccountServicesPager: r"""List account services for the specified accounts. Supports filtering. @@ -802,10 +930,14 @@ def sample_list_account_services(): # - 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. @@ -823,9 +955,7 @@ def sample_list_account_services(): # 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. @@ -853,16 +983,19 @@ def sample_list_account_services(): # Done; return the response. return response - def propose_account_service(self, - request: Optional[Union[accountservices.ProposeAccountServiceRequest, dict]] = None, - *, - parent: Optional[str] = None, - provider: Optional[str] = None, - account_service: Optional[accountservices.AccountService] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountservices.AccountService: + def propose_account_service( + self, + request: Optional[ + Union[accountservices.ProposeAccountServiceRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + provider: Optional[str] = None, + account_service: Optional[accountservices.AccountService] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Propose an account service. .. code-block:: python @@ -960,10 +1093,14 @@ def sample_propose_account_service(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, provider, account_service] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -985,9 +1122,7 @@ def sample_propose_account_service(): # 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. @@ -1004,14 +1139,17 @@ def sample_propose_account_service(): # Done; return the response. return response - def approve_account_service(self, - request: Optional[Union[accountservices.ApproveAccountServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accountservices.AccountService: + def approve_account_service( + self, + request: Optional[ + Union[accountservices.ApproveAccountServiceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Approve an account service proposal. .. code-block:: python @@ -1092,10 +1230,14 @@ def sample_approve_account_service(): # - 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. @@ -1113,9 +1255,7 @@ def sample_approve_account_service(): # 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. @@ -1132,14 +1272,17 @@ def sample_approve_account_service(): # Done; return the response. return response - def reject_account_service(self, - request: Optional[Union[accountservices.RejectAccountServiceRequest, dict]] = None, - *, - name: 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 reject_account_service( + self, + request: Optional[ + Union[accountservices.RejectAccountServiceRequest, dict] + ] = None, + *, + name: 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"""Reject an account service (both proposed and approve services can be rejected). @@ -1189,10 +1332,14 @@ def sample_reject_account_service(): # - 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. @@ -1210,9 +1357,7 @@ def sample_reject_account_service(): # 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. @@ -1240,16 +1385,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__ = ( - "AccountServicesServiceClient", -) +__all__ = ("AccountServicesServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py index 9c6b3e52eaf5..767d18cf05c1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_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 ListAccountServicesPager: 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[..., accountservices.ListAccountServicesResponse], - request: accountservices.ListAccountServicesRequest, - response: accountservices.ListAccountServicesResponse, - *, - 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[..., accountservices.ListAccountServicesResponse], + request: accountservices.ListAccountServicesRequest, + response: accountservices.ListAccountServicesResponse, + *, + 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[accountservices.ListAccountServicesResponse]: 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[accountservices.AccountService]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[accountservices.AccountService]: yield from page.account_services 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 ListAccountServicesAsyncPager: @@ -112,14 +134,17 @@ class ListAccountServicesAsyncPager: 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[accountservices.ListAccountServicesResponse]], - request: accountservices.ListAccountServicesRequest, - response: accountservices.ListAccountServicesResponse, - *, - 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[accountservices.ListAccountServicesResponse]], + request: accountservices.ListAccountServicesRequest, + response: accountservices.ListAccountServicesResponse, + *, + 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[accountservices.ListAccountServicesRespon 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[accountservices.AccountService]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py index 51c38ac42781..c2af51bb2b8d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import AccountServicesServiceTransport from .grpc import AccountServicesServiceGrpcTransport from .grpc_asyncio import AccountServicesServiceGrpcAsyncIOTransport -from .rest import AccountServicesServiceRestTransport -from .rest import AccountServicesServiceRestInterceptor - +from .rest import ( + AccountServicesServiceRestInterceptor, + AccountServicesServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AccountServicesServiceTransport]] -_transport_registry['grpc'] = AccountServicesServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountServicesServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountServicesServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[AccountServicesServiceTransport]] +_transport_registry["grpc"] = AccountServicesServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AccountServicesServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AccountServicesServiceRestTransport __all__ = ( - 'AccountServicesServiceTransport', - 'AccountServicesServiceGrpcTransport', - 'AccountServicesServiceGrpcAsyncIOTransport', - 'AccountServicesServiceRestTransport', - 'AccountServicesServiceRestInterceptor', + "AccountServicesServiceTransport", + "AccountServicesServiceGrpcTransport", + "AccountServicesServiceGrpcAsyncIOTransport", + "AccountServicesServiceRestTransport", + "AccountServicesServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py index dd1d691bdd22..aedcd00408b1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import accountservices -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 AccountServicesServiceTransport(abc.ABC): """Abstract transport class for AccountServicesService.""" - 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 @@ -150,60 +158,69 @@ 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 get_account_service(self) -> Callable[ - [accountservices.GetAccountServiceRequest], - Union[ - accountservices.AccountService, - Awaitable[accountservices.AccountService] - ]]: + def get_account_service( + self, + ) -> Callable[ + [accountservices.GetAccountServiceRequest], + Union[ + accountservices.AccountService, Awaitable[accountservices.AccountService] + ], + ]: raise NotImplementedError() @property - def list_account_services(self) -> Callable[ - [accountservices.ListAccountServicesRequest], - Union[ - accountservices.ListAccountServicesResponse, - Awaitable[accountservices.ListAccountServicesResponse] - ]]: + def list_account_services( + self, + ) -> Callable[ + [accountservices.ListAccountServicesRequest], + Union[ + accountservices.ListAccountServicesResponse, + Awaitable[accountservices.ListAccountServicesResponse], + ], + ]: raise NotImplementedError() @property - def propose_account_service(self) -> Callable[ - [accountservices.ProposeAccountServiceRequest], - Union[ - accountservices.AccountService, - Awaitable[accountservices.AccountService] - ]]: + def propose_account_service( + self, + ) -> Callable[ + [accountservices.ProposeAccountServiceRequest], + Union[ + accountservices.AccountService, Awaitable[accountservices.AccountService] + ], + ]: raise NotImplementedError() @property - def approve_account_service(self) -> Callable[ - [accountservices.ApproveAccountServiceRequest], - Union[ - accountservices.AccountService, - Awaitable[accountservices.AccountService] - ]]: + def approve_account_service( + self, + ) -> Callable[ + [accountservices.ApproveAccountServiceRequest], + Union[ + accountservices.AccountService, Awaitable[accountservices.AccountService] + ], + ]: raise NotImplementedError() @property - def reject_account_service(self) -> Callable[ - [accountservices.RejectAccountServiceRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def reject_account_service( + self, + ) -> Callable[ + [accountservices.RejectAccountServiceRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -211,6 +228,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AccountServicesServiceTransport', -) +__all__ = ("AccountServicesServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py index f009ad51edf7..082697b249a6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_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_accounts_v1.types import accountservices -from .base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountServicesServiceTransport 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.accounts.v1.AccountServicesService", "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.accounts.v1.AccountServicesService", "rpcName": client_call_details.method, "response": grpc_response, @@ -114,23 +120,26 @@ class AccountServicesServiceGrpcTransport(AccountServicesServiceTransport): 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,20 @@ 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 get_account_service(self) -> Callable[ - [accountservices.GetAccountServiceRequest], - accountservices.AccountService]: + def get_account_service( + self, + ) -> Callable[ + [accountservices.GetAccountServiceRequest], accountservices.AccountService + ]: r"""Return a callable for the get account service method over gRPC. Retrieve an account service. @@ -326,18 +340,21 @@ def get_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_account_service' not in self._stubs: - self._stubs['get_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/GetAccountService', + if "get_account_service" not in self._stubs: + self._stubs["get_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/GetAccountService", request_serializer=accountservices.GetAccountServiceRequest.serialize, response_deserializer=accountservices.AccountService.deserialize, ) - return self._stubs['get_account_service'] + return self._stubs["get_account_service"] @property - def list_account_services(self) -> Callable[ - [accountservices.ListAccountServicesRequest], - accountservices.ListAccountServicesResponse]: + def list_account_services( + self, + ) -> Callable[ + [accountservices.ListAccountServicesRequest], + accountservices.ListAccountServicesResponse, + ]: r"""Return a callable for the list account services method over gRPC. List account services for the specified accounts. @@ -353,18 +370,20 @@ def list_account_services(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_account_services' not in self._stubs: - self._stubs['list_account_services'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/ListAccountServices', + if "list_account_services" not in self._stubs: + self._stubs["list_account_services"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/ListAccountServices", request_serializer=accountservices.ListAccountServicesRequest.serialize, response_deserializer=accountservices.ListAccountServicesResponse.deserialize, ) - return self._stubs['list_account_services'] + return self._stubs["list_account_services"] @property - def propose_account_service(self) -> Callable[ - [accountservices.ProposeAccountServiceRequest], - accountservices.AccountService]: + def propose_account_service( + self, + ) -> Callable[ + [accountservices.ProposeAccountServiceRequest], accountservices.AccountService + ]: r"""Return a callable for the propose account service method over gRPC. Propose an account service. @@ -379,18 +398,20 @@ def propose_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'propose_account_service' not in self._stubs: - self._stubs['propose_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/ProposeAccountService', + if "propose_account_service" not in self._stubs: + self._stubs["propose_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/ProposeAccountService", request_serializer=accountservices.ProposeAccountServiceRequest.serialize, response_deserializer=accountservices.AccountService.deserialize, ) - return self._stubs['propose_account_service'] + return self._stubs["propose_account_service"] @property - def approve_account_service(self) -> Callable[ - [accountservices.ApproveAccountServiceRequest], - accountservices.AccountService]: + def approve_account_service( + self, + ) -> Callable[ + [accountservices.ApproveAccountServiceRequest], accountservices.AccountService + ]: r"""Return a callable for the approve account service method over gRPC. Approve an account service proposal. @@ -405,18 +426,18 @@ def approve_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'approve_account_service' not in self._stubs: - self._stubs['approve_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/ApproveAccountService', + if "approve_account_service" not in self._stubs: + self._stubs["approve_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/ApproveAccountService", request_serializer=accountservices.ApproveAccountServiceRequest.serialize, response_deserializer=accountservices.AccountService.deserialize, ) - return self._stubs['approve_account_service'] + return self._stubs["approve_account_service"] @property - def reject_account_service(self) -> Callable[ - [accountservices.RejectAccountServiceRequest], - empty_pb2.Empty]: + def reject_account_service( + self, + ) -> Callable[[accountservices.RejectAccountServiceRequest], empty_pb2.Empty]: r"""Return a callable for the reject account service method over gRPC. Reject an account service (both proposed and approve @@ -432,13 +453,13 @@ def reject_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'reject_account_service' not in self._stubs: - self._stubs['reject_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/RejectAccountService', + if "reject_account_service" not in self._stubs: + self._stubs["reject_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/RejectAccountService", request_serializer=accountservices.RejectAccountServiceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['reject_account_service'] + return self._stubs["reject_account_service"] def close(self): self._logged_channel.close() @@ -448,6 +469,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AccountServicesServiceGrpcTransport', -) +__all__ = ("AccountServicesServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py index 9e23f8c0f3c1..bae04f620789 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_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_accounts_v1.types import accountservices -from .base import AccountServicesServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountServicesServiceTransport from .grpc import AccountServicesServiceGrpcTransport 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.accounts.v1.AccountServicesService", "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.accounts.v1.AccountServicesService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -123,13 +131,15 @@ class AccountServicesServiceGrpcAsyncIOTransport(AccountServicesServiceTransport _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 get_account_service(self) -> Callable[ - [accountservices.GetAccountServiceRequest], - Awaitable[accountservices.AccountService]]: + def get_account_service( + self, + ) -> Callable[ + [accountservices.GetAccountServiceRequest], + Awaitable[accountservices.AccountService], + ]: r"""Return a callable for the get account service method over gRPC. Retrieve an account service. @@ -332,18 +349,21 @@ def get_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_account_service' not in self._stubs: - self._stubs['get_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/GetAccountService', + if "get_account_service" not in self._stubs: + self._stubs["get_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/GetAccountService", request_serializer=accountservices.GetAccountServiceRequest.serialize, response_deserializer=accountservices.AccountService.deserialize, ) - return self._stubs['get_account_service'] + return self._stubs["get_account_service"] @property - def list_account_services(self) -> Callable[ - [accountservices.ListAccountServicesRequest], - Awaitable[accountservices.ListAccountServicesResponse]]: + def list_account_services( + self, + ) -> Callable[ + [accountservices.ListAccountServicesRequest], + Awaitable[accountservices.ListAccountServicesResponse], + ]: r"""Return a callable for the list account services method over gRPC. List account services for the specified accounts. @@ -359,18 +379,21 @@ def list_account_services(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_account_services' not in self._stubs: - self._stubs['list_account_services'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/ListAccountServices', + if "list_account_services" not in self._stubs: + self._stubs["list_account_services"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/ListAccountServices", request_serializer=accountservices.ListAccountServicesRequest.serialize, response_deserializer=accountservices.ListAccountServicesResponse.deserialize, ) - return self._stubs['list_account_services'] + return self._stubs["list_account_services"] @property - def propose_account_service(self) -> Callable[ - [accountservices.ProposeAccountServiceRequest], - Awaitable[accountservices.AccountService]]: + def propose_account_service( + self, + ) -> Callable[ + [accountservices.ProposeAccountServiceRequest], + Awaitable[accountservices.AccountService], + ]: r"""Return a callable for the propose account service method over gRPC. Propose an account service. @@ -385,18 +408,21 @@ def propose_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'propose_account_service' not in self._stubs: - self._stubs['propose_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/ProposeAccountService', + if "propose_account_service" not in self._stubs: + self._stubs["propose_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/ProposeAccountService", request_serializer=accountservices.ProposeAccountServiceRequest.serialize, response_deserializer=accountservices.AccountService.deserialize, ) - return self._stubs['propose_account_service'] + return self._stubs["propose_account_service"] @property - def approve_account_service(self) -> Callable[ - [accountservices.ApproveAccountServiceRequest], - Awaitable[accountservices.AccountService]]: + def approve_account_service( + self, + ) -> Callable[ + [accountservices.ApproveAccountServiceRequest], + Awaitable[accountservices.AccountService], + ]: r"""Return a callable for the approve account service method over gRPC. Approve an account service proposal. @@ -411,18 +437,20 @@ def approve_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'approve_account_service' not in self._stubs: - self._stubs['approve_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/ApproveAccountService', + if "approve_account_service" not in self._stubs: + self._stubs["approve_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/ApproveAccountService", request_serializer=accountservices.ApproveAccountServiceRequest.serialize, response_deserializer=accountservices.AccountService.deserialize, ) - return self._stubs['approve_account_service'] + return self._stubs["approve_account_service"] @property - def reject_account_service(self) -> Callable[ - [accountservices.RejectAccountServiceRequest], - Awaitable[empty_pb2.Empty]]: + def reject_account_service( + self, + ) -> Callable[ + [accountservices.RejectAccountServiceRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the reject account service method over gRPC. Reject an account service (both proposed and approve @@ -438,16 +466,16 @@ def reject_account_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'reject_account_service' not in self._stubs: - self._stubs['reject_account_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountServicesService/RejectAccountService', + if "reject_account_service" not in self._stubs: + self._stubs["reject_account_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountServicesService/RejectAccountService", request_serializer=accountservices.RejectAccountServiceRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['reject_account_service'] + return self._stubs["reject_account_service"] 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.get_account_service: self._wrap_method( self.get_account_service, @@ -489,6 +517,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'AccountServicesServiceGrpcAsyncIOTransport', -) +__all__ = ("AccountServicesServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py similarity index 70% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py index c5fc207721aa..4eb2005aed06 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_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_accounts_v1.types import accountservices - -from .rest_base import _BaseAccountServicesServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAccountServicesServiceRestTransport 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 @@ -119,7 +114,15 @@ def pre_reject_account_service(self, request, metadata): """ - def pre_approve_account_service(self, request: accountservices.ApproveAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ApproveAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_approve_account_service( + self, + request: accountservices.ApproveAccountServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountservices.ApproveAccountServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for approve_account_service Override in a subclass to manipulate the request or metadata @@ -127,7 +130,9 @@ def pre_approve_account_service(self, request: accountservices.ApproveAccountSer """ return request, metadata - def post_approve_account_service(self, response: accountservices.AccountService) -> accountservices.AccountService: + def post_approve_account_service( + self, response: accountservices.AccountService + ) -> accountservices.AccountService: """Post-rpc interceptor for approve_account_service DEPRECATED. Please use the `post_approve_account_service_with_metadata` @@ -140,7 +145,11 @@ def post_approve_account_service(self, response: accountservices.AccountService) """ return response - def post_approve_account_service_with_metadata(self, response: accountservices.AccountService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_approve_account_service_with_metadata( + self, + response: accountservices.AccountService, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for approve_account_service Override in a subclass to read or manipulate the response or metadata after it @@ -155,7 +164,14 @@ def post_approve_account_service_with_metadata(self, response: accountservices.A """ return response, metadata - def pre_get_account_service(self, request: accountservices.GetAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.GetAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_account_service( + self, + request: accountservices.GetAccountServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountservices.GetAccountServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_account_service Override in a subclass to manipulate the request or metadata @@ -163,7 +179,9 @@ def pre_get_account_service(self, request: accountservices.GetAccountServiceRequ """ return request, metadata - def post_get_account_service(self, response: accountservices.AccountService) -> accountservices.AccountService: + def post_get_account_service( + self, response: accountservices.AccountService + ) -> accountservices.AccountService: """Post-rpc interceptor for get_account_service DEPRECATED. Please use the `post_get_account_service_with_metadata` @@ -176,7 +194,11 @@ def post_get_account_service(self, response: accountservices.AccountService) -> """ return response - def post_get_account_service_with_metadata(self, response: accountservices.AccountService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_account_service_with_metadata( + self, + response: accountservices.AccountService, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_account_service Override in a subclass to read or manipulate the response or metadata after it @@ -191,7 +213,14 @@ def post_get_account_service_with_metadata(self, response: accountservices.Accou """ return response, metadata - def pre_list_account_services(self, request: accountservices.ListAccountServicesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ListAccountServicesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_account_services( + self, + request: accountservices.ListAccountServicesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountservices.ListAccountServicesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_account_services Override in a subclass to manipulate the request or metadata @@ -199,7 +228,9 @@ def pre_list_account_services(self, request: accountservices.ListAccountServices """ return request, metadata - def post_list_account_services(self, response: accountservices.ListAccountServicesResponse) -> accountservices.ListAccountServicesResponse: + def post_list_account_services( + self, response: accountservices.ListAccountServicesResponse + ) -> accountservices.ListAccountServicesResponse: """Post-rpc interceptor for list_account_services DEPRECATED. Please use the `post_list_account_services_with_metadata` @@ -212,7 +243,14 @@ def post_list_account_services(self, response: accountservices.ListAccountServic """ return response - def post_list_account_services_with_metadata(self, response: accountservices.ListAccountServicesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ListAccountServicesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_account_services_with_metadata( + self, + response: accountservices.ListAccountServicesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountservices.ListAccountServicesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_account_services Override in a subclass to read or manipulate the response or metadata after it @@ -227,7 +265,14 @@ def post_list_account_services_with_metadata(self, response: accountservices.Lis """ return response, metadata - def pre_propose_account_service(self, request: accountservices.ProposeAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.ProposeAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_propose_account_service( + self, + request: accountservices.ProposeAccountServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountservices.ProposeAccountServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for propose_account_service Override in a subclass to manipulate the request or metadata @@ -235,7 +280,9 @@ def pre_propose_account_service(self, request: accountservices.ProposeAccountSer """ return request, metadata - def post_propose_account_service(self, response: accountservices.AccountService) -> accountservices.AccountService: + def post_propose_account_service( + self, response: accountservices.AccountService + ) -> accountservices.AccountService: """Post-rpc interceptor for propose_account_service DEPRECATED. Please use the `post_propose_account_service_with_metadata` @@ -248,7 +295,11 @@ def post_propose_account_service(self, response: accountservices.AccountService) """ return response - def post_propose_account_service_with_metadata(self, response: accountservices.AccountService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_propose_account_service_with_metadata( + self, + response: accountservices.AccountService, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accountservices.AccountService, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for propose_account_service Override in a subclass to read or manipulate the response or metadata after it @@ -263,7 +314,14 @@ def post_propose_account_service_with_metadata(self, response: accountservices.A """ return response, metadata - def pre_reject_account_service(self, request: accountservices.RejectAccountServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accountservices.RejectAccountServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_reject_account_service( + self, + request: accountservices.RejectAccountServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accountservices.RejectAccountServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for reject_account_service Override in a subclass to manipulate the request or metadata @@ -291,20 +349,21 @@ class AccountServicesServiceRestTransport(_BaseAccountServicesServiceRestTranspo 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[AccountServicesServiceRestInterceptor] = 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[AccountServicesServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -347,16 +406,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 AccountServicesServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _ApproveAccountService(_BaseAccountServicesServiceRestTransport._BaseApproveAccountService, AccountServicesServiceRestStub): + class _ApproveAccountService( + _BaseAccountServicesServiceRestTransport._BaseApproveAccountService, + AccountServicesServiceRestStub, + ): def __hash__(self): return hash("AccountServicesServiceRestTransport.ApproveAccountService") @@ -368,27 +431,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: accountservices.ApproveAccountServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountservices.AccountService: + def __call__( + self, + request: accountservices.ApproveAccountServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Call the approve account service method over HTTP. Args: @@ -433,32 +498,46 @@ def __call__(self, """ - http_options = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_http_options() + http_options = ( + _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_http_options() + ) - request, metadata = self._interceptor.pre_approve_account_service(request, metadata) - transcoded_request = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_approve_account_service( + request, metadata + ) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_transcoded_request( + http_options, request + ) - body = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_request_body_json(transcoded_request) + body = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.ApproveAccountService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "ApproveAccountService", "httpRequest": http_request, @@ -467,7 +546,15 @@ def __call__(self, ) # Send the request - response = AccountServicesServiceRestTransport._ApproveAccountService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AccountServicesServiceRestTransport._ApproveAccountService._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. @@ -482,20 +569,24 @@ def __call__(self, resp = self._interceptor.post_approve_account_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_approve_account_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_approve_account_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accountservices.AccountService.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.accounts_v1.AccountServicesServiceClient.approve_account_service", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "ApproveAccountService", "metadata": http_response["headers"], @@ -504,7 +595,10 @@ def __call__(self, ) return resp - class _GetAccountService(_BaseAccountServicesServiceRestTransport._BaseGetAccountService, AccountServicesServiceRestStub): + class _GetAccountService( + _BaseAccountServicesServiceRestTransport._BaseGetAccountService, + AccountServicesServiceRestStub, + ): def __hash__(self): return hash("AccountServicesServiceRestTransport.GetAccountService") @@ -516,26 +610,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: accountservices.GetAccountServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountservices.AccountService: + def __call__( + self, + request: accountservices.GetAccountServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Call the get account service method over HTTP. Args: @@ -579,30 +675,42 @@ def __call__(self, """ - http_options = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_http_options() + http_options = ( + _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_http_options() + ) - request, metadata = self._interceptor.pre_get_account_service(request, metadata) - transcoded_request = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_account_service( + request, metadata + ) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.GetAccountService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "GetAccountService", "httpRequest": http_request, @@ -611,7 +719,16 @@ def __call__(self, ) # Send the request - response = AccountServicesServiceRestTransport._GetAccountService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AccountServicesServiceRestTransport._GetAccountService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -626,20 +743,24 @@ def __call__(self, resp = self._interceptor.post_get_account_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_account_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_account_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accountservices.AccountService.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.accounts_v1.AccountServicesServiceClient.get_account_service", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "GetAccountService", "metadata": http_response["headers"], @@ -648,7 +769,10 @@ def __call__(self, ) return resp - class _ListAccountServices(_BaseAccountServicesServiceRestTransport._BaseListAccountServices, AccountServicesServiceRestStub): + class _ListAccountServices( + _BaseAccountServicesServiceRestTransport._BaseListAccountServices, + AccountServicesServiceRestStub, + ): def __hash__(self): return hash("AccountServicesServiceRestTransport.ListAccountServices") @@ -660,26 +784,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: accountservices.ListAccountServicesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountservices.ListAccountServicesResponse: + def __call__( + self, + request: accountservices.ListAccountServicesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.ListAccountServicesResponse: r"""Call the list account services method over HTTP. Args: @@ -700,30 +826,42 @@ def __call__(self, """ - http_options = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_http_options() + http_options = ( + _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_http_options() + ) - request, metadata = self._interceptor.pre_list_account_services(request, metadata) - transcoded_request = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_account_services( + request, metadata + ) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.ListAccountServices", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "ListAccountServices", "httpRequest": http_request, @@ -732,7 +870,16 @@ def __call__(self, ) # Send the request - response = AccountServicesServiceRestTransport._ListAccountServices._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AccountServicesServiceRestTransport._ListAccountServices._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -747,20 +894,26 @@ def __call__(self, resp = self._interceptor.post_list_account_services(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_account_services_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_account_services_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = accountservices.ListAccountServicesResponse.to_json(response) + response_payload = ( + accountservices.ListAccountServicesResponse.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.accounts_v1.AccountServicesServiceClient.list_account_services", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "ListAccountServices", "metadata": http_response["headers"], @@ -769,7 +922,10 @@ def __call__(self, ) return resp - class _ProposeAccountService(_BaseAccountServicesServiceRestTransport._BaseProposeAccountService, AccountServicesServiceRestStub): + class _ProposeAccountService( + _BaseAccountServicesServiceRestTransport._BaseProposeAccountService, + AccountServicesServiceRestStub, + ): def __hash__(self): return hash("AccountServicesServiceRestTransport.ProposeAccountService") @@ -781,27 +937,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: accountservices.ProposeAccountServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accountservices.AccountService: + def __call__( + self, + request: accountservices.ProposeAccountServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accountservices.AccountService: r"""Call the propose account service method over HTTP. Args: @@ -846,32 +1004,46 @@ def __call__(self, """ - http_options = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_http_options() + http_options = ( + _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_http_options() + ) - request, metadata = self._interceptor.pre_propose_account_service(request, metadata) - transcoded_request = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_propose_account_service( + request, metadata + ) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_transcoded_request( + http_options, request + ) - body = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_request_body_json(transcoded_request) + body = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.ProposeAccountService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "ProposeAccountService", "httpRequest": http_request, @@ -880,7 +1052,15 @@ def __call__(self, ) # Send the request - response = AccountServicesServiceRestTransport._ProposeAccountService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AccountServicesServiceRestTransport._ProposeAccountService._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. @@ -895,20 +1075,24 @@ def __call__(self, resp = self._interceptor.post_propose_account_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_propose_account_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_propose_account_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accountservices.AccountService.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.accounts_v1.AccountServicesServiceClient.propose_account_service", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "ProposeAccountService", "metadata": http_response["headers"], @@ -917,7 +1101,10 @@ def __call__(self, ) return resp - class _RejectAccountService(_BaseAccountServicesServiceRestTransport._BaseRejectAccountService, AccountServicesServiceRestStub): + class _RejectAccountService( + _BaseAccountServicesServiceRestTransport._BaseRejectAccountService, + AccountServicesServiceRestStub, + ): def __hash__(self): return hash("AccountServicesServiceRestTransport.RejectAccountService") @@ -929,27 +1116,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: accountservices.RejectAccountServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: accountservices.RejectAccountServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the reject account service method over HTTP. Args: @@ -964,32 +1153,46 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_http_options() + http_options = ( + _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_http_options() + ) - request, metadata = self._interceptor.pre_reject_account_service(request, metadata) - transcoded_request = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_reject_account_service( + request, metadata + ) + transcoded_request = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_transcoded_request( + http_options, request + ) - body = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_request_body_json(transcoded_request) + body = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountServicesServiceClient.RejectAccountService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountServicesService", "rpcName": "RejectAccountService", "httpRequest": http_request, @@ -998,7 +1201,17 @@ def __call__(self, ) # Send the request - response = AccountServicesServiceRestTransport._RejectAccountService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AccountServicesServiceRestTransport._RejectAccountService._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. @@ -1006,44 +1219,53 @@ def __call__(self, raise core_exceptions.from_http_response(response) @property - def approve_account_service(self) -> Callable[ - [accountservices.ApproveAccountServiceRequest], - accountservices.AccountService]: + def approve_account_service( + self, + ) -> Callable[ + [accountservices.ApproveAccountServiceRequest], accountservices.AccountService + ]: # 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._ApproveAccountService(self._session, self._host, self._interceptor) # type: ignore + return self._ApproveAccountService(self._session, self._host, self._interceptor) # type: ignore @property - def get_account_service(self) -> Callable[ - [accountservices.GetAccountServiceRequest], - accountservices.AccountService]: + def get_account_service( + self, + ) -> Callable[ + [accountservices.GetAccountServiceRequest], accountservices.AccountService + ]: # 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._GetAccountService(self._session, self._host, self._interceptor) # type: ignore + return self._GetAccountService(self._session, self._host, self._interceptor) # type: ignore @property - def list_account_services(self) -> Callable[ - [accountservices.ListAccountServicesRequest], - accountservices.ListAccountServicesResponse]: + def list_account_services( + self, + ) -> Callable[ + [accountservices.ListAccountServicesRequest], + accountservices.ListAccountServicesResponse, + ]: # 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._ListAccountServices(self._session, self._host, self._interceptor) # type: ignore + return self._ListAccountServices(self._session, self._host, self._interceptor) # type: ignore @property - def propose_account_service(self) -> Callable[ - [accountservices.ProposeAccountServiceRequest], - accountservices.AccountService]: + def propose_account_service( + self, + ) -> Callable[ + [accountservices.ProposeAccountServiceRequest], accountservices.AccountService + ]: # 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._ProposeAccountService(self._session, self._host, self._interceptor) # type: ignore + return self._ProposeAccountService(self._session, self._host, self._interceptor) # type: ignore @property - def reject_account_service(self) -> Callable[ - [accountservices.RejectAccountServiceRequest], - empty_pb2.Empty]: + def reject_account_service( + self, + ) -> Callable[[accountservices.RejectAccountServiceRequest], 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._RejectAccountService(self._session, self._host, self._interceptor) # type: ignore + return self._RejectAccountService(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -1053,6 +1275,4 @@ def close(self): self._session.close() -__all__=( - 'AccountServicesServiceRestTransport', -) +__all__ = ("AccountServicesServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py index 8861b1a075e0..8c5817b7fc50 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/account_services_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/account_services_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 AccountServicesServiceTransport, 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_accounts_v1.types import accountservices +from .base import DEFAULT_CLIENT_INFO, AccountServicesServiceTransport + class _BaseAccountServicesServiceRestTransport(AccountServicesServiceTransport): """Base REST backend transport for AccountServicesService. @@ -41,14 +39,16 @@ class _BaseAccountServicesServiceRestTransport(AccountServicesServiceTransport): 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,27 +85,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseApproveAccountService: 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': '/accounts/v1/{name=accounts/*/services/*}:approve', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/services/*}:approve", + "body": "*", + }, ] return http_options @@ -118,17 +124,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(_BaseAccountServicesServiceRestTransport._BaseApproveAccountService._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( + _BaseAccountServicesServiceRestTransport._BaseApproveAccountService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -137,19 +149,23 @@ class _BaseGetAccountService: 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': '/accounts/v1/{name=accounts/*/services/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/services/*}", + }, ] return http_options @@ -161,11 +177,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(_BaseAccountServicesServiceRestTransport._BaseGetAccountService._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( + _BaseAccountServicesServiceRestTransport._BaseGetAccountService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,19 +196,23 @@ class _BaseListAccountServices: 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': '/accounts/v1/{parent=accounts/*}/services', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/services", + }, ] return http_options @@ -198,11 +224,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(_BaseAccountServicesServiceRestTransport._BaseListAccountServices._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( + _BaseAccountServicesServiceRestTransport._BaseListAccountServices._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -211,20 +243,24 @@ class _BaseProposeAccountService: 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': '/accounts/v1/{parent=accounts/*}/services:propose', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/services:propose", + "body": "*", + }, ] return http_options @@ -239,17 +275,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(_BaseAccountServicesServiceRestTransport._BaseProposeAccountService._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( + _BaseAccountServicesServiceRestTransport._BaseProposeAccountService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -258,20 +300,24 @@ class _BaseRejectAccountService: 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': '/accounts/v1/{name=accounts/*/services/*}:reject', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/services/*}:reject", + "body": "*", + }, ] return http_options @@ -286,22 +332,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAccountServicesServiceRestTransport._BaseRejectAccountService._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( + _BaseAccountServicesServiceRestTransport._BaseRejectAccountService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseAccountServicesServiceRestTransport', -) +__all__ = ("_BaseAccountServicesServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py index 5115ab24752a..bfa586948c88 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AccountsServiceClient from .async_client import AccountsServiceAsyncClient +from .client import AccountsServiceClient __all__ = ( - 'AccountsServiceClient', - 'AccountsServiceAsyncClient', + "AccountsServiceClient", + "AccountsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py index 137050836009..0b4787ffac78 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,21 +45,25 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.accounts_service import pagers from google.shopping.merchant_accounts_v1.types import accounts -from google.type import datetime_pb2 # type: ignore -from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport + from .client import AccountsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AccountsServiceTransport +from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport 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 AccountsServiceAsyncClient: """Service to support Accounts API.""" @@ -66,16 +80,30 @@ class AccountsServiceAsyncClient: parse_account_path = staticmethod(AccountsServiceClient.parse_account_path) user_path = staticmethod(AccountsServiceClient.user_path) parse_user_path = staticmethod(AccountsServiceClient.parse_user_path) - common_billing_account_path = staticmethod(AccountsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AccountsServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + AccountsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AccountsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(AccountsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AccountsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AccountsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AccountsServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + AccountsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AccountsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AccountsServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(AccountsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AccountsServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + AccountsServiceClient.parse_common_project_path + ) common_location_path = staticmethod(AccountsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AccountsServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + AccountsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -111,7 +139,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: @@ -174,12 +204,18 @@ def universe_domain(self) -> str: get_transport_class = AccountsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = "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, AccountsServiceTransport, Callable[..., AccountsServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the accounts service async client. Args: @@ -234,31 +270,39 @@ 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.accounts_v1.AccountsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", - "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.accounts.v1.AccountsService", "credentialsType": None, - } + }, ) - async def get_account(self, - request: Optional[Union[accounts.GetAccountRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: + async def get_account( + self, + request: Optional[Union[accounts.GetAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Retrieves an account from your Merchant Center account. After inserting, updating, or deleting an account, it may take several minutes before changes take @@ -333,10 +377,14 @@ async def sample_get_account(): # - 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. @@ -350,14 +398,14 @@ async def sample_get_account(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_account] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_account + ] # 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. @@ -374,13 +422,16 @@ async def sample_get_account(): # Done; return the response. return response - async def create_and_configure_account(self, - request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: + async def create_and_configure_account( + self, + request: Optional[ + Union[accounts.CreateAndConfigureAccountRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Creates a Merchant Center account with additional configuration. Adds the user that makes the request as an admin for the new account. @@ -456,7 +507,9 @@ async def sample_create_and_configure_account(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_and_configure_account] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_and_configure_account + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -472,14 +525,15 @@ async def sample_create_and_configure_account(): # Done; return the response. return response - async def delete_account(self, - request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, - *, - name: 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_account( + self, + request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, + *, + name: 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 account regardless of its type: standalone, advanced account or sub-account. Deleting an advanced account leads to the deletion of all of its @@ -533,10 +587,14 @@ async def sample_delete_account(): # - 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. @@ -550,14 +608,14 @@ async def sample_delete_account(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_account] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_account + ] # 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. @@ -571,15 +629,16 @@ async def sample_delete_account(): metadata=metadata, ) - async def update_account(self, - request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, - *, - account: Optional[accounts.Account] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: + async def update_account( + self, + request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, + *, + account: Optional[accounts.Account] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Updates an account regardless of its type: standalone, advanced account or sub-account. Executing this method requires admin access. @@ -671,10 +730,14 @@ async def sample_update_account(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [account, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -690,14 +753,16 @@ async def sample_update_account(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_account] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_account + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account.name", request.account.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("account.name", request.account.name),) + ), ) # Validate the universe domain. @@ -714,13 +779,14 @@ async def sample_update_account(): # Done; return the response. return response - async def list_accounts(self, - request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAccountsAsyncPager: + async def list_accounts( + self, + request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAccountsAsyncPager: r"""Note: For the ``accounts.list`` method, quota and limits usage are charged for each user, and not for the Merchant Center ID or the advanced account ID. To list several sub-accounts, you @@ -780,7 +846,9 @@ async def sample_list_accounts(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_accounts] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_accounts + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -807,14 +875,15 @@ async def sample_list_accounts(): # Done; return the response. return response - async def list_sub_accounts(self, - request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, - *, - provider: 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.ListSubAccountsAsyncPager: + async def list_sub_accounts( + self, + request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, + *, + provider: 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.ListSubAccountsAsyncPager: r"""List all sub-accounts for a given advanced account. This is a convenience wrapper for the more powerful ``accounts.list`` method. This method will produce the same results as calling @@ -878,10 +947,14 @@ async def sample_list_sub_accounts(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [provider] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -895,14 +968,14 @@ async def sample_list_sub_accounts(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_sub_accounts] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_sub_accounts + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("provider", request.provider), - )), + gapic_v1.routing_header.to_grpc_metadata((("provider", request.provider),)), ) # Validate the universe domain. @@ -936,12 +1009,13 @@ async def __aenter__(self) -> "AccountsServiceAsyncClient": 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__ = ( - "AccountsServiceAsyncClient", -) +__all__ = ("AccountsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/client.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/client.py index 344dc5ed02d0..1974399d9c63 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,10 +62,12 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.accounts_service import pagers from google.shopping.merchant_accounts_v1.types import accounts -from google.type import datetime_pb2 # type: ignore -from .transports.base import AccountsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, AccountsServiceTransport from .transports.grpc import AccountsServiceGrpcTransport from .transports.grpc_asyncio import AccountsServiceGrpcAsyncIOTransport from .transports.rest import AccountsServiceRestTransport @@ -65,14 +80,18 @@ class AccountsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AccountsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AccountsServiceTransport]] _transport_registry["grpc"] = AccountsServiceGrpcTransport _transport_registry["grpc_asyncio"] = AccountsServiceGrpcAsyncIOTransport _transport_registry["rest"] = AccountsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AccountsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AccountsServiceTransport]: """Returns an appropriate transport class. Args: @@ -164,8 +183,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AccountsServiceClient: 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) @@ -182,84 +200,118 @@ def transport(self) -> AccountsServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def user_path(account: str,email: str,) -> str: + def user_path( + account: str, + email: str, + ) -> str: """Returns a fully-qualified user string.""" - return "accounts/{account}/users/{email}".format(account=account, email=email, ) + return "accounts/{account}/users/{email}".format( + account=account, + email=email, + ) @staticmethod - def parse_user_path(path: str) -> Dict[str,str]: + def parse_user_path(path: str) -> Dict[str, str]: """Parses a user path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/users/(?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: @@ -291,16 +343,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 @@ -313,7 +371,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 @@ -334,13 +394,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 @@ -363,7 +429,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: @@ -379,17 +447,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = AccountsServiceClient._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 = AccountsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = AccountsServiceClient._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: @@ -425,15 +501,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 @@ -466,12 +545,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AccountsServiceTransport, Callable[..., AccountsServiceTransport]]] = 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, AccountsServiceTransport, Callable[..., AccountsServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the accounts service client. Args: @@ -526,14 +611,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 = AccountsServiceClient._read_environment_variables() - self._client_cert_source = AccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AccountsServiceClient._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, + ) = AccountsServiceClient._read_environment_variables() + self._client_cert_source = AccountsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AccountsServiceClient._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 @@ -544,7 +639,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 @@ -553,8 +650,10 @@ def __init__(self, *, if transport_provided: # transport is a AccountsServiceTransport 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 " @@ -563,20 +662,29 @@ def __init__(self, *, self._transport = cast(AccountsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AccountsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AccountsServiceClient._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[AccountsServiceTransport], Callable[..., AccountsServiceTransport]] = ( + transport_init: Union[ + Type[AccountsServiceTransport], Callable[..., AccountsServiceTransport] + ] = ( AccountsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AccountsServiceTransport], transport) @@ -595,28 +703,37 @@ 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.accounts_v1.AccountsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", - "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.accounts.v1.AccountsService", "credentialsType": None, - } + }, ) - def get_account(self, - request: Optional[Union[accounts.GetAccountRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: + def get_account( + self, + request: Optional[Union[accounts.GetAccountRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Retrieves an account from your Merchant Center account. After inserting, updating, or deleting an account, it may take several minutes before changes take @@ -691,10 +808,14 @@ def sample_get_account(): # - 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. @@ -712,9 +833,7 @@ def sample_get_account(): # 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. @@ -731,13 +850,16 @@ def sample_get_account(): # Done; return the response. return response - def create_and_configure_account(self, - request: Optional[Union[accounts.CreateAndConfigureAccountRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: + def create_and_configure_account( + self, + request: Optional[ + Union[accounts.CreateAndConfigureAccountRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Creates a Merchant Center account with additional configuration. Adds the user that makes the request as an admin for the new account. @@ -813,7 +935,9 @@ def sample_create_and_configure_account(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_and_configure_account] + rpc = self._transport._wrapped_methods[ + self._transport.create_and_configure_account + ] # Validate the universe domain. self._validate_universe_domain() @@ -829,14 +953,15 @@ def sample_create_and_configure_account(): # Done; return the response. return response - def delete_account(self, - request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, - *, - name: 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_account( + self, + request: Optional[Union[accounts.DeleteAccountRequest, dict]] = None, + *, + name: 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 account regardless of its type: standalone, advanced account or sub-account. Deleting an advanced account leads to the deletion of all of its @@ -890,10 +1015,14 @@ def sample_delete_account(): # - 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. @@ -911,9 +1040,7 @@ def sample_delete_account(): # 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. @@ -927,15 +1054,16 @@ def sample_delete_account(): metadata=metadata, ) - def update_account(self, - request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, - *, - account: Optional[accounts.Account] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> accounts.Account: + def update_account( + self, + request: Optional[Union[accounts.UpdateAccountRequest, dict]] = None, + *, + account: Optional[accounts.Account] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Updates an account regardless of its type: standalone, advanced account or sub-account. Executing this method requires admin access. @@ -1027,10 +1155,14 @@ def sample_update_account(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [account, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1050,9 +1182,9 @@ def sample_update_account(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("account.name", request.account.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("account.name", request.account.name),) + ), ) # Validate the universe domain. @@ -1069,13 +1201,14 @@ def sample_update_account(): # Done; return the response. return response - def list_accounts(self, - request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListAccountsPager: + def list_accounts( + self, + request: Optional[Union[accounts.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAccountsPager: r"""Note: For the ``accounts.list`` method, quota and limits usage are charged for each user, and not for the Merchant Center ID or the advanced account ID. To list several sub-accounts, you @@ -1162,14 +1295,15 @@ def sample_list_accounts(): # Done; return the response. return response - def list_sub_accounts(self, - request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, - *, - provider: 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.ListSubAccountsPager: + def list_sub_accounts( + self, + request: Optional[Union[accounts.ListSubAccountsRequest, dict]] = None, + *, + provider: 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.ListSubAccountsPager: r"""List all sub-accounts for a given advanced account. This is a convenience wrapper for the more powerful ``accounts.list`` method. This method will produce the same results as calling @@ -1233,10 +1367,14 @@ def sample_list_sub_accounts(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [provider] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1254,9 +1392,7 @@ def sample_list_sub_accounts(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("provider", request.provider), - )), + gapic_v1.routing_header.to_grpc_metadata((("provider", request.provider),)), ) # Validate the universe domain. @@ -1298,16 +1434,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__ = ( - "AccountsServiceClient", -) +__all__ = ("AccountsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py index b96de6c53897..3f8e1a419215 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_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 ListAccountsPager: 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[..., accounts.ListAccountsResponse], - request: accounts.ListAccountsRequest, - response: accounts.ListAccountsResponse, - *, - 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[..., accounts.ListAccountsResponse], + request: accounts.ListAccountsRequest, + response: accounts.ListAccountsResponse, + *, + 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[accounts.ListAccountsResponse]: 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[accounts.Account]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[accounts.Account]: yield from page.accounts 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 ListAccountsAsyncPager: @@ -112,14 +134,17 @@ class ListAccountsAsyncPager: 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[accounts.ListAccountsResponse]], - request: accounts.ListAccountsRequest, - response: accounts.ListAccountsResponse, - *, - 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[accounts.ListAccountsResponse]], + request: accounts.ListAccountsRequest, + response: accounts.ListAccountsResponse, + *, + 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[accounts.ListAccountsResponse]: 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[accounts.Account]: async def async_generator(): async for page in self.pages: @@ -163,7 +194,7 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListSubAccountsPager: @@ -183,14 +214,17 @@ class ListSubAccountsPager: 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[..., accounts.ListSubAccountsResponse], - request: accounts.ListSubAccountsRequest, - response: accounts.ListSubAccountsResponse, - *, - 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[..., accounts.ListSubAccountsResponse], + request: accounts.ListSubAccountsRequest, + response: accounts.ListSubAccountsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiate the pager. Args: @@ -223,7 +257,12 @@ def pages(self) -> Iterator[accounts.ListSubAccountsResponse]: 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[accounts.Account]: @@ -231,7 +270,7 @@ def __iter__(self) -> Iterator[accounts.Account]: yield from page.accounts 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 ListSubAccountsAsyncPager: @@ -251,14 +290,17 @@ class ListSubAccountsAsyncPager: 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[accounts.ListSubAccountsResponse]], - request: accounts.ListSubAccountsRequest, - response: accounts.ListSubAccountsResponse, - *, - 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[accounts.ListSubAccountsResponse]], + request: accounts.ListSubAccountsRequest, + response: accounts.ListSubAccountsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): """Instantiates the pager. Args: @@ -291,8 +333,14 @@ async def pages(self) -> AsyncIterator[accounts.ListSubAccountsResponse]: 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[accounts.Account]: async def async_generator(): async for page in self.pages: @@ -302,4 +350,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-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py index 36cbcd559b5e..d58da4a0980e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/accounts_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import AccountsServiceTransport from .grpc import AccountsServiceGrpcTransport from .grpc_asyncio import AccountsServiceGrpcAsyncIOTransport -from .rest import AccountsServiceRestTransport -from .rest import AccountsServiceRestInterceptor - +from .rest import AccountsServiceRestInterceptor, AccountsServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[AccountsServiceTransport]] -_transport_registry['grpc'] = AccountsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AccountsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AccountsServiceRestTransport +_transport_registry["grpc"] = AccountsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AccountsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AccountsServiceRestTransport __all__ = ( - 'AccountsServiceTransport', - 'AccountsServiceGrpcTransport', - 'AccountsServiceGrpcAsyncIOTransport', - 'AccountsServiceRestTransport', - 'AccountsServiceRestInterceptor', + "AccountsServiceTransport", + "AccountsServiceGrpcTransport", + "AccountsServiceGrpcAsyncIOTransport", + "AccountsServiceRestTransport", + "AccountsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py index 2709aec9f8d0..881a3f5b3e87 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import accounts -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 AccountsServiceTransport(abc.ABC): """Abstract transport class for AccountsService.""" - 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 @@ -155,69 +163,72 @@ 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 get_account(self) -> Callable[ - [accounts.GetAccountRequest], - Union[ - accounts.Account, - Awaitable[accounts.Account] - ]]: + def get_account( + self, + ) -> Callable[ + [accounts.GetAccountRequest], + Union[accounts.Account, Awaitable[accounts.Account]], + ]: raise NotImplementedError() @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - Union[ - accounts.Account, - Awaitable[accounts.Account] - ]]: + def create_and_configure_account( + self, + ) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], + Union[accounts.Account, Awaitable[accounts.Account]], + ]: raise NotImplementedError() @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_account( + self, + ) -> Callable[ + [accounts.DeleteAccountRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - Union[ - accounts.Account, - Awaitable[accounts.Account] - ]]: + def update_account( + self, + ) -> Callable[ + [accounts.UpdateAccountRequest], + Union[accounts.Account, Awaitable[accounts.Account]], + ]: raise NotImplementedError() @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - Union[ - accounts.ListAccountsResponse, - Awaitable[accounts.ListAccountsResponse] - ]]: + def list_accounts( + self, + ) -> Callable[ + [accounts.ListAccountsRequest], + Union[accounts.ListAccountsResponse, Awaitable[accounts.ListAccountsResponse]], + ]: raise NotImplementedError() @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - Union[ - accounts.ListSubAccountsResponse, - Awaitable[accounts.ListSubAccountsResponse] - ]]: + def list_sub_accounts( + self, + ) -> Callable[ + [accounts.ListSubAccountsRequest], + Union[ + accounts.ListSubAccountsResponse, + Awaitable[accounts.ListSubAccountsResponse], + ], + ]: raise NotImplementedError() @property @@ -225,6 +236,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AccountsServiceTransport', -) +__all__ = ("AccountsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py index 47ccf95f96ad..ba853015de79 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_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_accounts_v1.types import accounts -from .base import AccountsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountsServiceTransport 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.accounts.v1.AccountsService", "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.accounts.v1.AccountsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -114,23 +120,26 @@ class AccountsServiceGrpcTransport(AccountsServiceTransport): 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,16 @@ 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 get_account(self) -> Callable[ - [accounts.GetAccountRequest], - accounts.Account]: + def get_account(self) -> Callable[[accounts.GetAccountRequest], accounts.Account]: r"""Return a callable for the get account method over gRPC. Retrieves an account from your Merchant Center @@ -329,18 +339,18 @@ def get_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_account' not in self._stubs: - self._stubs['get_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/GetAccount', + if "get_account" not in self._stubs: + self._stubs["get_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/GetAccount", request_serializer=accounts.GetAccountRequest.serialize, response_deserializer=accounts.Account.deserialize, ) - return self._stubs['get_account'] + return self._stubs["get_account"] @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - accounts.Account]: + def create_and_configure_account( + self, + ) -> Callable[[accounts.CreateAndConfigureAccountRequest], accounts.Account]: r"""Return a callable for the create and configure account method over gRPC. Creates a Merchant Center account with additional @@ -357,18 +367,20 @@ def create_and_configure_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_and_configure_account' not in self._stubs: - self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/CreateAndConfigureAccount', + if "create_and_configure_account" not in self._stubs: + self._stubs[ + "create_and_configure_account" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/CreateAndConfigureAccount", request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, response_deserializer=accounts.Account.deserialize, ) - return self._stubs['create_and_configure_account'] + return self._stubs["create_and_configure_account"] @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - empty_pb2.Empty]: + def delete_account( + self, + ) -> Callable[[accounts.DeleteAccountRequest], empty_pb2.Empty]: r"""Return a callable for the delete account method over gRPC. Deletes the specified account regardless of its type: @@ -389,18 +401,18 @@ def delete_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_account' not in self._stubs: - self._stubs['delete_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/DeleteAccount', + if "delete_account" not in self._stubs: + self._stubs["delete_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/DeleteAccount", request_serializer=accounts.DeleteAccountRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_account'] + return self._stubs["delete_account"] @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - accounts.Account]: + def update_account( + self, + ) -> Callable[[accounts.UpdateAccountRequest], accounts.Account]: r"""Return a callable for the update account method over gRPC. Updates an account regardless of its type: @@ -417,18 +429,18 @@ def update_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_account' not in self._stubs: - self._stubs['update_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/UpdateAccount', + if "update_account" not in self._stubs: + self._stubs["update_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/UpdateAccount", request_serializer=accounts.UpdateAccountRequest.serialize, response_deserializer=accounts.Account.deserialize, ) - return self._stubs['update_account'] + return self._stubs["update_account"] @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - accounts.ListAccountsResponse]: + def list_accounts( + self, + ) -> Callable[[accounts.ListAccountsRequest], accounts.ListAccountsResponse]: r"""Return a callable for the list accounts method over gRPC. Note: For the ``accounts.list`` method, quota and limits usage @@ -447,18 +459,18 @@ def list_accounts(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_accounts' not in self._stubs: - self._stubs['list_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/ListAccounts', + if "list_accounts" not in self._stubs: + self._stubs["list_accounts"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/ListAccounts", request_serializer=accounts.ListAccountsRequest.serialize, response_deserializer=accounts.ListAccountsResponse.deserialize, ) - return self._stubs['list_accounts'] + return self._stubs["list_accounts"] @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - accounts.ListSubAccountsResponse]: + def list_sub_accounts( + self, + ) -> Callable[[accounts.ListSubAccountsRequest], accounts.ListSubAccountsResponse]: r"""Return a callable for the list sub accounts method over gRPC. List all sub-accounts for a given advanced account. This is a @@ -477,13 +489,13 @@ def list_sub_accounts(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_sub_accounts' not in self._stubs: - self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/ListSubAccounts', + if "list_sub_accounts" not in self._stubs: + self._stubs["list_sub_accounts"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/ListSubAccounts", request_serializer=accounts.ListSubAccountsRequest.serialize, response_deserializer=accounts.ListSubAccountsResponse.deserialize, ) - return self._stubs['list_sub_accounts'] + return self._stubs["list_sub_accounts"] def close(self): self._logged_channel.close() @@ -493,6 +505,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AccountsServiceGrpcTransport', -) +__all__ = ("AccountsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py index e51bdf24f15a..7c8985783a02 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_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_accounts_v1.types import accounts -from .base import AccountsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AccountsServiceTransport from .grpc import AccountsServiceGrpcTransport 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.accounts.v1.AccountsService", "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.accounts.v1.AccountsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -123,13 +131,15 @@ class AccountsServiceGrpcAsyncIOTransport(AccountsServiceTransport): _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,9 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_account(self) -> Callable[ - [accounts.GetAccountRequest], - Awaitable[accounts.Account]]: + def get_account( + self, + ) -> Callable[[accounts.GetAccountRequest], Awaitable[accounts.Account]]: r"""Return a callable for the get account method over gRPC. Retrieves an account from your Merchant Center @@ -335,18 +349,20 @@ def get_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_account' not in self._stubs: - self._stubs['get_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/GetAccount', + if "get_account" not in self._stubs: + self._stubs["get_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/GetAccount", request_serializer=accounts.GetAccountRequest.serialize, response_deserializer=accounts.Account.deserialize, ) - return self._stubs['get_account'] + return self._stubs["get_account"] @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - Awaitable[accounts.Account]]: + def create_and_configure_account( + self, + ) -> Callable[ + [accounts.CreateAndConfigureAccountRequest], Awaitable[accounts.Account] + ]: r"""Return a callable for the create and configure account method over gRPC. Creates a Merchant Center account with additional @@ -363,18 +379,20 @@ def create_and_configure_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_and_configure_account' not in self._stubs: - self._stubs['create_and_configure_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/CreateAndConfigureAccount', + if "create_and_configure_account" not in self._stubs: + self._stubs[ + "create_and_configure_account" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/CreateAndConfigureAccount", request_serializer=accounts.CreateAndConfigureAccountRequest.serialize, response_deserializer=accounts.Account.deserialize, ) - return self._stubs['create_and_configure_account'] + return self._stubs["create_and_configure_account"] @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - Awaitable[empty_pb2.Empty]]: + def delete_account( + self, + ) -> Callable[[accounts.DeleteAccountRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete account method over gRPC. Deletes the specified account regardless of its type: @@ -395,18 +413,18 @@ def delete_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_account' not in self._stubs: - self._stubs['delete_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/DeleteAccount', + if "delete_account" not in self._stubs: + self._stubs["delete_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/DeleteAccount", request_serializer=accounts.DeleteAccountRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_account'] + return self._stubs["delete_account"] @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - Awaitable[accounts.Account]]: + def update_account( + self, + ) -> Callable[[accounts.UpdateAccountRequest], Awaitable[accounts.Account]]: r"""Return a callable for the update account method over gRPC. Updates an account regardless of its type: @@ -423,18 +441,20 @@ def update_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_account' not in self._stubs: - self._stubs['update_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/UpdateAccount', + if "update_account" not in self._stubs: + self._stubs["update_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/UpdateAccount", request_serializer=accounts.UpdateAccountRequest.serialize, response_deserializer=accounts.Account.deserialize, ) - return self._stubs['update_account'] + return self._stubs["update_account"] @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - Awaitable[accounts.ListAccountsResponse]]: + def list_accounts( + self, + ) -> Callable[ + [accounts.ListAccountsRequest], Awaitable[accounts.ListAccountsResponse] + ]: r"""Return a callable for the list accounts method over gRPC. Note: For the ``accounts.list`` method, quota and limits usage @@ -453,18 +473,20 @@ def list_accounts(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_accounts' not in self._stubs: - self._stubs['list_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/ListAccounts', + if "list_accounts" not in self._stubs: + self._stubs["list_accounts"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/ListAccounts", request_serializer=accounts.ListAccountsRequest.serialize, response_deserializer=accounts.ListAccountsResponse.deserialize, ) - return self._stubs['list_accounts'] + return self._stubs["list_accounts"] @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - Awaitable[accounts.ListSubAccountsResponse]]: + def list_sub_accounts( + self, + ) -> Callable[ + [accounts.ListSubAccountsRequest], Awaitable[accounts.ListSubAccountsResponse] + ]: r"""Return a callable for the list sub accounts method over gRPC. List all sub-accounts for a given advanced account. This is a @@ -483,16 +505,16 @@ def list_sub_accounts(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_sub_accounts' not in self._stubs: - self._stubs['list_sub_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AccountsService/ListSubAccounts', + if "list_sub_accounts" not in self._stubs: + self._stubs["list_sub_accounts"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AccountsService/ListSubAccounts", request_serializer=accounts.ListSubAccountsRequest.serialize, response_deserializer=accounts.ListSubAccountsResponse.deserialize, ) - return self._stubs['list_sub_accounts'] + return self._stubs["list_sub_accounts"] 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.get_account: self._wrap_method( self.get_account, @@ -539,6 +561,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'AccountsServiceGrpcAsyncIOTransport', -) +__all__ = ("AccountsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py index 16d7ea6a4261..3579871d951b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_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_accounts_v1.types import accounts - -from .rest_base import _BaseAccountsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAccountsServiceRestTransport 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 @@ -127,7 +122,15 @@ def post_update_account(self, response): """ - def pre_create_and_configure_account(self, request: accounts.CreateAndConfigureAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.CreateAndConfigureAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_and_configure_account( + self, + request: accounts.CreateAndConfigureAccountRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accounts.CreateAndConfigureAccountRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_and_configure_account Override in a subclass to manipulate the request or metadata @@ -135,7 +138,9 @@ def pre_create_and_configure_account(self, request: accounts.CreateAndConfigureA """ return request, metadata - def post_create_and_configure_account(self, response: accounts.Account) -> accounts.Account: + def post_create_and_configure_account( + self, response: accounts.Account + ) -> accounts.Account: """Post-rpc interceptor for create_and_configure_account DEPRECATED. Please use the `post_create_and_configure_account_with_metadata` @@ -148,7 +153,11 @@ def post_create_and_configure_account(self, response: accounts.Account) -> accou """ return response - def post_create_and_configure_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_and_configure_account_with_metadata( + self, + response: accounts.Account, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_and_configure_account Override in a subclass to read or manipulate the response or metadata after it @@ -163,7 +172,11 @@ def post_create_and_configure_account_with_metadata(self, response: accounts.Acc """ return response, metadata - def pre_delete_account(self, request: accounts.DeleteAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_account( + self, + request: accounts.DeleteAccountRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.DeleteAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_account Override in a subclass to manipulate the request or metadata @@ -171,7 +184,11 @@ def pre_delete_account(self, request: accounts.DeleteAccountRequest, metadata: S """ return request, metadata - def pre_get_account(self, request: accounts.GetAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_account( + self, + request: accounts.GetAccountRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.GetAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_account Override in a subclass to manipulate the request or metadata @@ -192,7 +209,11 @@ def post_get_account(self, response: accounts.Account) -> accounts.Account: """ return response - def post_get_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_account_with_metadata( + self, + response: accounts.Account, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_account Override in a subclass to read or manipulate the response or metadata after it @@ -207,7 +228,11 @@ def post_get_account_with_metadata(self, response: accounts.Account, metadata: S """ return response, metadata - def pre_list_accounts(self, request: accounts.ListAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_accounts( + self, + request: accounts.ListAccountsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.ListAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_accounts Override in a subclass to manipulate the request or metadata @@ -215,7 +240,9 @@ def pre_list_accounts(self, request: accounts.ListAccountsRequest, metadata: Seq """ return request, metadata - def post_list_accounts(self, response: accounts.ListAccountsResponse) -> accounts.ListAccountsResponse: + def post_list_accounts( + self, response: accounts.ListAccountsResponse + ) -> accounts.ListAccountsResponse: """Post-rpc interceptor for list_accounts DEPRECATED. Please use the `post_list_accounts_with_metadata` @@ -228,7 +255,11 @@ def post_list_accounts(self, response: accounts.ListAccountsResponse) -> account """ return response - def post_list_accounts_with_metadata(self, response: accounts.ListAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_accounts_with_metadata( + self, + response: accounts.ListAccountsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.ListAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_accounts Override in a subclass to read or manipulate the response or metadata after it @@ -243,7 +274,13 @@ def post_list_accounts_with_metadata(self, response: accounts.ListAccountsRespon """ return response, metadata - def pre_list_sub_accounts(self, request: accounts.ListSubAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_sub_accounts( + self, + request: accounts.ListSubAccountsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accounts.ListSubAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_sub_accounts Override in a subclass to manipulate the request or metadata @@ -251,7 +288,9 @@ def pre_list_sub_accounts(self, request: accounts.ListSubAccountsRequest, metada """ return request, metadata - def post_list_sub_accounts(self, response: accounts.ListSubAccountsResponse) -> accounts.ListSubAccountsResponse: + def post_list_sub_accounts( + self, response: accounts.ListSubAccountsResponse + ) -> accounts.ListSubAccountsResponse: """Post-rpc interceptor for list_sub_accounts DEPRECATED. Please use the `post_list_sub_accounts_with_metadata` @@ -264,7 +303,13 @@ def post_list_sub_accounts(self, response: accounts.ListSubAccountsResponse) -> """ return response - def post_list_sub_accounts_with_metadata(self, response: accounts.ListSubAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.ListSubAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_sub_accounts_with_metadata( + self, + response: accounts.ListSubAccountsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + accounts.ListSubAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_sub_accounts Override in a subclass to read or manipulate the response or metadata after it @@ -279,7 +324,11 @@ def post_list_sub_accounts_with_metadata(self, response: accounts.ListSubAccount """ return response, metadata - def pre_update_account(self, request: accounts.UpdateAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_account( + self, + request: accounts.UpdateAccountRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.UpdateAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_account Override in a subclass to manipulate the request or metadata @@ -300,7 +349,11 @@ def post_update_account(self, response: accounts.Account) -> accounts.Account: """ return response - def post_update_account_with_metadata(self, response: accounts.Account, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_account_with_metadata( + self, + response: accounts.Account, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[accounts.Account, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_account Override in a subclass to read or manipulate the response or metadata after it @@ -335,20 +388,21 @@ class AccountsServiceRestTransport(_BaseAccountsServiceRestTransport): 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[AccountsServiceRestInterceptor] = 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[AccountsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -391,16 +445,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 AccountsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateAndConfigureAccount(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount, AccountsServiceRestStub): + class _CreateAndConfigureAccount( + _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount, + AccountsServiceRestStub, + ): def __hash__(self): return hash("AccountsServiceRestTransport.CreateAndConfigureAccount") @@ -412,89 +470,105 @@ 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: accounts.CreateAndConfigureAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.Account: + def __call__( + self, + request: accounts.CreateAndConfigureAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Call the create and configure - account method over HTTP. - - Args: - request (~.accounts.CreateAndConfigureAccountRequest): - The request object. Request message for the ``CreateAndConfigureAccount`` - 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: - ~.accounts.Account: - The ``Account`` message represents a business's account - within Shopping Ads. It's the primary entity for - managing product data, settings, and interactions with - Google's services and external providers. - - Accounts can operate as standalone entities or be part - of a advanced account structure. In an advanced account - setup the parent account manages multiple sub-accounts. - - Establishing an account involves configuring attributes - like the account name, time zone, and language - preferences. - - The ``Account`` message is the parent entity for many - other resources, for example, ``AccountRelationship``, - ``Homepage``, ``BusinessInfo`` and so on. + account method over HTTP. + + Args: + request (~.accounts.CreateAndConfigureAccountRequest): + The request object. Request message for the ``CreateAndConfigureAccount`` + 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: + ~.accounts.Account: + The ``Account`` message represents a business's account + within Shopping Ads. It's the primary entity for + managing product data, settings, and interactions with + Google's services and external providers. + + Accounts can operate as standalone entities or be part + of a advanced account structure. In an advanced account + setup the parent account manages multiple sub-accounts. + + Establishing an account involves configuring attributes + like the account name, time zone, and language + preferences. + + The ``Account`` message is the parent entity for many + other resources, for example, ``AccountRelationship``, + ``Homepage``, ``BusinessInfo`` and so on. """ - http_options = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_http_options() + http_options = ( + _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_http_options() + ) - request, metadata = self._interceptor.pre_create_and_configure_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_and_configure_account( + request, metadata + ) + transcoded_request = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_transcoded_request( + http_options, request + ) - body = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_request_body_json(transcoded_request) + body = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.CreateAndConfigureAccount", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "CreateAndConfigureAccount", "httpRequest": http_request, @@ -503,7 +577,17 @@ def __call__(self, ) # Send the request - response = AccountsServiceRestTransport._CreateAndConfigureAccount._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + AccountsServiceRestTransport._CreateAndConfigureAccount._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -518,20 +602,24 @@ def __call__(self, resp = self._interceptor.post_create_and_configure_account(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_and_configure_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_and_configure_account_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accounts.Account.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.accounts_v1.AccountsServiceClient.create_and_configure_account", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "CreateAndConfigureAccount", "metadata": http_response["headers"], @@ -540,7 +628,9 @@ def __call__(self, ) return resp - class _DeleteAccount(_BaseAccountsServiceRestTransport._BaseDeleteAccount, AccountsServiceRestStub): + class _DeleteAccount( + _BaseAccountsServiceRestTransport._BaseDeleteAccount, AccountsServiceRestStub + ): def __hash__(self): return hash("AccountsServiceRestTransport.DeleteAccount") @@ -552,26 +642,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: accounts.DeleteAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: accounts.DeleteAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete account method over HTTP. Args: @@ -586,30 +678,40 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_http_options() + http_options = ( + _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_http_options() + ) request, metadata = self._interceptor.pre_delete_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_transcoded_request(http_options, request) + transcoded_request = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.DeleteAccount", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "DeleteAccount", "httpRequest": http_request, @@ -618,14 +720,23 @@ def __call__(self, ) # Send the request - response = AccountsServiceRestTransport._DeleteAccount._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AccountsServiceRestTransport._DeleteAccount._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 _GetAccount(_BaseAccountsServiceRestTransport._BaseGetAccount, AccountsServiceRestStub): + class _GetAccount( + _BaseAccountsServiceRestTransport._BaseGetAccount, AccountsServiceRestStub + ): def __hash__(self): return hash("AccountsServiceRestTransport.GetAccount") @@ -637,26 +748,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: accounts.GetAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.Account: + def __call__( + self, + request: accounts.GetAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Call the get account method over HTTP. Args: @@ -691,30 +804,40 @@ def __call__(self, """ - http_options = _BaseAccountsServiceRestTransport._BaseGetAccount._get_http_options() + http_options = ( + _BaseAccountsServiceRestTransport._BaseGetAccount._get_http_options() + ) request, metadata = self._interceptor.pre_get_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseGetAccount._get_transcoded_request(http_options, request) + transcoded_request = _BaseAccountsServiceRestTransport._BaseGetAccount._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseGetAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountsServiceRestTransport._BaseGetAccount._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.GetAccount", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "GetAccount", "httpRequest": http_request, @@ -723,7 +846,14 @@ def __call__(self, ) # Send the request - response = AccountsServiceRestTransport._GetAccount._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AccountsServiceRestTransport._GetAccount._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -738,20 +868,24 @@ def __call__(self, resp = self._interceptor.post_get_account(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_account_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accounts.Account.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.accounts_v1.AccountsServiceClient.get_account", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "GetAccount", "metadata": http_response["headers"], @@ -760,7 +894,9 @@ def __call__(self, ) return resp - class _ListAccounts(_BaseAccountsServiceRestTransport._BaseListAccounts, AccountsServiceRestStub): + class _ListAccounts( + _BaseAccountsServiceRestTransport._BaseListAccounts, AccountsServiceRestStub + ): def __hash__(self): return hash("AccountsServiceRestTransport.ListAccounts") @@ -772,26 +908,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: accounts.ListAccountsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.ListAccountsResponse: + def __call__( + self, + request: accounts.ListAccountsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.ListAccountsResponse: r"""Call the list accounts method over HTTP. Args: @@ -810,30 +948,40 @@ def __call__(self, Response message for the ``accounts.list`` method. """ - http_options = _BaseAccountsServiceRestTransport._BaseListAccounts._get_http_options() + http_options = ( + _BaseAccountsServiceRestTransport._BaseListAccounts._get_http_options() + ) request, metadata = self._interceptor.pre_list_accounts(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseListAccounts._get_transcoded_request(http_options, request) + transcoded_request = _BaseAccountsServiceRestTransport._BaseListAccounts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseListAccounts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountsServiceRestTransport._BaseListAccounts._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.ListAccounts", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "ListAccounts", "httpRequest": http_request, @@ -842,7 +990,14 @@ def __call__(self, ) # Send the request - response = AccountsServiceRestTransport._ListAccounts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AccountsServiceRestTransport._ListAccounts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -857,20 +1012,24 @@ def __call__(self, resp = self._interceptor.post_list_accounts(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_accounts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_accounts_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accounts.ListAccountsResponse.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.accounts_v1.AccountsServiceClient.list_accounts", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "ListAccounts", "metadata": http_response["headers"], @@ -879,7 +1038,9 @@ def __call__(self, ) return resp - class _ListSubAccounts(_BaseAccountsServiceRestTransport._BaseListSubAccounts, AccountsServiceRestStub): + class _ListSubAccounts( + _BaseAccountsServiceRestTransport._BaseListSubAccounts, AccountsServiceRestStub + ): def __hash__(self): return hash("AccountsServiceRestTransport.ListSubAccounts") @@ -891,26 +1052,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: accounts.ListSubAccountsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.ListSubAccountsResponse: + def __call__( + self, + request: accounts.ListSubAccountsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.ListSubAccountsResponse: r"""Call the list sub accounts method over HTTP. Args: @@ -929,30 +1092,42 @@ def __call__(self, Response message for the ``ListSubAccounts`` method. """ - http_options = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_http_options() + http_options = ( + _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_http_options() + ) - request, metadata = self._interceptor.pre_list_sub_accounts(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_sub_accounts( + request, metadata + ) + transcoded_request = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.ListSubAccounts", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "ListSubAccounts", "httpRequest": http_request, @@ -961,7 +1136,14 @@ def __call__(self, ) # Send the request - response = AccountsServiceRestTransport._ListSubAccounts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AccountsServiceRestTransport._ListSubAccounts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -976,20 +1158,26 @@ def __call__(self, resp = self._interceptor.post_list_sub_accounts(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_sub_accounts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_sub_accounts_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = accounts.ListSubAccountsResponse.to_json(response) + response_payload = accounts.ListSubAccountsResponse.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.accounts_v1.AccountsServiceClient.list_sub_accounts", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "ListSubAccounts", "metadata": http_response["headers"], @@ -998,7 +1186,9 @@ def __call__(self, ) return resp - class _UpdateAccount(_BaseAccountsServiceRestTransport._BaseUpdateAccount, AccountsServiceRestStub): + class _UpdateAccount( + _BaseAccountsServiceRestTransport._BaseUpdateAccount, AccountsServiceRestStub + ): def __hash__(self): return hash("AccountsServiceRestTransport.UpdateAccount") @@ -1010,27 +1200,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: accounts.UpdateAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> accounts.Account: + def __call__( + self, + request: accounts.UpdateAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> accounts.Account: r"""Call the update account method over HTTP. Args: @@ -1065,32 +1257,44 @@ def __call__(self, """ - http_options = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_http_options() + http_options = ( + _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_http_options() + ) request, metadata = self._interceptor.pre_update_account(request, metadata) - transcoded_request = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_transcoded_request(http_options, request) + transcoded_request = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_transcoded_request( + http_options, request + ) - body = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_request_body_json(transcoded_request) + body = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AccountsServiceClient.UpdateAccount", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "UpdateAccount", "httpRequest": http_request, @@ -1099,7 +1303,15 @@ def __call__(self, ) # Send the request - response = AccountsServiceRestTransport._UpdateAccount._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AccountsServiceRestTransport._UpdateAccount._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. @@ -1114,20 +1326,24 @@ def __call__(self, resp = self._interceptor.post_update_account(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_account_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = accounts.Account.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.accounts_v1.AccountsServiceClient.update_account", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AccountsService", "rpcName": "UpdateAccount", "metadata": http_response["headers"], @@ -1137,52 +1353,50 @@ def __call__(self, return resp @property - def create_and_configure_account(self) -> Callable[ - [accounts.CreateAndConfigureAccountRequest], - accounts.Account]: + def create_and_configure_account( + self, + ) -> Callable[[accounts.CreateAndConfigureAccountRequest], accounts.Account]: # 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._CreateAndConfigureAccount(self._session, self._host, self._interceptor) # type: ignore + return self._CreateAndConfigureAccount(self._session, self._host, self._interceptor) # type: ignore @property - def delete_account(self) -> Callable[ - [accounts.DeleteAccountRequest], - empty_pb2.Empty]: + def delete_account( + self, + ) -> Callable[[accounts.DeleteAccountRequest], 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._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore @property - def get_account(self) -> Callable[ - [accounts.GetAccountRequest], - accounts.Account]: + def get_account(self) -> Callable[[accounts.GetAccountRequest], accounts.Account]: # 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._GetAccount(self._session, self._host, self._interceptor) # type: ignore + return self._GetAccount(self._session, self._host, self._interceptor) # type: ignore @property - def list_accounts(self) -> Callable[ - [accounts.ListAccountsRequest], - accounts.ListAccountsResponse]: + def list_accounts( + self, + ) -> Callable[[accounts.ListAccountsRequest], accounts.ListAccountsResponse]: # 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._ListAccounts(self._session, self._host, self._interceptor) # type: ignore + return self._ListAccounts(self._session, self._host, self._interceptor) # type: ignore @property - def list_sub_accounts(self) -> Callable[ - [accounts.ListSubAccountsRequest], - accounts.ListSubAccountsResponse]: + def list_sub_accounts( + self, + ) -> Callable[[accounts.ListSubAccountsRequest], accounts.ListSubAccountsResponse]: # 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._ListSubAccounts(self._session, self._host, self._interceptor) # type: ignore + return self._ListSubAccounts(self._session, self._host, self._interceptor) # type: ignore @property - def update_account(self) -> Callable[ - [accounts.UpdateAccountRequest], - accounts.Account]: + def update_account( + self, + ) -> Callable[[accounts.UpdateAccountRequest], accounts.Account]: # 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._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -1192,6 +1406,4 @@ def close(self): self._session.close() -__all__=( - 'AccountsServiceRestTransport', -) +__all__ = ("AccountsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py index cd4f88fdfc5d..987539fcbe9e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/accounts_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/accounts_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 AccountsServiceTransport, 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_accounts_v1.types import accounts +from .base import DEFAULT_CLIENT_INFO, AccountsServiceTransport + class _BaseAccountsServiceRestTransport(AccountsServiceTransport): """Base REST backend transport for AccountsService. @@ -41,14 +39,16 @@ class _BaseAccountsServiceRestTransport(AccountsServiceTransport): 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,27 +85,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseCreateAndConfigureAccount: 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': '/accounts/v1/accounts:createAndConfigure', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/accounts:createAndConfigure", + "body": "*", + }, ] return http_options @@ -118,17 +124,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(_BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._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( + _BaseAccountsServiceRestTransport._BaseCreateAndConfigureAccount._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -137,19 +149,23 @@ class _BaseDeleteAccount: 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': '/accounts/v1/{name=accounts/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/accounts/v1/{name=accounts/*}", + }, ] return http_options @@ -161,11 +177,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(_BaseAccountsServiceRestTransport._BaseDeleteAccount._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( + _BaseAccountsServiceRestTransport._BaseDeleteAccount._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,19 +196,23 @@ class _BaseGetAccount: 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': '/accounts/v1/{name=accounts/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*}", + }, ] return http_options @@ -198,11 +224,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(_BaseAccountsServiceRestTransport._BaseGetAccount._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( + _BaseAccountsServiceRestTransport._BaseGetAccount._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -213,10 +245,11 @@ def __hash__(self): # pragma: NO COVER @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/accounts/v1/accounts', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/accounts", + }, ] return http_options @@ -228,10 +261,12 @@ 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 = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -240,19 +275,23 @@ class _BaseListSubAccounts: 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': '/accounts/v1/{provider=accounts/*}:listSubaccounts', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{provider=accounts/*}:listSubaccounts", + }, ] return http_options @@ -264,11 +303,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(_BaseAccountsServiceRestTransport._BaseListSubAccounts._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( + _BaseAccountsServiceRestTransport._BaseListSubAccounts._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -277,20 +322,24 @@ class _BaseUpdateAccount: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{account.name=accounts/*}', - 'body': 'account', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{account.name=accounts/*}", + "body": "account", + }, ] return http_options @@ -305,22 +354,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAccountsServiceRestTransport._BaseUpdateAccount._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( + _BaseAccountsServiceRestTransport._BaseUpdateAccount._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseAccountsServiceRestTransport', -) +__all__ = ("_BaseAccountsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py index 9d2f0554ddd6..dd8d3006666b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AutofeedSettingsServiceClient from .async_client import AutofeedSettingsServiceAsyncClient +from .client import AutofeedSettingsServiceClient __all__ = ( - 'AutofeedSettingsServiceClient', - 'AutofeedSettingsServiceAsyncClient', + "AutofeedSettingsServiceClient", + "AutofeedSettingsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py index 1a2a99f47bcc..d9ae0d19131d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,19 +45,23 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import autofeedsettings -from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport + from .client import AutofeedSettingsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AutofeedSettingsServiceTransport +from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport 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 AutofeedSettingsServiceAsyncClient: """Service to support `autofeed `__ @@ -60,21 +74,45 @@ class AutofeedSettingsServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.autofeed_settings_path) - parse_autofeed_settings_path = staticmethod(AutofeedSettingsServiceClient.parse_autofeed_settings_path) - common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AutofeedSettingsServiceClient.parse_common_billing_account_path) + autofeed_settings_path = staticmethod( + AutofeedSettingsServiceClient.autofeed_settings_path + ) + parse_autofeed_settings_path = staticmethod( + AutofeedSettingsServiceClient.parse_autofeed_settings_path + ) + common_billing_account_path = staticmethod( + AutofeedSettingsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AutofeedSettingsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(AutofeedSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AutofeedSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AutofeedSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AutofeedSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AutofeedSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AutofeedSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(AutofeedSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AutofeedSettingsServiceClient.parse_common_location_path) + parse_common_folder_path = staticmethod( + AutofeedSettingsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AutofeedSettingsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AutofeedSettingsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + AutofeedSettingsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + AutofeedSettingsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + AutofeedSettingsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + AutofeedSettingsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +148,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 +213,20 @@ def universe_domain(self) -> str: get_transport_class = AutofeedSettingsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = "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, + AutofeedSettingsServiceTransport, + Callable[..., AutofeedSettingsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the autofeed settings service async client. Args: @@ -233,31 +281,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.accounts_v1.AutofeedSettingsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", - "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.accounts.v1.AutofeedSettingsService", "credentialsType": None, - } + }, ) - async def get_autofeed_settings(self, - request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: + async def get_autofeed_settings( + self, + request: Optional[ + Union[autofeedsettings.GetAutofeedSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: r"""Retrieves the autofeed settings of an account. .. code-block:: python @@ -315,10 +373,14 @@ async def sample_get_autofeed_settings(): # - 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. @@ -332,14 +394,14 @@ async def sample_get_autofeed_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_autofeed_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_autofeed_settings + ] # 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. @@ -356,15 +418,18 @@ async def sample_get_autofeed_settings(): # Done; return the response. return response - async def update_autofeed_settings(self, - request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, - *, - autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: + async def update_autofeed_settings( + self, + request: Optional[ + Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict] + ] = None, + *, + autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: r"""Updates the autofeed settings of an account. .. code-block:: python @@ -433,10 +498,14 @@ async def sample_update_autofeed_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [autofeed_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -452,14 +521,16 @@ async def sample_update_autofeed_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_autofeed_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_autofeed_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("autofeed_settings.name", request.autofeed_settings.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("autofeed_settings.name", request.autofeed_settings.name),) + ), ) # Validate the universe domain. @@ -482,12 +553,13 @@ async def __aenter__(self) -> "AutofeedSettingsServiceAsyncClient": 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__ = ( - "AutofeedSettingsServiceAsyncClient", -) +__all__ = ("AutofeedSettingsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py index afea1b1c7e72..35fa3dc7bc03 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,8 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import autofeedsettings -from .transports.base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, AutofeedSettingsServiceTransport from .transports.grpc import AutofeedSettingsServiceGrpcTransport from .transports.grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport from .transports.rest import AutofeedSettingsServiceRestTransport @@ -63,14 +78,18 @@ class AutofeedSettingsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AutofeedSettingsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AutofeedSettingsServiceTransport]] _transport_registry["grpc"] = AutofeedSettingsServiceGrpcTransport _transport_registry["grpc_asyncio"] = AutofeedSettingsServiceGrpcAsyncIOTransport _transport_registry["rest"] = AutofeedSettingsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AutofeedSettingsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AutofeedSettingsServiceTransport]: """Returns an appropriate transport class. Args: @@ -165,8 +184,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AutofeedSettingsServiceClient: 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 +201,101 @@ def transport(self) -> AutofeedSettingsServiceTransport: return self._transport @staticmethod - def autofeed_settings_path(account: str,) -> str: + def autofeed_settings_path( + account: str, + ) -> str: """Returns a fully-qualified autofeed_settings string.""" - return "accounts/{account}/autofeedSettings".format(account=account, ) + return "accounts/{account}/autofeedSettings".format( + account=account, + ) @staticmethod - def parse_autofeed_settings_path(path: str) -> Dict[str,str]: + def parse_autofeed_settings_path(path: str) -> Dict[str, str]: """Parses a autofeed_settings path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/autofeedSettings$", 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 +327,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 +355,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 +378,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 +413,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 +431,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 = AutofeedSettingsServiceClient._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 = AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + AutofeedSettingsServiceClient._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 +487,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 +531,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutofeedSettingsServiceTransport, Callable[..., AutofeedSettingsServiceTransport]]] = 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, + AutofeedSettingsServiceTransport, + Callable[..., AutofeedSettingsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the autofeed settings service client. Args: @@ -516,14 +599,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 = AutofeedSettingsServiceClient._read_environment_variables() - self._client_cert_source = AutofeedSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AutofeedSettingsServiceClient._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, + ) = AutofeedSettingsServiceClient._read_environment_variables() + self._client_cert_source = ( + AutofeedSettingsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = AutofeedSettingsServiceClient._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 +629,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 +640,10 @@ def __init__(self, *, if transport_provided: # transport is a AutofeedSettingsServiceTransport 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 +652,30 @@ def __init__(self, *, self._transport = cast(AutofeedSettingsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AutofeedSettingsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AutofeedSettingsServiceClient._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[AutofeedSettingsServiceTransport], Callable[..., AutofeedSettingsServiceTransport]] = ( + transport_init: Union[ + Type[AutofeedSettingsServiceTransport], + Callable[..., AutofeedSettingsServiceTransport], + ] = ( AutofeedSettingsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., AutofeedSettingsServiceTransport], transport) @@ -585,28 +694,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.accounts_v1.AutofeedSettingsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", - "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.accounts.v1.AutofeedSettingsService", "credentialsType": None, - } + }, ) - def get_autofeed_settings(self, - request: Optional[Union[autofeedsettings.GetAutofeedSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: + def get_autofeed_settings( + self, + request: Optional[ + Union[autofeedsettings.GetAutofeedSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: r"""Retrieves the autofeed settings of an account. .. code-block:: python @@ -664,10 +784,14 @@ def sample_get_autofeed_settings(): # - 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. @@ -685,9 +809,7 @@ def sample_get_autofeed_settings(): # 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. @@ -704,15 +826,18 @@ def sample_get_autofeed_settings(): # Done; return the response. return response - def update_autofeed_settings(self, - request: Optional[Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict]] = None, - *, - autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autofeedsettings.AutofeedSettings: + def update_autofeed_settings( + self, + request: Optional[ + Union[autofeedsettings.UpdateAutofeedSettingsRequest, dict] + ] = None, + *, + autofeed_settings: Optional[autofeedsettings.AutofeedSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: r"""Updates the autofeed settings of an account. .. code-block:: python @@ -781,10 +906,14 @@ def sample_update_autofeed_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [autofeed_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -804,9 +933,9 @@ def sample_update_autofeed_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("autofeed_settings.name", request.autofeed_settings.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("autofeed_settings.name", request.autofeed_settings.name),) + ), ) # Validate the universe domain. @@ -837,16 +966,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__ = ( - "AutofeedSettingsServiceClient", -) +__all__ = ("AutofeedSettingsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py index c2ddd49ce02d..0ae7aeee528a 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/autofeed_settings_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import AutofeedSettingsServiceTransport from .grpc import AutofeedSettingsServiceGrpcTransport from .grpc_asyncio import AutofeedSettingsServiceGrpcAsyncIOTransport -from .rest import AutofeedSettingsServiceRestTransport -from .rest import AutofeedSettingsServiceRestInterceptor - +from .rest import ( + AutofeedSettingsServiceRestInterceptor, + AutofeedSettingsServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AutofeedSettingsServiceTransport]] -_transport_registry['grpc'] = AutofeedSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AutofeedSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AutofeedSettingsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[AutofeedSettingsServiceTransport]] +_transport_registry["grpc"] = AutofeedSettingsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AutofeedSettingsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AutofeedSettingsServiceRestTransport __all__ = ( - 'AutofeedSettingsServiceTransport', - 'AutofeedSettingsServiceGrpcTransport', - 'AutofeedSettingsServiceGrpcAsyncIOTransport', - 'AutofeedSettingsServiceRestTransport', - 'AutofeedSettingsServiceRestInterceptor', + "AutofeedSettingsServiceTransport", + "AutofeedSettingsServiceGrpcTransport", + "AutofeedSettingsServiceGrpcAsyncIOTransport", + "AutofeedSettingsServiceRestTransport", + "AutofeedSettingsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py index 80bd06ae78d1..369aa5582ff9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import autofeedsettings -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__ @@ -38,24 +39,23 @@ class AutofeedSettingsServiceTransport(abc.ABC): """Abstract transport class for AutofeedSettingsService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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 get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - Union[ - autofeedsettings.AutofeedSettings, - Awaitable[autofeedsettings.AutofeedSettings] - ]]: + def get_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + Union[ + autofeedsettings.AutofeedSettings, + Awaitable[autofeedsettings.AutofeedSettings], + ], + ]: raise NotImplementedError() @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - Union[ - autofeedsettings.AutofeedSettings, - Awaitable[autofeedsettings.AutofeedSettings] - ]]: + def update_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + Union[ + autofeedsettings.AutofeedSettings, + Awaitable[autofeedsettings.AutofeedSettings], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AutofeedSettingsServiceTransport', -) +__all__ = ("AutofeedSettingsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py index 953f936aba64..596a3ed7bb3a 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import autofeedsettings -from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AutofeedSettingsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,23 +121,26 @@ class AutofeedSettingsServiceGrpcTransport(AutofeedSettingsServiceTransport): 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,20 @@ 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 get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: + def get_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], autofeedsettings.AutofeedSettings + ]: r"""Return a callable for the get autofeed settings method over gRPC. Retrieves the autofeed settings of an account. @@ -327,18 +341,21 @@ def get_autofeed_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_autofeed_settings' not in self._stubs: - self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/GetAutofeedSettings', + if "get_autofeed_settings" not in self._stubs: + self._stubs["get_autofeed_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutofeedSettingsService/GetAutofeedSettings", request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, response_deserializer=autofeedsettings.AutofeedSettings.deserialize, ) - return self._stubs['get_autofeed_settings'] + return self._stubs["get_autofeed_settings"] @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: + def update_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings, + ]: r"""Return a callable for the update autofeed settings method over gRPC. Updates the autofeed settings of an account. @@ -353,13 +370,13 @@ def update_autofeed_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_autofeed_settings' not in self._stubs: - self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/UpdateAutofeedSettings', + if "update_autofeed_settings" not in self._stubs: + self._stubs["update_autofeed_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutofeedSettingsService/UpdateAutofeedSettings", request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, response_deserializer=autofeedsettings.AutofeedSettings.deserialize, ) - return self._stubs['update_autofeed_settings'] + return self._stubs["update_autofeed_settings"] def close(self): self._logged_channel.close() @@ -369,6 +386,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AutofeedSettingsServiceGrpcTransport', -) +__all__ = ("AutofeedSettingsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py index 79e80efb6ecc..9c85b672c0b6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import autofeedsettings -from .base import AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AutofeedSettingsServiceTransport from .grpc import AutofeedSettingsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -124,13 +132,15 @@ class AutofeedSettingsServiceGrpcAsyncIOTransport(AutofeedSettingsServiceTranspo _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 get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - Awaitable[autofeedsettings.AutofeedSettings]]: + def get_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], + Awaitable[autofeedsettings.AutofeedSettings], + ]: r"""Return a callable for the get autofeed settings method over gRPC. Retrieves the autofeed settings of an account. @@ -333,18 +350,21 @@ def get_autofeed_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_autofeed_settings' not in self._stubs: - self._stubs['get_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/GetAutofeedSettings', + if "get_autofeed_settings" not in self._stubs: + self._stubs["get_autofeed_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutofeedSettingsService/GetAutofeedSettings", request_serializer=autofeedsettings.GetAutofeedSettingsRequest.serialize, response_deserializer=autofeedsettings.AutofeedSettings.deserialize, ) - return self._stubs['get_autofeed_settings'] + return self._stubs["get_autofeed_settings"] @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - Awaitable[autofeedsettings.AutofeedSettings]]: + def update_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + Awaitable[autofeedsettings.AutofeedSettings], + ]: r"""Return a callable for the update autofeed settings method over gRPC. Updates the autofeed settings of an account. @@ -359,16 +379,16 @@ def update_autofeed_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_autofeed_settings' not in self._stubs: - self._stubs['update_autofeed_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutofeedSettingsService/UpdateAutofeedSettings', + if "update_autofeed_settings" not in self._stubs: + self._stubs["update_autofeed_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutofeedSettingsService/UpdateAutofeedSettings", request_serializer=autofeedsettings.UpdateAutofeedSettingsRequest.serialize, response_deserializer=autofeedsettings.AutofeedSettings.deserialize, ) - return self._stubs['update_autofeed_settings'] + return self._stubs["update_autofeed_settings"] 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.get_autofeed_settings: self._wrap_method( self.get_autofeed_settings, @@ -395,6 +415,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'AutofeedSettingsServiceGrpcAsyncIOTransport', -) +__all__ = ("AutofeedSettingsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py index 0ac0ad13768c..59967fc6bed9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import autofeedsettings - -from .rest_base import _BaseAutofeedSettingsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAutofeedSettingsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,15 @@ def post_update_autofeed_settings(self, response): """ - def pre_get_autofeed_settings(self, request: autofeedsettings.GetAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.GetAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_autofeed_settings( + self, + request: autofeedsettings.GetAutofeedSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autofeedsettings.GetAutofeedSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_autofeed_settings Override in a subclass to manipulate the request or metadata @@ -106,7 +109,9 @@ def pre_get_autofeed_settings(self, request: autofeedsettings.GetAutofeedSetting """ return request, metadata - def post_get_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: + def post_get_autofeed_settings( + self, response: autofeedsettings.AutofeedSettings + ) -> autofeedsettings.AutofeedSettings: """Post-rpc interceptor for get_autofeed_settings DEPRECATED. Please use the `post_get_autofeed_settings_with_metadata` @@ -119,7 +124,13 @@ def post_get_autofeed_settings(self, response: autofeedsettings.AutofeedSettings """ return response - def post_get_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_autofeed_settings_with_metadata( + self, + response: autofeedsettings.AutofeedSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_autofeed_settings Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +145,14 @@ def post_get_autofeed_settings_with_metadata(self, response: autofeedsettings.Au """ return response, metadata - def pre_update_autofeed_settings(self, request: autofeedsettings.UpdateAutofeedSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.UpdateAutofeedSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_autofeed_settings( + self, + request: autofeedsettings.UpdateAutofeedSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autofeedsettings.UpdateAutofeedSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_autofeed_settings Override in a subclass to manipulate the request or metadata @@ -142,7 +160,9 @@ def pre_update_autofeed_settings(self, request: autofeedsettings.UpdateAutofeedS """ return request, metadata - def post_update_autofeed_settings(self, response: autofeedsettings.AutofeedSettings) -> autofeedsettings.AutofeedSettings: + def post_update_autofeed_settings( + self, response: autofeedsettings.AutofeedSettings + ) -> autofeedsettings.AutofeedSettings: """Post-rpc interceptor for update_autofeed_settings DEPRECATED. Please use the `post_update_autofeed_settings_with_metadata` @@ -155,7 +175,13 @@ def post_update_autofeed_settings(self, response: autofeedsettings.AutofeedSetti """ return response - def post_update_autofeed_settings_with_metadata(self, response: autofeedsettings.AutofeedSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_autofeed_settings_with_metadata( + self, + response: autofeedsettings.AutofeedSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autofeedsettings.AutofeedSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for update_autofeed_settings Override in a subclass to read or manipulate the response or metadata after it @@ -192,20 +218,21 @@ class AutofeedSettingsServiceRestTransport(_BaseAutofeedSettingsServiceRestTrans 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[AutofeedSettingsServiceRestInterceptor] = 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[AutofeedSettingsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -248,16 +275,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 AutofeedSettingsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings, AutofeedSettingsServiceRestStub): + class _GetAutofeedSettings( + _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings, + AutofeedSettingsServiceRestStub, + ): def __hash__(self): return hash("AutofeedSettingsServiceRestTransport.GetAutofeedSettings") @@ -269,26 +300,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: autofeedsettings.GetAutofeedSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> autofeedsettings.AutofeedSettings: + def __call__( + self, + request: autofeedsettings.GetAutofeedSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: r"""Call the get autofeed settings method over HTTP. Args: @@ -310,30 +343,42 @@ def __call__(self, """ - http_options = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_http_options() + http_options = ( + _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_get_autofeed_settings(request, metadata) - transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_autofeed_settings( + request, metadata + ) + transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutofeedSettingsServiceClient.GetAutofeedSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": "GetAutofeedSettings", "httpRequest": http_request, @@ -342,7 +387,16 @@ def __call__(self, ) # Send the request - response = AutofeedSettingsServiceRestTransport._GetAutofeedSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + AutofeedSettingsServiceRestTransport._GetAutofeedSettings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -357,20 +411,26 @@ def __call__(self, resp = self._interceptor.post_get_autofeed_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_autofeed_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_autofeed_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = autofeedsettings.AutofeedSettings.to_json(response) + response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1.AutofeedSettingsServiceClient.get_autofeed_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": "GetAutofeedSettings", "metadata": http_response["headers"], @@ -379,7 +439,10 @@ def __call__(self, ) return resp - class _UpdateAutofeedSettings(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings, AutofeedSettingsServiceRestStub): + class _UpdateAutofeedSettings( + _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings, + AutofeedSettingsServiceRestStub, + ): def __hash__(self): return hash("AutofeedSettingsServiceRestTransport.UpdateAutofeedSettings") @@ -391,27 +454,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: autofeedsettings.UpdateAutofeedSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> autofeedsettings.AutofeedSettings: + def __call__( + self, + request: autofeedsettings.UpdateAutofeedSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autofeedsettings.AutofeedSettings: r"""Call the update autofeed settings method over HTTP. Args: @@ -434,32 +499,46 @@ def __call__(self, """ - http_options = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_http_options() + http_options = ( + _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_update_autofeed_settings(request, metadata) - transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_autofeed_settings( + request, metadata + ) + transcoded_request = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_transcoded_request( + http_options, request + ) - body = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_request_body_json(transcoded_request) + body = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutofeedSettingsServiceClient.UpdateAutofeedSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": "UpdateAutofeedSettings", "httpRequest": http_request, @@ -468,7 +547,15 @@ def __call__(self, ) # Send the request - response = AutofeedSettingsServiceRestTransport._UpdateAutofeedSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AutofeedSettingsServiceRestTransport._UpdateAutofeedSettings._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. @@ -483,20 +570,26 @@ def __call__(self, resp = self._interceptor.post_update_autofeed_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_autofeed_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_autofeed_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = autofeedsettings.AutofeedSettings.to_json(response) + response_payload = autofeedsettings.AutofeedSettings.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.accounts_v1.AutofeedSettingsServiceClient.update_autofeed_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutofeedSettingsService", "rpcName": "UpdateAutofeedSettings", "metadata": http_response["headers"], @@ -506,20 +599,25 @@ def __call__(self, return resp @property - def get_autofeed_settings(self) -> Callable[ - [autofeedsettings.GetAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: + def get_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.GetAutofeedSettingsRequest], autofeedsettings.AutofeedSettings + ]: # 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._GetAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore + return self._GetAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore @property - def update_autofeed_settings(self) -> Callable[ - [autofeedsettings.UpdateAutofeedSettingsRequest], - autofeedsettings.AutofeedSettings]: + def update_autofeed_settings( + self, + ) -> Callable[ + [autofeedsettings.UpdateAutofeedSettingsRequest], + autofeedsettings.AutofeedSettings, + ]: # 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._UpdateAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateAutofeedSettings(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -529,6 +627,4 @@ def close(self): self._session.close() -__all__=( - 'AutofeedSettingsServiceRestTransport', -) +__all__ = ("AutofeedSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py similarity index 64% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py index 972cfaeac785..16c5121de8c6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/autofeed_settings_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 AutofeedSettingsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import autofeedsettings +from .base import DEFAULT_CLIENT_INFO, AutofeedSettingsServiceTransport + class _BaseAutofeedSettingsServiceRestTransport(AutofeedSettingsServiceTransport): """Base REST backend transport for AutofeedSettingsService. @@ -40,14 +38,16 @@ class _BaseAutofeedSettingsServiceRestTransport(AutofeedSettingsServiceTransport 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseGetAutofeedSettings: 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': '/accounts/v1/{name=accounts/*/autofeedSettings}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/autofeedSettings}", + }, ] return http_options @@ -113,11 +119,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(_BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._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( + _BaseAutofeedSettingsServiceRestTransport._BaseGetAutofeedSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,20 +138,26 @@ class _BaseUpdateAutofeedSettings: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{autofeed_settings.name=accounts/*/autofeedSettings}', - 'body': 'autofeed_settings', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{autofeed_settings.name=accounts/*/autofeedSettings}", + "body": "autofeed_settings", + }, ] return http_options @@ -154,22 +172,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._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( + _BaseAutofeedSettingsServiceRestTransport._BaseUpdateAutofeedSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseAutofeedSettingsServiceRestTransport', -) +__all__ = ("_BaseAutofeedSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py index 7df59eeedb79..f5b488172bad 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import AutomaticImprovementsServiceClient from .async_client import AutomaticImprovementsServiceAsyncClient +from .client import AutomaticImprovementsServiceClient __all__ = ( - 'AutomaticImprovementsServiceClient', - 'AutomaticImprovementsServiceAsyncClient', + "AutomaticImprovementsServiceClient", + "AutomaticImprovementsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py similarity index 76% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py index eb5446f6f1b6..b2239b8cdbe6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,19 +45,23 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import automaticimprovements -from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport + from .client import AutomaticImprovementsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AutomaticImprovementsServiceTransport +from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport 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 AutomaticImprovementsServiceAsyncClient: """Service to manage the automatic improvements of an account. The automatic improvements of the account can be used to @@ -60,21 +74,47 @@ class AutomaticImprovementsServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.automatic_improvements_path) - parse_automatic_improvements_path = staticmethod(AutomaticImprovementsServiceClient.parse_automatic_improvements_path) - common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AutomaticImprovementsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AutomaticImprovementsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AutomaticImprovementsServiceClient.common_project_path) - parse_common_project_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_project_path) - common_location_path = staticmethod(AutomaticImprovementsServiceClient.common_location_path) - parse_common_location_path = staticmethod(AutomaticImprovementsServiceClient.parse_common_location_path) + automatic_improvements_path = staticmethod( + AutomaticImprovementsServiceClient.automatic_improvements_path + ) + parse_automatic_improvements_path = staticmethod( + AutomaticImprovementsServiceClient.parse_automatic_improvements_path + ) + common_billing_account_path = staticmethod( + AutomaticImprovementsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AutomaticImprovementsServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + AutomaticImprovementsServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + AutomaticImprovementsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AutomaticImprovementsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AutomaticImprovementsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + AutomaticImprovementsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + AutomaticImprovementsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + AutomaticImprovementsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + AutomaticImprovementsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +150,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 +215,20 @@ def universe_domain(self) -> str: get_transport_class = AutomaticImprovementsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = "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, + AutomaticImprovementsServiceTransport, + Callable[..., AutomaticImprovementsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the automatic improvements service async client. Args: @@ -233,31 +283,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.accounts_v1.AutomaticImprovementsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", - "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.accounts.v1.AutomaticImprovementsService", "credentialsType": None, - } + }, ) - async def get_automatic_improvements(self, - request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: + async def get_automatic_improvements( + self, + request: Optional[ + Union[automaticimprovements.GetAutomaticImprovementsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: r"""Retrieves the automatic improvements of an account. .. code-block:: python @@ -317,14 +377,20 @@ async def sample_get_automatic_improvements(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, automaticimprovements.GetAutomaticImprovementsRequest): + if not isinstance( + request, automaticimprovements.GetAutomaticImprovementsRequest + ): request = automaticimprovements.GetAutomaticImprovementsRequest(request) # If we have keyword arguments corresponding to fields on the @@ -334,14 +400,14 @@ async def sample_get_automatic_improvements(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_automatic_improvements] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_automatic_improvements + ] # 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. @@ -358,15 +424,20 @@ async def sample_get_automatic_improvements(): # Done; return the response. return response - async def update_automatic_improvements(self, - request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, - *, - automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: + async def update_automatic_improvements( + self, + request: Optional[ + Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict] + ] = None, + *, + automatic_improvements: Optional[ + automaticimprovements.AutomaticImprovements + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: r"""Updates the automatic improvements of an account. .. code-block:: python @@ -439,14 +510,20 @@ async def sample_update_automatic_improvements(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [automatic_improvements, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, automaticimprovements.UpdateAutomaticImprovementsRequest): + if not isinstance( + request, automaticimprovements.UpdateAutomaticImprovementsRequest + ): request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) # If we have keyword arguments corresponding to fields on the @@ -458,14 +535,16 @@ async def sample_update_automatic_improvements(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_automatic_improvements] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_automatic_improvements + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("automatic_improvements.name", request.automatic_improvements.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("automatic_improvements.name", request.automatic_improvements.name),) + ), ) # Validate the universe domain. @@ -488,12 +567,13 @@ async def __aenter__(self) -> "AutomaticImprovementsServiceAsyncClient": 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__ = ( - "AutomaticImprovementsServiceAsyncClient", -) +__all__ = ("AutomaticImprovementsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py similarity index 76% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py index 27be6fb27f1e..0478c4465bb1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,8 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import automaticimprovements -from .transports.base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, AutomaticImprovementsServiceTransport from .transports.grpc import AutomaticImprovementsServiceGrpcTransport from .transports.grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport from .transports.rest import AutomaticImprovementsServiceRestTransport @@ -63,14 +78,20 @@ class AutomaticImprovementsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] _transport_registry["grpc"] = AutomaticImprovementsServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AutomaticImprovementsServiceGrpcAsyncIOTransport + _transport_registry[ + "grpc_asyncio" + ] = AutomaticImprovementsServiceGrpcAsyncIOTransport _transport_registry["rest"] = AutomaticImprovementsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AutomaticImprovementsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AutomaticImprovementsServiceTransport]: """Returns an appropriate transport class. Args: @@ -89,7 +110,9 @@ def get_transport_class(cls, return next(iter(cls._transport_registry.values())) -class AutomaticImprovementsServiceClient(metaclass=AutomaticImprovementsServiceClientMeta): +class AutomaticImprovementsServiceClient( + metaclass=AutomaticImprovementsServiceClientMeta +): """Service to manage the automatic improvements of an account. The automatic improvements of the account can be used to automatically update products, improve images and shipping. @@ -165,8 +188,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: AutomaticImprovementsServiceClient: 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 +205,101 @@ def transport(self) -> AutomaticImprovementsServiceTransport: return self._transport @staticmethod - def automatic_improvements_path(account: str,) -> str: + def automatic_improvements_path( + account: str, + ) -> str: """Returns a fully-qualified automatic_improvements string.""" - return "accounts/{account}/automaticImprovements".format(account=account, ) + return "accounts/{account}/automaticImprovements".format( + account=account, + ) @staticmethod - def parse_automatic_improvements_path(path: str) -> Dict[str,str]: + def parse_automatic_improvements_path(path: str) -> Dict[str, str]: """Parses a automatic_improvements path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/automaticImprovements$", 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 +331,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 +359,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 +382,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 +417,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): """Return the API endpoint used by the client. Args: @@ -369,17 +435,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 = AutomaticImprovementsServiceClient._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 = AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + AutomaticImprovementsServiceClient._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 +491,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 +535,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutomaticImprovementsServiceTransport, Callable[..., AutomaticImprovementsServiceTransport]]] = 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, + AutomaticImprovementsServiceTransport, + Callable[..., AutomaticImprovementsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the automatic improvements service client. Args: @@ -516,14 +603,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 = AutomaticImprovementsServiceClient._read_environment_variables() - self._client_cert_source = AutomaticImprovementsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AutomaticImprovementsServiceClient._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, + ) = AutomaticImprovementsServiceClient._read_environment_variables() + self._client_cert_source = ( + AutomaticImprovementsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = AutomaticImprovementsServiceClient._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,17 +633,23 @@ 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 # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, AutomaticImprovementsServiceTransport) + transport_provided = isinstance( + transport, AutomaticImprovementsServiceTransport + ) if transport_provided: # transport is a AutomaticImprovementsServiceTransport 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,23 +658,35 @@ def __init__(self, *, self._transport = cast(AutomaticImprovementsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - AutomaticImprovementsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or AutomaticImprovementsServiceClient._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[AutomaticImprovementsServiceTransport], Callable[..., AutomaticImprovementsServiceTransport]] = ( + transport_init: Union[ + Type[AutomaticImprovementsServiceTransport], + Callable[..., AutomaticImprovementsServiceTransport], + ] = ( AutomaticImprovementsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None - else cast(Callable[..., AutomaticImprovementsServiceTransport], transport) + else cast( + Callable[..., AutomaticImprovementsServiceTransport], transport + ) ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -585,28 +702,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.accounts_v1.AutomaticImprovementsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", - "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.accounts.v1.AutomaticImprovementsService", "credentialsType": None, - } + }, ) - def get_automatic_improvements(self, - request: Optional[Union[automaticimprovements.GetAutomaticImprovementsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: + def get_automatic_improvements( + self, + request: Optional[ + Union[automaticimprovements.GetAutomaticImprovementsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: r"""Retrieves the automatic improvements of an account. .. code-block:: python @@ -666,14 +794,20 @@ def sample_get_automatic_improvements(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, automaticimprovements.GetAutomaticImprovementsRequest): + if not isinstance( + request, automaticimprovements.GetAutomaticImprovementsRequest + ): request = automaticimprovements.GetAutomaticImprovementsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -682,14 +816,14 @@ def sample_get_automatic_improvements(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_automatic_improvements] + rpc = self._transport._wrapped_methods[ + self._transport.get_automatic_improvements + ] # 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. @@ -706,15 +840,20 @@ def sample_get_automatic_improvements(): # Done; return the response. return response - def update_automatic_improvements(self, - request: Optional[Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict]] = None, - *, - automatic_improvements: Optional[automaticimprovements.AutomaticImprovements] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> automaticimprovements.AutomaticImprovements: + def update_automatic_improvements( + self, + request: Optional[ + Union[automaticimprovements.UpdateAutomaticImprovementsRequest, dict] + ] = None, + *, + automatic_improvements: Optional[ + automaticimprovements.AutomaticImprovements + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: r"""Updates the automatic improvements of an account. .. code-block:: python @@ -787,14 +926,20 @@ def sample_update_automatic_improvements(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [automatic_improvements, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, automaticimprovements.UpdateAutomaticImprovementsRequest): + if not isinstance( + request, automaticimprovements.UpdateAutomaticImprovementsRequest + ): request = automaticimprovements.UpdateAutomaticImprovementsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -805,14 +950,16 @@ def sample_update_automatic_improvements(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_automatic_improvements] + rpc = self._transport._wrapped_methods[ + self._transport.update_automatic_improvements + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("automatic_improvements.name", request.automatic_improvements.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("automatic_improvements.name", request.automatic_improvements.name),) + ), ) # Validate the universe domain. @@ -843,16 +990,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__ = ( - "AutomaticImprovementsServiceClient", -) +__all__ = ("AutomaticImprovementsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py index 815443dffafc..fd71a1354dd8 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import AutomaticImprovementsServiceTransport from .grpc import AutomaticImprovementsServiceGrpcTransport from .grpc_asyncio import AutomaticImprovementsServiceGrpcAsyncIOTransport -from .rest import AutomaticImprovementsServiceRestTransport -from .rest import AutomaticImprovementsServiceRestInterceptor - +from .rest import ( + AutomaticImprovementsServiceRestInterceptor, + AutomaticImprovementsServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] -_transport_registry['grpc'] = AutomaticImprovementsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AutomaticImprovementsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AutomaticImprovementsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[AutomaticImprovementsServiceTransport]] +_transport_registry["grpc"] = AutomaticImprovementsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AutomaticImprovementsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AutomaticImprovementsServiceRestTransport __all__ = ( - 'AutomaticImprovementsServiceTransport', - 'AutomaticImprovementsServiceGrpcTransport', - 'AutomaticImprovementsServiceGrpcAsyncIOTransport', - 'AutomaticImprovementsServiceRestTransport', - 'AutomaticImprovementsServiceRestInterceptor', + "AutomaticImprovementsServiceTransport", + "AutomaticImprovementsServiceGrpcTransport", + "AutomaticImprovementsServiceGrpcAsyncIOTransport", + "AutomaticImprovementsServiceRestTransport", + "AutomaticImprovementsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py index f26ae7ecb83f..99b2552855e4 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import automaticimprovements -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__ @@ -38,24 +39,23 @@ class AutomaticImprovementsServiceTransport(abc.ABC): """Abstract transport class for AutomaticImprovementsService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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 get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - Union[ - automaticimprovements.AutomaticImprovements, - Awaitable[automaticimprovements.AutomaticImprovements] - ]]: + def get_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + Union[ + automaticimprovements.AutomaticImprovements, + Awaitable[automaticimprovements.AutomaticImprovements], + ], + ]: raise NotImplementedError() @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - Union[ - automaticimprovements.AutomaticImprovements, - Awaitable[automaticimprovements.AutomaticImprovements] - ]]: + def update_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + Union[ + automaticimprovements.AutomaticImprovements, + Awaitable[automaticimprovements.AutomaticImprovements], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'AutomaticImprovementsServiceTransport', -) +__all__ = ("AutomaticImprovementsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py index f0e16dc7ca10..91cc87a7c4c8 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import automaticimprovements -from .base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AutomaticImprovementsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,23 +121,26 @@ class AutomaticImprovementsServiceGrpcTransport(AutomaticImprovementsServiceTran 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 get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: + def get_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements, + ]: r"""Return a callable for the get automatic improvements method over gRPC. Retrieves the automatic improvements of an account. @@ -327,18 +342,23 @@ def get_automatic_improvements(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_automatic_improvements' not in self._stubs: - self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/GetAutomaticImprovements', + if "get_automatic_improvements" not in self._stubs: + self._stubs[ + "get_automatic_improvements" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/GetAutomaticImprovements", request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, ) - return self._stubs['get_automatic_improvements'] + return self._stubs["get_automatic_improvements"] @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: + def update_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements, + ]: r"""Return a callable for the update automatic improvements method over gRPC. Updates the automatic improvements of an account. @@ -353,13 +373,15 @@ def update_automatic_improvements(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_automatic_improvements' not in self._stubs: - self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/UpdateAutomaticImprovements', + if "update_automatic_improvements" not in self._stubs: + self._stubs[ + "update_automatic_improvements" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/UpdateAutomaticImprovements", request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, ) - return self._stubs['update_automatic_improvements'] + return self._stubs["update_automatic_improvements"] def close(self): self._logged_channel.close() @@ -369,6 +391,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'AutomaticImprovementsServiceGrpcTransport', -) +__all__ = ("AutomaticImprovementsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py index dfc1ccc7465e..11802ed60a91 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import automaticimprovements -from .base import AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, AutomaticImprovementsServiceTransport from .grpc import AutomaticImprovementsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -105,7 +113,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request return response -class AutomaticImprovementsServiceGrpcAsyncIOTransport(AutomaticImprovementsServiceTransport): +class AutomaticImprovementsServiceGrpcAsyncIOTransport( + AutomaticImprovementsServiceTransport +): """gRPC AsyncIO backend transport for AutomaticImprovementsService. Service to manage the automatic improvements of an account. @@ -124,13 +134,15 @@ class AutomaticImprovementsServiceGrpcAsyncIOTransport(AutomaticImprovementsServ _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 +172,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = '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 +315,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 +332,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - Awaitable[automaticimprovements.AutomaticImprovements]]: + def get_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + Awaitable[automaticimprovements.AutomaticImprovements], + ]: r"""Return a callable for the get automatic improvements method over gRPC. Retrieves the automatic improvements of an account. @@ -333,18 +352,23 @@ def get_automatic_improvements(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_automatic_improvements' not in self._stubs: - self._stubs['get_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/GetAutomaticImprovements', + if "get_automatic_improvements" not in self._stubs: + self._stubs[ + "get_automatic_improvements" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/GetAutomaticImprovements", request_serializer=automaticimprovements.GetAutomaticImprovementsRequest.serialize, response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, ) - return self._stubs['get_automatic_improvements'] + return self._stubs["get_automatic_improvements"] @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - Awaitable[automaticimprovements.AutomaticImprovements]]: + def update_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + Awaitable[automaticimprovements.AutomaticImprovements], + ]: r"""Return a callable for the update automatic improvements method over gRPC. Updates the automatic improvements of an account. @@ -359,16 +383,18 @@ def update_automatic_improvements(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_automatic_improvements' not in self._stubs: - self._stubs['update_automatic_improvements'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/UpdateAutomaticImprovements', + if "update_automatic_improvements" not in self._stubs: + self._stubs[ + "update_automatic_improvements" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.AutomaticImprovementsService/UpdateAutomaticImprovements", request_serializer=automaticimprovements.UpdateAutomaticImprovementsRequest.serialize, response_deserializer=automaticimprovements.AutomaticImprovements.deserialize, ) - return self._stubs['update_automatic_improvements'] + return self._stubs["update_automatic_improvements"] 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.get_automatic_improvements: self._wrap_method( self.get_automatic_improvements, @@ -395,6 +421,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'AutomaticImprovementsServiceGrpcAsyncIOTransport', -) +__all__ = ("AutomaticImprovementsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py similarity index 62% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py index ec5a09c351c5..a03eccede247 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import automaticimprovements - -from .rest_base import _BaseAutomaticImprovementsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAutomaticImprovementsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,15 @@ def post_update_automatic_improvements(self, response): """ - def pre_get_automatic_improvements(self, request: automaticimprovements.GetAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.GetAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_automatic_improvements( + self, + request: automaticimprovements.GetAutomaticImprovementsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + automaticimprovements.GetAutomaticImprovementsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_automatic_improvements Override in a subclass to manipulate the request or metadata @@ -106,7 +109,9 @@ def pre_get_automatic_improvements(self, request: automaticimprovements.GetAutom """ return request, metadata - def post_get_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: + def post_get_automatic_improvements( + self, response: automaticimprovements.AutomaticImprovements + ) -> automaticimprovements.AutomaticImprovements: """Post-rpc interceptor for get_automatic_improvements DEPRECATED. Please use the `post_get_automatic_improvements_with_metadata` @@ -119,7 +124,14 @@ def post_get_automatic_improvements(self, response: automaticimprovements.Automa """ return response - def post_get_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_automatic_improvements_with_metadata( + self, + response: automaticimprovements.AutomaticImprovements, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + automaticimprovements.AutomaticImprovements, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for get_automatic_improvements Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +146,14 @@ def post_get_automatic_improvements_with_metadata(self, response: automaticimpro """ return response, metadata - def pre_update_automatic_improvements(self, request: automaticimprovements.UpdateAutomaticImprovementsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.UpdateAutomaticImprovementsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_automatic_improvements( + self, + request: automaticimprovements.UpdateAutomaticImprovementsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + automaticimprovements.UpdateAutomaticImprovementsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_automatic_improvements Override in a subclass to manipulate the request or metadata @@ -142,7 +161,9 @@ def pre_update_automatic_improvements(self, request: automaticimprovements.Updat """ return request, metadata - def post_update_automatic_improvements(self, response: automaticimprovements.AutomaticImprovements) -> automaticimprovements.AutomaticImprovements: + def post_update_automatic_improvements( + self, response: automaticimprovements.AutomaticImprovements + ) -> automaticimprovements.AutomaticImprovements: """Post-rpc interceptor for update_automatic_improvements DEPRECATED. Please use the `post_update_automatic_improvements_with_metadata` @@ -155,7 +176,14 @@ def post_update_automatic_improvements(self, response: automaticimprovements.Aut """ return response - def post_update_automatic_improvements_with_metadata(self, response: automaticimprovements.AutomaticImprovements, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[automaticimprovements.AutomaticImprovements, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_automatic_improvements_with_metadata( + self, + response: automaticimprovements.AutomaticImprovements, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + automaticimprovements.AutomaticImprovements, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for update_automatic_improvements Override in a subclass to read or manipulate the response or metadata after it @@ -178,7 +206,9 @@ class AutomaticImprovementsServiceRestStub: _interceptor: AutomaticImprovementsServiceRestInterceptor -class AutomaticImprovementsServiceRestTransport(_BaseAutomaticImprovementsServiceRestTransport): +class AutomaticImprovementsServiceRestTransport( + _BaseAutomaticImprovementsServiceRestTransport +): """REST backend synchronous transport for AutomaticImprovementsService. Service to manage the automatic improvements of an account. @@ -192,20 +222,21 @@ class AutomaticImprovementsServiceRestTransport(_BaseAutomaticImprovementsServic 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[AutomaticImprovementsServiceRestInterceptor] = 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[AutomaticImprovementsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -248,18 +279,24 @@ 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 AutomaticImprovementsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements, AutomaticImprovementsServiceRestStub): + class _GetAutomaticImprovements( + _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements, + AutomaticImprovementsServiceRestStub, + ): def __hash__(self): - return hash("AutomaticImprovementsServiceRestTransport.GetAutomaticImprovements") + return hash( + "AutomaticImprovementsServiceRestTransport.GetAutomaticImprovements" + ) @staticmethod def _get_response( @@ -269,73 +306,87 @@ 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: automaticimprovements.GetAutomaticImprovementsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> automaticimprovements.AutomaticImprovements: + def __call__( + self, + request: automaticimprovements.GetAutomaticImprovementsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: r"""Call the get automatic - improvements method over HTTP. - - Args: - request (~.automaticimprovements.GetAutomaticImprovementsRequest): - The request object. Request message for the ``GetAutomaticImprovements`` - 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: - ~.automaticimprovements.AutomaticImprovements: - Collection of information related to the `automatic - improvements `__ - of an account. + improvements method over HTTP. + + Args: + request (~.automaticimprovements.GetAutomaticImprovementsRequest): + The request object. Request message for the ``GetAutomaticImprovements`` + 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: + ~.automaticimprovements.AutomaticImprovements: + Collection of information related to the `automatic + improvements `__ + of an account. """ - http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_http_options() + http_options = ( + _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_http_options() + ) - request, metadata = self._interceptor.pre_get_automatic_improvements(request, metadata) - transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_automatic_improvements( + request, metadata + ) + transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutomaticImprovementsServiceClient.GetAutomaticImprovements", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": "GetAutomaticImprovements", "httpRequest": http_request, @@ -344,7 +395,14 @@ def __call__(self, ) # Send the request - response = AutomaticImprovementsServiceRestTransport._GetAutomaticImprovements._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = AutomaticImprovementsServiceRestTransport._GetAutomaticImprovements._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -359,20 +417,26 @@ def __call__(self, resp = self._interceptor.post_get_automatic_improvements(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_automatic_improvements_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_automatic_improvements_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = automaticimprovements.AutomaticImprovements.to_json(response) + response_payload = ( + automaticimprovements.AutomaticImprovements.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.accounts_v1.AutomaticImprovementsServiceClient.get_automatic_improvements", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": "GetAutomaticImprovements", "metadata": http_response["headers"], @@ -381,9 +445,14 @@ def __call__(self, ) return resp - class _UpdateAutomaticImprovements(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements, AutomaticImprovementsServiceRestStub): + class _UpdateAutomaticImprovements( + _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements, + AutomaticImprovementsServiceRestStub, + ): def __hash__(self): - return hash("AutomaticImprovementsServiceRestTransport.UpdateAutomaticImprovements") + return hash( + "AutomaticImprovementsServiceRestTransport.UpdateAutomaticImprovements" + ) @staticmethod def _get_response( @@ -393,76 +462,92 @@ 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: automaticimprovements.UpdateAutomaticImprovementsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> automaticimprovements.AutomaticImprovements: + def __call__( + self, + request: automaticimprovements.UpdateAutomaticImprovementsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> automaticimprovements.AutomaticImprovements: r"""Call the update automatic - improvements method over HTTP. - - Args: - request (~.automaticimprovements.UpdateAutomaticImprovementsRequest): - The request object. Request message for the ``UpdateAutomaticImprovements`` - 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: - ~.automaticimprovements.AutomaticImprovements: - Collection of information related to the `automatic - improvements `__ - of an account. + improvements method over HTTP. + + Args: + request (~.automaticimprovements.UpdateAutomaticImprovementsRequest): + The request object. Request message for the ``UpdateAutomaticImprovements`` + 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: + ~.automaticimprovements.AutomaticImprovements: + Collection of information related to the `automatic + improvements `__ + of an account. """ - http_options = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_http_options() + http_options = ( + _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_http_options() + ) - request, metadata = self._interceptor.pre_update_automatic_improvements(request, metadata) - transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_automatic_improvements( + request, metadata + ) + transcoded_request = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_transcoded_request( + http_options, request + ) - body = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_request_body_json(transcoded_request) + body = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.AutomaticImprovementsServiceClient.UpdateAutomaticImprovements", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": "UpdateAutomaticImprovements", "httpRequest": http_request, @@ -471,7 +556,15 @@ def __call__(self, ) # Send the request - response = AutomaticImprovementsServiceRestTransport._UpdateAutomaticImprovements._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = AutomaticImprovementsServiceRestTransport._UpdateAutomaticImprovements._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. @@ -486,20 +579,29 @@ def __call__(self, resp = self._interceptor.post_update_automatic_improvements(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_automatic_improvements_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_update_automatic_improvements_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = automaticimprovements.AutomaticImprovements.to_json(response) + response_payload = ( + automaticimprovements.AutomaticImprovements.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.accounts_v1.AutomaticImprovementsServiceClient.update_automatic_improvements", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.AutomaticImprovementsService", "rpcName": "UpdateAutomaticImprovements", "metadata": http_response["headers"], @@ -509,20 +611,26 @@ def __call__(self, return resp @property - def get_automatic_improvements(self) -> Callable[ - [automaticimprovements.GetAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: + def get_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.GetAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements, + ]: # 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._GetAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore + return self._GetAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore @property - def update_automatic_improvements(self) -> Callable[ - [automaticimprovements.UpdateAutomaticImprovementsRequest], - automaticimprovements.AutomaticImprovements]: + def update_automatic_improvements( + self, + ) -> Callable[ + [automaticimprovements.UpdateAutomaticImprovementsRequest], + automaticimprovements.AutomaticImprovements, + ]: # 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._UpdateAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateAutomaticImprovements(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -532,6 +640,4 @@ def close(self): self._session.close() -__all__=( - 'AutomaticImprovementsServiceRestTransport', -) +__all__ = ("AutomaticImprovementsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py similarity index 62% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py index 3bb6c7689ef5..2c7e03dcaacc 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/automatic_improvements_service/transports/rest_base.py @@ -14,20 +14,20 @@ # 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 AutomaticImprovementsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import automaticimprovements +from .base import DEFAULT_CLIENT_INFO, AutomaticImprovementsServiceTransport -class _BaseAutomaticImprovementsServiceRestTransport(AutomaticImprovementsServiceTransport): + +class _BaseAutomaticImprovementsServiceRestTransport( + AutomaticImprovementsServiceTransport +): """Base REST backend transport for AutomaticImprovementsService. Note: This class is not meant to be used directly. Use its sync and @@ -40,14 +40,16 @@ class _BaseAutomaticImprovementsServiceRestTransport(AutomaticImprovementsServic 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]): @@ -71,7 +73,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,42 +86,54 @@ 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 _BaseGetAutomaticImprovements: 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': '/accounts/v1/{name=accounts/*/automaticImprovements}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/automaticImprovements}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = automaticimprovements.GetAutomaticImprovementsRequest.pb(request) + pb_request = automaticimprovements.GetAutomaticImprovementsRequest.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(_BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._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( + _BaseAutomaticImprovementsServiceRestTransport._BaseGetAutomaticImprovements._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,26 +142,34 @@ class _BaseUpdateAutomaticImprovements: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{automatic_improvements.name=accounts/*/automaticImprovements}', - 'body': 'automatic_improvements', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{automatic_improvements.name=accounts/*/automaticImprovements}", + "body": "automatic_improvements", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = automaticimprovements.UpdateAutomaticImprovementsRequest.pb(request) + pb_request = automaticimprovements.UpdateAutomaticImprovementsRequest.pb( + request + ) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -154,22 +178,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._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( + _BaseAutomaticImprovementsServiceRestTransport._BaseUpdateAutomaticImprovements._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseAutomaticImprovementsServiceRestTransport', -) +__all__ = ("_BaseAutomaticImprovementsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py index f97b26e0a25c..52ba082b9ad4 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import BusinessIdentityServiceClient from .async_client import BusinessIdentityServiceAsyncClient +from .client import BusinessIdentityServiceClient __all__ = ( - 'BusinessIdentityServiceClient', - 'BusinessIdentityServiceAsyncClient', + "BusinessIdentityServiceClient", + "BusinessIdentityServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py index c771acbc99d1..8abdbda0f91f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,19 +45,23 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import businessidentity -from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport + from .client import BusinessIdentityServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, BusinessIdentityServiceTransport +from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport 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 BusinessIdentityServiceAsyncClient: """Service to support `business identity `__ @@ -60,21 +74,45 @@ class BusinessIdentityServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - business_identity_path = staticmethod(BusinessIdentityServiceClient.business_identity_path) - parse_business_identity_path = staticmethod(BusinessIdentityServiceClient.parse_business_identity_path) - common_billing_account_path = staticmethod(BusinessIdentityServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BusinessIdentityServiceClient.parse_common_billing_account_path) + business_identity_path = staticmethod( + BusinessIdentityServiceClient.business_identity_path + ) + parse_business_identity_path = staticmethod( + BusinessIdentityServiceClient.parse_business_identity_path + ) + common_billing_account_path = staticmethod( + BusinessIdentityServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + BusinessIdentityServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(BusinessIdentityServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(BusinessIdentityServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(BusinessIdentityServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(BusinessIdentityServiceClient.parse_common_organization_path) - common_project_path = staticmethod(BusinessIdentityServiceClient.common_project_path) - parse_common_project_path = staticmethod(BusinessIdentityServiceClient.parse_common_project_path) - common_location_path = staticmethod(BusinessIdentityServiceClient.common_location_path) - parse_common_location_path = staticmethod(BusinessIdentityServiceClient.parse_common_location_path) + parse_common_folder_path = staticmethod( + BusinessIdentityServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + BusinessIdentityServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + BusinessIdentityServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + BusinessIdentityServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + BusinessIdentityServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + BusinessIdentityServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + BusinessIdentityServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +148,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 +213,20 @@ def universe_domain(self) -> str: get_transport_class = BusinessIdentityServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = "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, + BusinessIdentityServiceTransport, + Callable[..., BusinessIdentityServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the business identity service async client. Args: @@ -233,31 +281,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.accounts_v1.BusinessIdentityServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", - "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.accounts.v1.BusinessIdentityService", "credentialsType": None, - } + }, ) - async def get_business_identity(self, - request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: + async def get_business_identity( + self, + request: Optional[ + Union[businessidentity.GetBusinessIdentityRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: r"""Retrieves the business identity of an account. .. code-block:: python @@ -315,10 +373,14 @@ async def sample_get_business_identity(): # - 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. @@ -332,14 +394,14 @@ async def sample_get_business_identity(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_business_identity] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_business_identity + ] # 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. @@ -356,15 +418,18 @@ async def sample_get_business_identity(): # Done; return the response. return response - async def update_business_identity(self, - request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, - *, - business_identity: Optional[businessidentity.BusinessIdentity] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: + async def update_business_identity( + self, + request: Optional[ + Union[businessidentity.UpdateBusinessIdentityRequest, dict] + ] = None, + *, + business_identity: Optional[businessidentity.BusinessIdentity] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: r"""Updates the business identity of an account. Executing this method requires admin access. @@ -442,10 +507,14 @@ async def sample_update_business_identity(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [business_identity, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -461,14 +530,16 @@ async def sample_update_business_identity(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_identity] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_business_identity + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_identity.name", request.business_identity.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("business_identity.name", request.business_identity.name),) + ), ) # Validate the universe domain. @@ -491,12 +562,13 @@ async def __aenter__(self) -> "BusinessIdentityServiceAsyncClient": 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__ = ( - "BusinessIdentityServiceAsyncClient", -) +__all__ = ("BusinessIdentityServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py index 86f8bcba90d3..8b9d553b4f49 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,8 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import businessidentity -from .transports.base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, BusinessIdentityServiceTransport from .transports.grpc import BusinessIdentityServiceGrpcTransport from .transports.grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport from .transports.rest import BusinessIdentityServiceRestTransport @@ -63,14 +78,18 @@ class BusinessIdentityServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[BusinessIdentityServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[BusinessIdentityServiceTransport]] _transport_registry["grpc"] = BusinessIdentityServiceGrpcTransport _transport_registry["grpc_asyncio"] = BusinessIdentityServiceGrpcAsyncIOTransport _transport_registry["rest"] = BusinessIdentityServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[BusinessIdentityServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[BusinessIdentityServiceTransport]: """Returns an appropriate transport class. Args: @@ -165,8 +184,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BusinessIdentityServiceClient: 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 +201,101 @@ def transport(self) -> BusinessIdentityServiceTransport: return self._transport @staticmethod - def business_identity_path(account: str,) -> str: + def business_identity_path( + account: str, + ) -> str: """Returns a fully-qualified business_identity string.""" - return "accounts/{account}/businessIdentity".format(account=account, ) + return "accounts/{account}/businessIdentity".format( + account=account, + ) @staticmethod - def parse_business_identity_path(path: str) -> Dict[str,str]: + def parse_business_identity_path(path: str) -> Dict[str, str]: """Parses a business_identity path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/businessIdentity$", 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 +327,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 +355,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 +378,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 +413,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 +431,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 = BusinessIdentityServiceClient._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 = BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + BusinessIdentityServiceClient._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 +487,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 +531,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BusinessIdentityServiceTransport, Callable[..., BusinessIdentityServiceTransport]]] = 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, + BusinessIdentityServiceTransport, + Callable[..., BusinessIdentityServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the business identity service client. Args: @@ -516,14 +599,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 = BusinessIdentityServiceClient._read_environment_variables() - self._client_cert_source = BusinessIdentityServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = BusinessIdentityServiceClient._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, + ) = BusinessIdentityServiceClient._read_environment_variables() + self._client_cert_source = ( + BusinessIdentityServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = BusinessIdentityServiceClient._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 +629,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 +640,10 @@ def __init__(self, *, if transport_provided: # transport is a BusinessIdentityServiceTransport 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 +652,30 @@ def __init__(self, *, self._transport = cast(BusinessIdentityServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - BusinessIdentityServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or BusinessIdentityServiceClient._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[BusinessIdentityServiceTransport], Callable[..., BusinessIdentityServiceTransport]] = ( + transport_init: Union[ + Type[BusinessIdentityServiceTransport], + Callable[..., BusinessIdentityServiceTransport], + ] = ( BusinessIdentityServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., BusinessIdentityServiceTransport], transport) @@ -585,28 +694,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.accounts_v1.BusinessIdentityServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", - "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.accounts.v1.BusinessIdentityService", "credentialsType": None, - } + }, ) - def get_business_identity(self, - request: Optional[Union[businessidentity.GetBusinessIdentityRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: + def get_business_identity( + self, + request: Optional[ + Union[businessidentity.GetBusinessIdentityRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: r"""Retrieves the business identity of an account. .. code-block:: python @@ -664,10 +784,14 @@ def sample_get_business_identity(): # - 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. @@ -685,9 +809,7 @@ def sample_get_business_identity(): # 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. @@ -704,15 +826,18 @@ def sample_get_business_identity(): # Done; return the response. return response - def update_business_identity(self, - request: Optional[Union[businessidentity.UpdateBusinessIdentityRequest, dict]] = None, - *, - business_identity: Optional[businessidentity.BusinessIdentity] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessidentity.BusinessIdentity: + def update_business_identity( + self, + request: Optional[ + Union[businessidentity.UpdateBusinessIdentityRequest, dict] + ] = None, + *, + business_identity: Optional[businessidentity.BusinessIdentity] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: r"""Updates the business identity of an account. Executing this method requires admin access. @@ -790,10 +915,14 @@ def sample_update_business_identity(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [business_identity, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -813,9 +942,9 @@ def sample_update_business_identity(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_identity.name", request.business_identity.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("business_identity.name", request.business_identity.name),) + ), ) # Validate the universe domain. @@ -846,16 +975,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__ = ( - "BusinessIdentityServiceClient", -) +__all__ = ("BusinessIdentityServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py index 0f211578bee2..4aaacf37a857 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import BusinessIdentityServiceTransport from .grpc import BusinessIdentityServiceGrpcTransport from .grpc_asyncio import BusinessIdentityServiceGrpcAsyncIOTransport -from .rest import BusinessIdentityServiceRestTransport -from .rest import BusinessIdentityServiceRestInterceptor - +from .rest import ( + BusinessIdentityServiceRestInterceptor, + BusinessIdentityServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessIdentityServiceTransport]] -_transport_registry['grpc'] = BusinessIdentityServiceGrpcTransport -_transport_registry['grpc_asyncio'] = BusinessIdentityServiceGrpcAsyncIOTransport -_transport_registry['rest'] = BusinessIdentityServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[BusinessIdentityServiceTransport]] +_transport_registry["grpc"] = BusinessIdentityServiceGrpcTransport +_transport_registry["grpc_asyncio"] = BusinessIdentityServiceGrpcAsyncIOTransport +_transport_registry["rest"] = BusinessIdentityServiceRestTransport __all__ = ( - 'BusinessIdentityServiceTransport', - 'BusinessIdentityServiceGrpcTransport', - 'BusinessIdentityServiceGrpcAsyncIOTransport', - 'BusinessIdentityServiceRestTransport', - 'BusinessIdentityServiceRestInterceptor', + "BusinessIdentityServiceTransport", + "BusinessIdentityServiceGrpcTransport", + "BusinessIdentityServiceGrpcAsyncIOTransport", + "BusinessIdentityServiceRestTransport", + "BusinessIdentityServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py index 971bcbe15a51..e0ac4fb58da5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import businessidentity -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__ @@ -38,24 +39,23 @@ class BusinessIdentityServiceTransport(abc.ABC): """Abstract transport class for BusinessIdentityService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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 get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - Union[ - businessidentity.BusinessIdentity, - Awaitable[businessidentity.BusinessIdentity] - ]]: + def get_business_identity( + self, + ) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + Union[ + businessidentity.BusinessIdentity, + Awaitable[businessidentity.BusinessIdentity], + ], + ]: raise NotImplementedError() @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - Union[ - businessidentity.BusinessIdentity, - Awaitable[businessidentity.BusinessIdentity] - ]]: + def update_business_identity( + self, + ) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + Union[ + businessidentity.BusinessIdentity, + Awaitable[businessidentity.BusinessIdentity], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'BusinessIdentityServiceTransport', -) +__all__ = ("BusinessIdentityServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py index 3b03093ac306..c344e0731327 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import businessidentity -from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, BusinessIdentityServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,23 +121,26 @@ class BusinessIdentityServiceGrpcTransport(BusinessIdentityServiceTransport): 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,20 @@ 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 get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - businessidentity.BusinessIdentity]: + def get_business_identity( + self, + ) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], businessidentity.BusinessIdentity + ]: r"""Return a callable for the get business identity method over gRPC. Retrieves the business identity of an account. @@ -327,18 +341,21 @@ def get_business_identity(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_business_identity' not in self._stubs: - self._stubs['get_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessIdentityService/GetBusinessIdentity', + if "get_business_identity" not in self._stubs: + self._stubs["get_business_identity"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessIdentityService/GetBusinessIdentity", request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, response_deserializer=businessidentity.BusinessIdentity.deserialize, ) - return self._stubs['get_business_identity'] + return self._stubs["get_business_identity"] @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - businessidentity.BusinessIdentity]: + def update_business_identity( + self, + ) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + businessidentity.BusinessIdentity, + ]: r"""Return a callable for the update business identity method over gRPC. Updates the business identity of an account. @@ -354,13 +371,13 @@ def update_business_identity(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_business_identity' not in self._stubs: - self._stubs['update_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessIdentityService/UpdateBusinessIdentity', + if "update_business_identity" not in self._stubs: + self._stubs["update_business_identity"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessIdentityService/UpdateBusinessIdentity", request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, response_deserializer=businessidentity.BusinessIdentity.deserialize, ) - return self._stubs['update_business_identity'] + return self._stubs["update_business_identity"] def close(self): self._logged_channel.close() @@ -370,6 +387,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'BusinessIdentityServiceGrpcTransport', -) +__all__ = ("BusinessIdentityServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py index 05110ef91b55..fcfc184bfdac 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import businessidentity -from .base import BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, BusinessIdentityServiceTransport from .grpc import BusinessIdentityServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -124,13 +132,15 @@ class BusinessIdentityServiceGrpcAsyncIOTransport(BusinessIdentityServiceTranspo _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 get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - Awaitable[businessidentity.BusinessIdentity]]: + def get_business_identity( + self, + ) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], + Awaitable[businessidentity.BusinessIdentity], + ]: r"""Return a callable for the get business identity method over gRPC. Retrieves the business identity of an account. @@ -333,18 +350,21 @@ def get_business_identity(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_business_identity' not in self._stubs: - self._stubs['get_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessIdentityService/GetBusinessIdentity', + if "get_business_identity" not in self._stubs: + self._stubs["get_business_identity"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessIdentityService/GetBusinessIdentity", request_serializer=businessidentity.GetBusinessIdentityRequest.serialize, response_deserializer=businessidentity.BusinessIdentity.deserialize, ) - return self._stubs['get_business_identity'] + return self._stubs["get_business_identity"] @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - Awaitable[businessidentity.BusinessIdentity]]: + def update_business_identity( + self, + ) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + Awaitable[businessidentity.BusinessIdentity], + ]: r"""Return a callable for the update business identity method over gRPC. Updates the business identity of an account. @@ -360,16 +380,16 @@ def update_business_identity(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_business_identity' not in self._stubs: - self._stubs['update_business_identity'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessIdentityService/UpdateBusinessIdentity', + if "update_business_identity" not in self._stubs: + self._stubs["update_business_identity"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessIdentityService/UpdateBusinessIdentity", request_serializer=businessidentity.UpdateBusinessIdentityRequest.serialize, response_deserializer=businessidentity.BusinessIdentity.deserialize, ) - return self._stubs['update_business_identity'] + return self._stubs["update_business_identity"] 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.get_business_identity: self._wrap_method( self.get_business_identity, @@ -396,6 +416,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'BusinessIdentityServiceGrpcAsyncIOTransport', -) +__all__ = ("BusinessIdentityServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py index c10c0fa1caea..06f3d220c366 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import businessidentity - -from .rest_base import _BaseBusinessIdentityServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseBusinessIdentityServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,15 @@ def post_update_business_identity(self, response): """ - def pre_get_business_identity(self, request: businessidentity.GetBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.GetBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_business_identity( + self, + request: businessidentity.GetBusinessIdentityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + businessidentity.GetBusinessIdentityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_business_identity Override in a subclass to manipulate the request or metadata @@ -106,7 +109,9 @@ def pre_get_business_identity(self, request: businessidentity.GetBusinessIdentit """ return request, metadata - def post_get_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: + def post_get_business_identity( + self, response: businessidentity.BusinessIdentity + ) -> businessidentity.BusinessIdentity: """Post-rpc interceptor for get_business_identity DEPRECATED. Please use the `post_get_business_identity_with_metadata` @@ -119,7 +124,13 @@ def post_get_business_identity(self, response: businessidentity.BusinessIdentity """ return response - def post_get_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_business_identity_with_metadata( + self, + response: businessidentity.BusinessIdentity, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_business_identity Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +145,14 @@ def post_get_business_identity_with_metadata(self, response: businessidentity.Bu """ return response, metadata - def pre_update_business_identity(self, request: businessidentity.UpdateBusinessIdentityRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.UpdateBusinessIdentityRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_business_identity( + self, + request: businessidentity.UpdateBusinessIdentityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + businessidentity.UpdateBusinessIdentityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_business_identity Override in a subclass to manipulate the request or metadata @@ -142,7 +160,9 @@ def pre_update_business_identity(self, request: businessidentity.UpdateBusinessI """ return request, metadata - def post_update_business_identity(self, response: businessidentity.BusinessIdentity) -> businessidentity.BusinessIdentity: + def post_update_business_identity( + self, response: businessidentity.BusinessIdentity + ) -> businessidentity.BusinessIdentity: """Post-rpc interceptor for update_business_identity DEPRECATED. Please use the `post_update_business_identity_with_metadata` @@ -155,7 +175,13 @@ def post_update_business_identity(self, response: businessidentity.BusinessIdent """ return response - def post_update_business_identity_with_metadata(self, response: businessidentity.BusinessIdentity, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_business_identity_with_metadata( + self, + response: businessidentity.BusinessIdentity, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + businessidentity.BusinessIdentity, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for update_business_identity Override in a subclass to read or manipulate the response or metadata after it @@ -192,20 +218,21 @@ class BusinessIdentityServiceRestTransport(_BaseBusinessIdentityServiceRestTrans 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[BusinessIdentityServiceRestInterceptor] = 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[BusinessIdentityServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -248,16 +275,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 BusinessIdentityServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity, BusinessIdentityServiceRestStub): + class _GetBusinessIdentity( + _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity, + BusinessIdentityServiceRestStub, + ): def __hash__(self): return hash("BusinessIdentityServiceRestTransport.GetBusinessIdentity") @@ -269,26 +300,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: businessidentity.GetBusinessIdentityRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessidentity.BusinessIdentity: + def __call__( + self, + request: businessidentity.GetBusinessIdentityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: r"""Call the get business identity method over HTTP. Args: @@ -309,30 +342,42 @@ def __call__(self, """ - http_options = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_http_options() + http_options = ( + _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_http_options() + ) - request, metadata = self._interceptor.pre_get_business_identity(request, metadata) - transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_business_identity( + request, metadata + ) + transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessIdentityServiceClient.GetBusinessIdentity", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": "GetBusinessIdentity", "httpRequest": http_request, @@ -341,7 +386,16 @@ def __call__(self, ) # Send the request - response = BusinessIdentityServiceRestTransport._GetBusinessIdentity._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + BusinessIdentityServiceRestTransport._GetBusinessIdentity._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -356,20 +410,26 @@ def __call__(self, resp = self._interceptor.post_get_business_identity(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_business_identity_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_business_identity_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = businessidentity.BusinessIdentity.to_json(response) + response_payload = businessidentity.BusinessIdentity.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.accounts_v1.BusinessIdentityServiceClient.get_business_identity", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": "GetBusinessIdentity", "metadata": http_response["headers"], @@ -378,7 +438,10 @@ def __call__(self, ) return resp - class _UpdateBusinessIdentity(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity, BusinessIdentityServiceRestStub): + class _UpdateBusinessIdentity( + _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity, + BusinessIdentityServiceRestStub, + ): def __hash__(self): return hash("BusinessIdentityServiceRestTransport.UpdateBusinessIdentity") @@ -390,27 +453,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: businessidentity.UpdateBusinessIdentityRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessidentity.BusinessIdentity: + def __call__( + self, + request: businessidentity.UpdateBusinessIdentityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessidentity.BusinessIdentity: r"""Call the update business identity method over HTTP. Args: @@ -432,32 +497,46 @@ def __call__(self, """ - http_options = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_http_options() + http_options = ( + _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_http_options() + ) - request, metadata = self._interceptor.pre_update_business_identity(request, metadata) - transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_business_identity( + request, metadata + ) + transcoded_request = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_transcoded_request( + http_options, request + ) - body = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_request_body_json(transcoded_request) + body = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessIdentityServiceClient.UpdateBusinessIdentity", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": "UpdateBusinessIdentity", "httpRequest": http_request, @@ -466,7 +545,15 @@ def __call__(self, ) # Send the request - response = BusinessIdentityServiceRestTransport._UpdateBusinessIdentity._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = BusinessIdentityServiceRestTransport._UpdateBusinessIdentity._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. @@ -481,20 +568,26 @@ def __call__(self, resp = self._interceptor.post_update_business_identity(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_business_identity_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_business_identity_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = businessidentity.BusinessIdentity.to_json(response) + response_payload = businessidentity.BusinessIdentity.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.accounts_v1.BusinessIdentityServiceClient.update_business_identity", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessIdentityService", "rpcName": "UpdateBusinessIdentity", "metadata": http_response["headers"], @@ -504,20 +597,25 @@ def __call__(self, return resp @property - def get_business_identity(self) -> Callable[ - [businessidentity.GetBusinessIdentityRequest], - businessidentity.BusinessIdentity]: + def get_business_identity( + self, + ) -> Callable[ + [businessidentity.GetBusinessIdentityRequest], businessidentity.BusinessIdentity + ]: # 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._GetBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore + return self._GetBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore @property - def update_business_identity(self) -> Callable[ - [businessidentity.UpdateBusinessIdentityRequest], - businessidentity.BusinessIdentity]: + def update_business_identity( + self, + ) -> Callable[ + [businessidentity.UpdateBusinessIdentityRequest], + businessidentity.BusinessIdentity, + ]: # 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._UpdateBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateBusinessIdentity(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -527,6 +625,4 @@ def close(self): self._session.close() -__all__=( - 'BusinessIdentityServiceRestTransport', -) +__all__ = ("BusinessIdentityServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py similarity index 64% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py index cc9e2447fde6..a709814f4178 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_identity_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 BusinessIdentityServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import businessidentity +from .base import DEFAULT_CLIENT_INFO, BusinessIdentityServiceTransport + class _BaseBusinessIdentityServiceRestTransport(BusinessIdentityServiceTransport): """Base REST backend transport for BusinessIdentityService. @@ -40,14 +38,16 @@ class _BaseBusinessIdentityServiceRestTransport(BusinessIdentityServiceTransport 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseGetBusinessIdentity: 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': '/accounts/v1/{name=accounts/*/businessIdentity}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/businessIdentity}", + }, ] return http_options @@ -113,11 +119,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(_BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._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( + _BaseBusinessIdentityServiceRestTransport._BaseGetBusinessIdentity._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,20 +138,24 @@ class _BaseUpdateBusinessIdentity: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{business_identity.name=accounts/*/businessIdentity}', - 'body': 'business_identity', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{business_identity.name=accounts/*/businessIdentity}", + "body": "business_identity", + }, ] return http_options @@ -154,22 +170,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._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( + _BaseBusinessIdentityServiceRestTransport._BaseUpdateBusinessIdentity._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseBusinessIdentityServiceRestTransport', -) +__all__ = ("_BaseBusinessIdentityServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py index df547a28f156..fdeade710727 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import BusinessInfoServiceClient from .async_client import BusinessInfoServiceAsyncClient +from .client import BusinessInfoServiceClient __all__ = ( - 'BusinessInfoServiceClient', - 'BusinessInfoServiceAsyncClient', + "BusinessInfoServiceClient", + "BusinessInfoServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py index 503f3b57907f..47249ff884c7 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,23 +45,29 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import businessinfo -from google.shopping.merchant_accounts_v1.types import customerservice -from google.shopping.merchant_accounts_v1.types import phoneverificationstate from google.type import phone_number_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore -from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport + +from google.shopping.merchant_accounts_v1.types import ( + businessinfo, + customerservice, + phoneverificationstate, +) + from .client import BusinessInfoServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, BusinessInfoServiceTransport +from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport 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 BusinessInfoServiceAsyncClient: """Service to support business info API.""" @@ -65,17 +81,33 @@ class BusinessInfoServiceAsyncClient: _DEFAULT_UNIVERSE = BusinessInfoServiceClient._DEFAULT_UNIVERSE business_info_path = staticmethod(BusinessInfoServiceClient.business_info_path) - parse_business_info_path = staticmethod(BusinessInfoServiceClient.parse_business_info_path) - common_billing_account_path = staticmethod(BusinessInfoServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(BusinessInfoServiceClient.parse_common_billing_account_path) + parse_business_info_path = staticmethod( + BusinessInfoServiceClient.parse_business_info_path + ) + common_billing_account_path = staticmethod( + BusinessInfoServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + BusinessInfoServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(BusinessInfoServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(BusinessInfoServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(BusinessInfoServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(BusinessInfoServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + BusinessInfoServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + BusinessInfoServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + BusinessInfoServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(BusinessInfoServiceClient.common_project_path) - parse_common_project_path = staticmethod(BusinessInfoServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + BusinessInfoServiceClient.parse_common_project_path + ) common_location_path = staticmethod(BusinessInfoServiceClient.common_location_path) - parse_common_location_path = staticmethod(BusinessInfoServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + BusinessInfoServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -111,7 +143,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: @@ -174,12 +208,20 @@ def universe_domain(self) -> str: get_transport_class = BusinessInfoServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = "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, + BusinessInfoServiceTransport, + Callable[..., BusinessInfoServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the business info service async client. Args: @@ -234,31 +276,39 @@ 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.accounts_v1.BusinessInfoServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", - "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.accounts.v1.BusinessInfoService", "credentialsType": None, - } + }, ) - async def get_business_info(self, - request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: + async def get_business_info( + self, + request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: r"""Retrieves the business info of an account. .. code-block:: python @@ -320,10 +370,14 @@ async def sample_get_business_info(): # - 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. @@ -337,14 +391,14 @@ async def sample_get_business_info(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_business_info] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_business_info + ] # 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. @@ -361,15 +415,16 @@ async def sample_get_business_info(): # Done; return the response. return response - async def update_business_info(self, - request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, - *, - business_info: Optional[businessinfo.BusinessInfo] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: + async def update_business_info( + self, + request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, + *, + business_info: Optional[businessinfo.BusinessInfo] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: r"""Updates the business info of an account. Executing this method requires admin access. @@ -443,10 +498,14 @@ async def sample_update_business_info(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [business_info, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -462,14 +521,16 @@ async def sample_update_business_info(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_business_info] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_business_info + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_info.name", request.business_info.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("business_info.name", request.business_info.name),) + ), ) # Validate the universe domain. @@ -492,12 +553,13 @@ async def __aenter__(self) -> "BusinessInfoServiceAsyncClient": 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__ = ( - "BusinessInfoServiceAsyncClient", -) +__all__ = ("BusinessInfoServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/client.py index 481fc3b7bedc..fa855cdb3c07 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,12 +62,16 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import businessinfo -from google.shopping.merchant_accounts_v1.types import customerservice -from google.shopping.merchant_accounts_v1.types import phoneverificationstate from google.type import phone_number_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore -from .transports.base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO + +from google.shopping.merchant_accounts_v1.types import ( + businessinfo, + customerservice, + phoneverificationstate, +) + +from .transports.base import DEFAULT_CLIENT_INFO, BusinessInfoServiceTransport from .transports.grpc import BusinessInfoServiceGrpcTransport from .transports.grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport from .transports.rest import BusinessInfoServiceRestTransport @@ -67,14 +84,18 @@ class BusinessInfoServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[BusinessInfoServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[BusinessInfoServiceTransport]] _transport_registry["grpc"] = BusinessInfoServiceGrpcTransport _transport_registry["grpc_asyncio"] = BusinessInfoServiceGrpcAsyncIOTransport _transport_registry["rest"] = BusinessInfoServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[BusinessInfoServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[BusinessInfoServiceTransport]: """Returns an appropriate transport class. Args: @@ -166,8 +187,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: BusinessInfoServiceClient: 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) @@ -184,73 +204,101 @@ def transport(self) -> BusinessInfoServiceTransport: return self._transport @staticmethod - def business_info_path(account: str,) -> str: + def business_info_path( + account: str, + ) -> str: """Returns a fully-qualified business_info string.""" - return "accounts/{account}/businessInfo".format(account=account, ) + return "accounts/{account}/businessInfo".format( + account=account, + ) @staticmethod - def parse_business_info_path(path: str) -> Dict[str,str]: + def parse_business_info_path(path: str) -> Dict[str, str]: """Parses a business_info path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/businessInfo$", 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: @@ -282,16 +330,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 @@ -304,7 +358,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 @@ -325,13 +381,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 @@ -354,7 +416,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: @@ -370,17 +434,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = BusinessInfoServiceClient._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 = BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = BusinessInfoServiceClient._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: @@ -416,15 +488,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 @@ -457,12 +532,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, BusinessInfoServiceTransport, Callable[..., BusinessInfoServiceTransport]]] = 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, + BusinessInfoServiceTransport, + Callable[..., BusinessInfoServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the business info service client. Args: @@ -517,14 +600,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 = BusinessInfoServiceClient._read_environment_variables() - self._client_cert_source = BusinessInfoServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = BusinessInfoServiceClient._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, + ) = BusinessInfoServiceClient._read_environment_variables() + self._client_cert_source = BusinessInfoServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = BusinessInfoServiceClient._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 @@ -535,7 +628,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 @@ -544,8 +639,10 @@ def __init__(self, *, if transport_provided: # transport is a BusinessInfoServiceTransport 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 " @@ -554,20 +651,30 @@ def __init__(self, *, self._transport = cast(BusinessInfoServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - BusinessInfoServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or BusinessInfoServiceClient._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[BusinessInfoServiceTransport], Callable[..., BusinessInfoServiceTransport]] = ( + transport_init: Union[ + Type[BusinessInfoServiceTransport], + Callable[..., BusinessInfoServiceTransport], + ] = ( BusinessInfoServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., BusinessInfoServiceTransport], transport) @@ -586,28 +693,37 @@ 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.accounts_v1.BusinessInfoServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", - "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.accounts.v1.BusinessInfoService", "credentialsType": None, - } + }, ) - def get_business_info(self, - request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: + def get_business_info( + self, + request: Optional[Union[businessinfo.GetBusinessInfoRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: r"""Retrieves the business info of an account. .. code-block:: python @@ -669,10 +785,14 @@ def sample_get_business_info(): # - 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. @@ -690,9 +810,7 @@ def sample_get_business_info(): # 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. @@ -709,15 +827,16 @@ def sample_get_business_info(): # Done; return the response. return response - def update_business_info(self, - request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, - *, - business_info: Optional[businessinfo.BusinessInfo] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> businessinfo.BusinessInfo: + def update_business_info( + self, + request: Optional[Union[businessinfo.UpdateBusinessInfoRequest, dict]] = None, + *, + business_info: Optional[businessinfo.BusinessInfo] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: r"""Updates the business info of an account. Executing this method requires admin access. @@ -791,10 +910,14 @@ def sample_update_business_info(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [business_info, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -814,9 +937,9 @@ def sample_update_business_info(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("business_info.name", request.business_info.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("business_info.name", request.business_info.name),) + ), ) # Validate the universe domain. @@ -847,16 +970,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__ = ( - "BusinessInfoServiceClient", -) +__all__ = ("BusinessInfoServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py index cd3235917a9f..e3e121d4cafc 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/business_info_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/__init__.py @@ -19,20 +19,20 @@ from .base import BusinessInfoServiceTransport from .grpc import BusinessInfoServiceGrpcTransport from .grpc_asyncio import BusinessInfoServiceGrpcAsyncIOTransport -from .rest import BusinessInfoServiceRestTransport -from .rest import BusinessInfoServiceRestInterceptor - +from .rest import BusinessInfoServiceRestInterceptor, BusinessInfoServiceRestTransport # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[BusinessInfoServiceTransport]] -_transport_registry['grpc'] = BusinessInfoServiceGrpcTransport -_transport_registry['grpc_asyncio'] = BusinessInfoServiceGrpcAsyncIOTransport -_transport_registry['rest'] = BusinessInfoServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[BusinessInfoServiceTransport]] +_transport_registry["grpc"] = BusinessInfoServiceGrpcTransport +_transport_registry["grpc_asyncio"] = BusinessInfoServiceGrpcAsyncIOTransport +_transport_registry["rest"] = BusinessInfoServiceRestTransport __all__ = ( - 'BusinessInfoServiceTransport', - 'BusinessInfoServiceGrpcTransport', - 'BusinessInfoServiceGrpcAsyncIOTransport', - 'BusinessInfoServiceRestTransport', - 'BusinessInfoServiceRestInterceptor', + "BusinessInfoServiceTransport", + "BusinessInfoServiceGrpcTransport", + "BusinessInfoServiceGrpcAsyncIOTransport", + "BusinessInfoServiceRestTransport", + "BusinessInfoServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py index 0644a964efe5..6164da720b6b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import businessinfo -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__ @@ -38,24 +39,23 @@ class BusinessInfoServiceTransport(abc.ABC): """Abstract transport class for BusinessInfoService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,33 @@ 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 get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - Union[ - businessinfo.BusinessInfo, - Awaitable[businessinfo.BusinessInfo] - ]]: + def get_business_info( + self, + ) -> Callable[ + [businessinfo.GetBusinessInfoRequest], + Union[businessinfo.BusinessInfo, Awaitable[businessinfo.BusinessInfo]], + ]: raise NotImplementedError() @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - Union[ - businessinfo.BusinessInfo, - Awaitable[businessinfo.BusinessInfo] - ]]: + def update_business_info( + self, + ) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], + Union[businessinfo.BusinessInfo, Awaitable[businessinfo.BusinessInfo]], + ]: raise NotImplementedError() @property @@ -168,6 +176,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'BusinessInfoServiceTransport', -) +__all__ = ("BusinessInfoServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py index b37d363e12a9..79363b35d746 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import businessinfo -from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, BusinessInfoServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": client_call_details.method, "response": grpc_response, @@ -113,23 +119,26 @@ class BusinessInfoServiceGrpcTransport(BusinessInfoServiceTransport): 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: @@ -251,19 +260,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. @@ -298,19 +311,18 @@ 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 get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - businessinfo.BusinessInfo]: + def get_business_info( + self, + ) -> Callable[[businessinfo.GetBusinessInfoRequest], businessinfo.BusinessInfo]: r"""Return a callable for the get business info method over gRPC. Retrieves the business info of an account. @@ -325,18 +337,18 @@ def get_business_info(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_business_info' not in self._stubs: - self._stubs['get_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessInfoService/GetBusinessInfo', + if "get_business_info" not in self._stubs: + self._stubs["get_business_info"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessInfoService/GetBusinessInfo", request_serializer=businessinfo.GetBusinessInfoRequest.serialize, response_deserializer=businessinfo.BusinessInfo.deserialize, ) - return self._stubs['get_business_info'] + return self._stubs["get_business_info"] @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - businessinfo.BusinessInfo]: + def update_business_info( + self, + ) -> Callable[[businessinfo.UpdateBusinessInfoRequest], businessinfo.BusinessInfo]: r"""Return a callable for the update business info method over gRPC. Updates the business info of an account. Executing @@ -352,13 +364,13 @@ def update_business_info(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_business_info' not in self._stubs: - self._stubs['update_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessInfoService/UpdateBusinessInfo', + if "update_business_info" not in self._stubs: + self._stubs["update_business_info"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessInfoService/UpdateBusinessInfo", request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, response_deserializer=businessinfo.BusinessInfo.deserialize, ) - return self._stubs['update_business_info'] + return self._stubs["update_business_info"] def close(self): self._logged_channel.close() @@ -368,6 +380,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'BusinessInfoServiceGrpcTransport', -) +__all__ = ("BusinessInfoServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py index 86f371dc6443..211f78c1c9b0 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import businessinfo -from .base import BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, BusinessInfoServiceTransport from .grpc import BusinessInfoServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -122,13 +130,15 @@ class BusinessInfoServiceGrpcAsyncIOTransport(BusinessInfoServiceTransport): _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. @@ -158,24 +168,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: @@ -299,7 +311,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) @@ -314,9 +328,11 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - Awaitable[businessinfo.BusinessInfo]]: + def get_business_info( + self, + ) -> Callable[ + [businessinfo.GetBusinessInfoRequest], Awaitable[businessinfo.BusinessInfo] + ]: r"""Return a callable for the get business info method over gRPC. Retrieves the business info of an account. @@ -331,18 +347,20 @@ def get_business_info(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_business_info' not in self._stubs: - self._stubs['get_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessInfoService/GetBusinessInfo', + if "get_business_info" not in self._stubs: + self._stubs["get_business_info"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessInfoService/GetBusinessInfo", request_serializer=businessinfo.GetBusinessInfoRequest.serialize, response_deserializer=businessinfo.BusinessInfo.deserialize, ) - return self._stubs['get_business_info'] + return self._stubs["get_business_info"] @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - Awaitable[businessinfo.BusinessInfo]]: + def update_business_info( + self, + ) -> Callable[ + [businessinfo.UpdateBusinessInfoRequest], Awaitable[businessinfo.BusinessInfo] + ]: r"""Return a callable for the update business info method over gRPC. Updates the business info of an account. Executing @@ -358,16 +376,16 @@ def update_business_info(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_business_info' not in self._stubs: - self._stubs['update_business_info'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.BusinessInfoService/UpdateBusinessInfo', + if "update_business_info" not in self._stubs: + self._stubs["update_business_info"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.BusinessInfoService/UpdateBusinessInfo", request_serializer=businessinfo.UpdateBusinessInfoRequest.serialize, response_deserializer=businessinfo.BusinessInfo.deserialize, ) - return self._stubs['update_business_info'] + return self._stubs["update_business_info"] 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.get_business_info: self._wrap_method( self.get_business_info, @@ -394,6 +412,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'BusinessInfoServiceGrpcAsyncIOTransport', -) +__all__ = ("BusinessInfoServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py similarity index 73% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py index b6403bcd3356..586dacc2d020 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import businessinfo - -from .rest_base import _BaseBusinessInfoServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseBusinessInfoServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,14 @@ def post_update_business_info(self, response): """ - def pre_get_business_info(self, request: businessinfo.GetBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_business_info( + self, + request: businessinfo.GetBusinessInfoRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + businessinfo.GetBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_business_info Override in a subclass to manipulate the request or metadata @@ -106,7 +108,9 @@ def pre_get_business_info(self, request: businessinfo.GetBusinessInfoRequest, me """ return request, metadata - def post_get_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: + def post_get_business_info( + self, response: businessinfo.BusinessInfo + ) -> businessinfo.BusinessInfo: """Post-rpc interceptor for get_business_info DEPRECATED. Please use the `post_get_business_info_with_metadata` @@ -119,7 +123,11 @@ def post_get_business_info(self, response: businessinfo.BusinessInfo) -> busines """ return response - def post_get_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_business_info_with_metadata( + self, + response: businessinfo.BusinessInfo, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_business_info Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +142,13 @@ def post_get_business_info_with_metadata(self, response: businessinfo.BusinessIn """ return response, metadata - def pre_update_business_info(self, request: businessinfo.UpdateBusinessInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_business_info( + self, + request: businessinfo.UpdateBusinessInfoRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + businessinfo.UpdateBusinessInfoRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_business_info Override in a subclass to manipulate the request or metadata @@ -142,7 +156,9 @@ def pre_update_business_info(self, request: businessinfo.UpdateBusinessInfoReque """ return request, metadata - def post_update_business_info(self, response: businessinfo.BusinessInfo) -> businessinfo.BusinessInfo: + def post_update_business_info( + self, response: businessinfo.BusinessInfo + ) -> businessinfo.BusinessInfo: """Post-rpc interceptor for update_business_info DEPRECATED. Please use the `post_update_business_info_with_metadata` @@ -155,7 +171,11 @@ def post_update_business_info(self, response: businessinfo.BusinessInfo) -> busi """ return response - def post_update_business_info_with_metadata(self, response: businessinfo.BusinessInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_business_info_with_metadata( + self, + response: businessinfo.BusinessInfo, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[businessinfo.BusinessInfo, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_business_info Override in a subclass to read or manipulate the response or metadata after it @@ -190,20 +210,21 @@ class BusinessInfoServiceRestTransport(_BaseBusinessInfoServiceRestTransport): 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[BusinessInfoServiceRestInterceptor] = 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[BusinessInfoServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -246,16 +267,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 BusinessInfoServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo, BusinessInfoServiceRestStub): + class _GetBusinessInfo( + _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo, + BusinessInfoServiceRestStub, + ): def __hash__(self): return hash("BusinessInfoServiceRestTransport.GetBusinessInfo") @@ -267,26 +292,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: businessinfo.GetBusinessInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessinfo.BusinessInfo: + def __call__( + self, + request: businessinfo.GetBusinessInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: r"""Call the get business info method over HTTP. Args: @@ -311,30 +338,42 @@ def __call__(self, """ - http_options = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_http_options() + http_options = ( + _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_http_options() + ) - request, metadata = self._interceptor.pre_get_business_info(request, metadata) - transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_business_info( + request, metadata + ) + transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessInfoServiceClient.GetBusinessInfo", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": "GetBusinessInfo", "httpRequest": http_request, @@ -343,7 +382,14 @@ def __call__(self, ) # Send the request - response = BusinessInfoServiceRestTransport._GetBusinessInfo._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = BusinessInfoServiceRestTransport._GetBusinessInfo._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -358,20 +404,24 @@ def __call__(self, resp = self._interceptor.post_get_business_info(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_business_info_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_business_info_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = businessinfo.BusinessInfo.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.accounts_v1.BusinessInfoServiceClient.get_business_info", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": "GetBusinessInfo", "metadata": http_response["headers"], @@ -380,7 +430,10 @@ def __call__(self, ) return resp - class _UpdateBusinessInfo(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo, BusinessInfoServiceRestStub): + class _UpdateBusinessInfo( + _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo, + BusinessInfoServiceRestStub, + ): def __hash__(self): return hash("BusinessInfoServiceRestTransport.UpdateBusinessInfo") @@ -392,27 +445,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: businessinfo.UpdateBusinessInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> businessinfo.BusinessInfo: + def __call__( + self, + request: businessinfo.UpdateBusinessInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> businessinfo.BusinessInfo: r"""Call the update business info method over HTTP. Args: @@ -437,32 +492,46 @@ def __call__(self, """ - http_options = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_http_options() + http_options = ( + _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_http_options() + ) - request, metadata = self._interceptor.pre_update_business_info(request, metadata) - transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_business_info( + request, metadata + ) + transcoded_request = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_transcoded_request( + http_options, request + ) - body = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_request_body_json(transcoded_request) + body = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.BusinessInfoServiceClient.UpdateBusinessInfo", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": "UpdateBusinessInfo", "httpRequest": http_request, @@ -471,7 +540,17 @@ def __call__(self, ) # Send the request - response = BusinessInfoServiceRestTransport._UpdateBusinessInfo._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + BusinessInfoServiceRestTransport._UpdateBusinessInfo._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. @@ -486,20 +565,24 @@ def __call__(self, resp = self._interceptor.post_update_business_info(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_business_info_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_business_info_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = businessinfo.BusinessInfo.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.accounts_v1.BusinessInfoServiceClient.update_business_info", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.BusinessInfoService", "rpcName": "UpdateBusinessInfo", "metadata": http_response["headers"], @@ -509,20 +592,20 @@ def __call__(self, return resp @property - def get_business_info(self) -> Callable[ - [businessinfo.GetBusinessInfoRequest], - businessinfo.BusinessInfo]: + def get_business_info( + self, + ) -> Callable[[businessinfo.GetBusinessInfoRequest], businessinfo.BusinessInfo]: # 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._GetBusinessInfo(self._session, self._host, self._interceptor) # type: ignore + return self._GetBusinessInfo(self._session, self._host, self._interceptor) # type: ignore @property - def update_business_info(self) -> Callable[ - [businessinfo.UpdateBusinessInfoRequest], - businessinfo.BusinessInfo]: + def update_business_info( + self, + ) -> Callable[[businessinfo.UpdateBusinessInfoRequest], businessinfo.BusinessInfo]: # 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._UpdateBusinessInfo(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateBusinessInfo(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -532,6 +615,4 @@ def close(self): self._session.close() -__all__=( - 'BusinessInfoServiceRestTransport', -) +__all__ = ("BusinessInfoServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py index 200b5f0fbbe2..e707add78d2d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/business_info_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 BusinessInfoServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import businessinfo +from .base import DEFAULT_CLIENT_INFO, BusinessInfoServiceTransport + class _BaseBusinessInfoServiceRestTransport(BusinessInfoServiceTransport): """Base REST backend transport for BusinessInfoService. @@ -40,14 +38,16 @@ class _BaseBusinessInfoServiceRestTransport(BusinessInfoServiceTransport): 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseGetBusinessInfo: 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': '/accounts/v1/{name=accounts/*/businessInfo}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/businessInfo}", + }, ] return http_options @@ -113,11 +119,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(_BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._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( + _BaseBusinessInfoServiceRestTransport._BaseGetBusinessInfo._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,20 +138,24 @@ class _BaseUpdateBusinessInfo: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{business_info.name=accounts/*/businessInfo}', - 'body': 'business_info', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{business_info.name=accounts/*/businessInfo}", + "body": "business_info", + }, ] return http_options @@ -154,22 +170,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._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( + _BaseBusinessInfoServiceRestTransport._BaseUpdateBusinessInfo._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseBusinessInfoServiceRestTransport', -) +__all__ = ("_BaseBusinessInfoServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py index d3119c55bf22..05d1f616fa0e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import CheckoutSettingsServiceClient from .async_client import CheckoutSettingsServiceAsyncClient +from .client import CheckoutSettingsServiceClient __all__ = ( - 'CheckoutSettingsServiceClient', - 'CheckoutSettingsServiceAsyncClient', + "CheckoutSettingsServiceClient", + "CheckoutSettingsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py index 445312673570..617e5c525d1c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,20 +45,24 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import checkoutsettings from google.shopping.type.types import types -from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport + +from google.shopping.merchant_accounts_v1.types import checkoutsettings + from .client import CheckoutSettingsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, CheckoutSettingsServiceTransport +from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport 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 CheckoutSettingsServiceAsyncClient: """Service for supporting `checkout settings `__. @@ -60,21 +74,45 @@ class CheckoutSettingsServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.checkout_settings_path) - parse_checkout_settings_path = staticmethod(CheckoutSettingsServiceClient.parse_checkout_settings_path) - common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CheckoutSettingsServiceClient.parse_common_billing_account_path) + checkout_settings_path = staticmethod( + CheckoutSettingsServiceClient.checkout_settings_path + ) + parse_checkout_settings_path = staticmethod( + CheckoutSettingsServiceClient.parse_checkout_settings_path + ) + common_billing_account_path = staticmethod( + CheckoutSettingsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + CheckoutSettingsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(CheckoutSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CheckoutSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CheckoutSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CheckoutSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CheckoutSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(CheckoutSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(CheckoutSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(CheckoutSettingsServiceClient.parse_common_location_path) + parse_common_folder_path = staticmethod( + CheckoutSettingsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + CheckoutSettingsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + CheckoutSettingsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + CheckoutSettingsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + CheckoutSettingsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + CheckoutSettingsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + CheckoutSettingsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +148,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 +213,20 @@ def universe_domain(self) -> str: get_transport_class = CheckoutSettingsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = "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, + CheckoutSettingsServiceTransport, + Callable[..., CheckoutSettingsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the checkout settings service async client. Args: @@ -233,31 +281,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.accounts_v1.CheckoutSettingsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", - "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.accounts.v1.CheckoutSettingsService", "credentialsType": None, - } + }, ) - async def get_checkout_settings(self, - request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: + async def get_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.GetCheckoutSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Gets ``CheckoutSettings`` for the given merchant. This includes information about review state, enrollment state and URL settings. @@ -317,10 +375,14 @@ async def sample_get_checkout_settings(): # - 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. @@ -334,14 +396,14 @@ async def sample_get_checkout_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_checkout_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_checkout_settings + ] # 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. @@ -358,15 +420,18 @@ async def sample_get_checkout_settings(): # Done; return the response. return response - async def create_checkout_settings(self, - request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: + async def create_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.CreateCheckoutSettingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Creates ``CheckoutSettings`` for the given merchant. .. code-block:: python @@ -429,10 +494,14 @@ async def sample_create_checkout_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, checkout_settings] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -448,14 +517,14 @@ async def sample_create_checkout_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_checkout_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_checkout_settings + ] # 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. @@ -472,15 +541,18 @@ async def sample_create_checkout_settings(): # Done; return the response. return response - async def update_checkout_settings(self, - request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, - *, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: + async def update_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict] + ] = None, + *, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Updates ``CheckoutSettings`` for the given merchant. .. code-block:: python @@ -550,10 +622,14 @@ async def sample_update_checkout_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [checkout_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -569,14 +645,16 @@ async def sample_update_checkout_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_checkout_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_checkout_settings + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("checkout_settings.name", request.checkout_settings.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("checkout_settings.name", request.checkout_settings.name),) + ), ) # Validate the universe domain. @@ -593,14 +671,17 @@ async def sample_update_checkout_settings(): # Done; return the response. return response - async def delete_checkout_settings(self, - request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, - *, - name: 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_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict] + ] = None, + *, + name: 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 ``CheckoutSettings`` and unenrolls merchant from ``Checkout`` program. @@ -651,10 +732,14 @@ async def sample_delete_checkout_settings(): # - 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. @@ -668,14 +753,14 @@ async def sample_delete_checkout_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_checkout_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_checkout_settings + ] # 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. @@ -695,12 +780,13 @@ async def __aenter__(self) -> "CheckoutSettingsServiceAsyncClient": 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__ = ( - "CheckoutSettingsServiceAsyncClient", -) +__all__ = ("CheckoutSettingsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py index f89fd85cd42a..73d0d0053bba 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,9 +62,11 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import checkoutsettings from google.shopping.type.types import types -from .transports.base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from google.shopping.merchant_accounts_v1.types import checkoutsettings + +from .transports.base import DEFAULT_CLIENT_INFO, CheckoutSettingsServiceTransport from .transports.grpc import CheckoutSettingsServiceGrpcTransport from .transports.grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport from .transports.rest import CheckoutSettingsServiceRestTransport @@ -64,14 +79,18 @@ class CheckoutSettingsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[CheckoutSettingsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[CheckoutSettingsServiceTransport]] _transport_registry["grpc"] = CheckoutSettingsServiceGrpcTransport _transport_registry["grpc_asyncio"] = CheckoutSettingsServiceGrpcAsyncIOTransport _transport_registry["rest"] = CheckoutSettingsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CheckoutSettingsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[CheckoutSettingsServiceTransport]: """Returns an appropriate transport class. Args: @@ -165,8 +184,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: CheckoutSettingsServiceClient: 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 +201,106 @@ def transport(self) -> CheckoutSettingsServiceTransport: return self._transport @staticmethod - def checkout_settings_path(account: str,program: str,) -> str: + def checkout_settings_path( + account: str, + program: str, + ) -> str: """Returns a fully-qualified checkout_settings string.""" - return "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) + return "accounts/{account}/programs/{program}/checkoutSettings".format( + account=account, + program=program, + ) @staticmethod - def parse_checkout_settings_path(path: str) -> Dict[str,str]: + def parse_checkout_settings_path(path: str) -> Dict[str, str]: """Parses a checkout_settings path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/programs/(?P.+?)/checkoutSettings$", path) + m = re.match( + r"^accounts/(?P.+?)/programs/(?P.+?)/checkoutSettings$", + 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 +332,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 +360,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -324,13 +383,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 +418,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 +436,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 = CheckoutSettingsServiceClient._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 = CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + CheckoutSettingsServiceClient._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 +492,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 +536,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CheckoutSettingsServiceTransport, Callable[..., CheckoutSettingsServiceTransport]]] = 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, + CheckoutSettingsServiceTransport, + Callable[..., CheckoutSettingsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the checkout settings service client. Args: @@ -516,14 +604,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 = CheckoutSettingsServiceClient._read_environment_variables() - self._client_cert_source = CheckoutSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = CheckoutSettingsServiceClient._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, + ) = CheckoutSettingsServiceClient._read_environment_variables() + self._client_cert_source = ( + CheckoutSettingsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = CheckoutSettingsServiceClient._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 +634,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 +645,10 @@ def __init__(self, *, if transport_provided: # transport is a CheckoutSettingsServiceTransport 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 +657,30 @@ def __init__(self, *, self._transport = cast(CheckoutSettingsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - CheckoutSettingsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or CheckoutSettingsServiceClient._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[CheckoutSettingsServiceTransport], Callable[..., CheckoutSettingsServiceTransport]] = ( + transport_init: Union[ + Type[CheckoutSettingsServiceTransport], + Callable[..., CheckoutSettingsServiceTransport], + ] = ( CheckoutSettingsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., CheckoutSettingsServiceTransport], transport) @@ -585,28 +699,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.accounts_v1.CheckoutSettingsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", - "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.accounts.v1.CheckoutSettingsService", "credentialsType": None, - } + }, ) - def get_checkout_settings(self, - request: Optional[Union[checkoutsettings.GetCheckoutSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: + def get_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.GetCheckoutSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Gets ``CheckoutSettings`` for the given merchant. This includes information about review state, enrollment state and URL settings. @@ -666,10 +791,14 @@ def sample_get_checkout_settings(): # - 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. @@ -687,9 +816,7 @@ def sample_get_checkout_settings(): # 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. @@ -706,15 +833,18 @@ def sample_get_checkout_settings(): # Done; return the response. return response - def create_checkout_settings(self, - request: Optional[Union[checkoutsettings.CreateCheckoutSettingsRequest, dict]] = None, - *, - parent: Optional[str] = None, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: + def create_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.CreateCheckoutSettingsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Creates ``CheckoutSettings`` for the given merchant. .. code-block:: python @@ -777,10 +907,14 @@ def sample_create_checkout_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, checkout_settings] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -800,9 +934,7 @@ def sample_create_checkout_settings(): # 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. @@ -819,15 +951,18 @@ def sample_create_checkout_settings(): # Done; return the response. return response - def update_checkout_settings(self, - request: Optional[Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict]] = None, - *, - checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> checkoutsettings.CheckoutSettings: + def update_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.UpdateCheckoutSettingsRequest, dict] + ] = None, + *, + checkout_settings: Optional[checkoutsettings.CheckoutSettings] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Updates ``CheckoutSettings`` for the given merchant. .. code-block:: python @@ -897,10 +1032,14 @@ def sample_update_checkout_settings(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [checkout_settings, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -920,9 +1059,9 @@ def sample_update_checkout_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("checkout_settings.name", request.checkout_settings.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("checkout_settings.name", request.checkout_settings.name),) + ), ) # Validate the universe domain. @@ -939,14 +1078,17 @@ def sample_update_checkout_settings(): # Done; return the response. return response - def delete_checkout_settings(self, - request: Optional[Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict]] = None, - *, - name: 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_checkout_settings( + self, + request: Optional[ + Union[checkoutsettings.DeleteCheckoutSettingsRequest, dict] + ] = None, + *, + name: 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 ``CheckoutSettings`` and unenrolls merchant from ``Checkout`` program. @@ -997,10 +1139,14 @@ def sample_delete_checkout_settings(): # - 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. @@ -1018,9 +1164,7 @@ def sample_delete_checkout_settings(): # 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. @@ -1048,16 +1192,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__ = ( - "CheckoutSettingsServiceClient", -) +__all__ = ("CheckoutSettingsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py index e319afd3cf0a..4c06dfd646d8 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/checkout_settings_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import CheckoutSettingsServiceTransport from .grpc import CheckoutSettingsServiceGrpcTransport from .grpc_asyncio import CheckoutSettingsServiceGrpcAsyncIOTransport -from .rest import CheckoutSettingsServiceRestTransport -from .rest import CheckoutSettingsServiceRestInterceptor - +from .rest import ( + CheckoutSettingsServiceRestInterceptor, + CheckoutSettingsServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CheckoutSettingsServiceTransport]] -_transport_registry['grpc'] = CheckoutSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CheckoutSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = CheckoutSettingsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[CheckoutSettingsServiceTransport]] +_transport_registry["grpc"] = CheckoutSettingsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = CheckoutSettingsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = CheckoutSettingsServiceRestTransport __all__ = ( - 'CheckoutSettingsServiceTransport', - 'CheckoutSettingsServiceGrpcTransport', - 'CheckoutSettingsServiceGrpcAsyncIOTransport', - 'CheckoutSettingsServiceRestTransport', - 'CheckoutSettingsServiceRestInterceptor', + "CheckoutSettingsServiceTransport", + "CheckoutSettingsServiceGrpcTransport", + "CheckoutSettingsServiceGrpcAsyncIOTransport", + "CheckoutSettingsServiceRestTransport", + "CheckoutSettingsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py index 4b512fc233f2..297e14c8653d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import checkoutsettings -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 CheckoutSettingsServiceTransport(abc.ABC): """Abstract transport class for CheckoutSettingsService.""" - 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 @@ -145,51 +153,60 @@ 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 get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - Union[ - checkoutsettings.CheckoutSettings, - Awaitable[checkoutsettings.CheckoutSettings] - ]]: + def get_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings], + ], + ]: raise NotImplementedError() @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - Union[ - checkoutsettings.CheckoutSettings, - Awaitable[checkoutsettings.CheckoutSettings] - ]]: + def create_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings], + ], + ]: raise NotImplementedError() @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - Union[ - checkoutsettings.CheckoutSettings, - Awaitable[checkoutsettings.CheckoutSettings] - ]]: + def update_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + Union[ + checkoutsettings.CheckoutSettings, + Awaitable[checkoutsettings.CheckoutSettings], + ], + ]: raise NotImplementedError() @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -197,6 +214,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'CheckoutSettingsServiceTransport', -) +__all__ = ("CheckoutSettingsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py index c7b4de46ebd4..65b61050a2ef 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_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_accounts_v1.types import checkoutsettings -from .base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, CheckoutSettingsServiceTransport 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.accounts.v1.CheckoutSettingsService", "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.accounts.v1.CheckoutSettingsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,23 +121,26 @@ class CheckoutSettingsServiceGrpcTransport(CheckoutSettingsServiceTransport): 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,20 @@ 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 get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: + def get_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], checkoutsettings.CheckoutSettings + ]: r"""Return a callable for the get checkout settings method over gRPC. Gets ``CheckoutSettings`` for the given merchant. This includes @@ -329,18 +343,21 @@ def get_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_checkout_settings' not in self._stubs: - self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/GetCheckoutSettings', + if "get_checkout_settings" not in self._stubs: + self._stubs["get_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/GetCheckoutSettings", request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, response_deserializer=checkoutsettings.CheckoutSettings.deserialize, ) - return self._stubs['get_checkout_settings'] + return self._stubs["get_checkout_settings"] @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: + def create_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings, + ]: r"""Return a callable for the create checkout settings method over gRPC. Creates ``CheckoutSettings`` for the given merchant. @@ -355,18 +372,21 @@ def create_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_checkout_settings' not in self._stubs: - self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/CreateCheckoutSettings', + if "create_checkout_settings" not in self._stubs: + self._stubs["create_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/CreateCheckoutSettings", request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, response_deserializer=checkoutsettings.CheckoutSettings.deserialize, ) - return self._stubs['create_checkout_settings'] + return self._stubs["create_checkout_settings"] @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: + def update_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings, + ]: r"""Return a callable for the update checkout settings method over gRPC. Updates ``CheckoutSettings`` for the given merchant. @@ -381,18 +401,18 @@ def update_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_checkout_settings' not in self._stubs: - self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/UpdateCheckoutSettings', + if "update_checkout_settings" not in self._stubs: + self._stubs["update_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/UpdateCheckoutSettings", request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, response_deserializer=checkoutsettings.CheckoutSettings.deserialize, ) - return self._stubs['update_checkout_settings'] + return self._stubs["update_checkout_settings"] @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - empty_pb2.Empty]: + def delete_checkout_settings( + self, + ) -> Callable[[checkoutsettings.DeleteCheckoutSettingsRequest], empty_pb2.Empty]: r"""Return a callable for the delete checkout settings method over gRPC. Deletes ``CheckoutSettings`` and unenrolls merchant from @@ -408,13 +428,13 @@ def delete_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_checkout_settings' not in self._stubs: - self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/DeleteCheckoutSettings', + if "delete_checkout_settings" not in self._stubs: + self._stubs["delete_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/DeleteCheckoutSettings", request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_checkout_settings'] + return self._stubs["delete_checkout_settings"] def close(self): self._logged_channel.close() @@ -424,6 +444,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'CheckoutSettingsServiceGrpcTransport', -) +__all__ = ("CheckoutSettingsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py index a7ff8012c889..8ab8ce903511 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_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_accounts_v1.types import checkoutsettings -from .base import CheckoutSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, CheckoutSettingsServiceTransport from .grpc import CheckoutSettingsServiceGrpcTransport 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.accounts.v1.CheckoutSettingsService", "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.accounts.v1.CheckoutSettingsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -124,13 +132,15 @@ class CheckoutSettingsServiceGrpcAsyncIOTransport(CheckoutSettingsServiceTranspo _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 get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - Awaitable[checkoutsettings.CheckoutSettings]]: + def get_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings], + ]: r"""Return a callable for the get checkout settings method over gRPC. Gets ``CheckoutSettings`` for the given merchant. This includes @@ -335,18 +352,21 @@ def get_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_checkout_settings' not in self._stubs: - self._stubs['get_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/GetCheckoutSettings', + if "get_checkout_settings" not in self._stubs: + self._stubs["get_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/GetCheckoutSettings", request_serializer=checkoutsettings.GetCheckoutSettingsRequest.serialize, response_deserializer=checkoutsettings.CheckoutSettings.deserialize, ) - return self._stubs['get_checkout_settings'] + return self._stubs["get_checkout_settings"] @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - Awaitable[checkoutsettings.CheckoutSettings]]: + def create_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings], + ]: r"""Return a callable for the create checkout settings method over gRPC. Creates ``CheckoutSettings`` for the given merchant. @@ -361,18 +381,21 @@ def create_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_checkout_settings' not in self._stubs: - self._stubs['create_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/CreateCheckoutSettings', + if "create_checkout_settings" not in self._stubs: + self._stubs["create_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/CreateCheckoutSettings", request_serializer=checkoutsettings.CreateCheckoutSettingsRequest.serialize, response_deserializer=checkoutsettings.CheckoutSettings.deserialize, ) - return self._stubs['create_checkout_settings'] + return self._stubs["create_checkout_settings"] @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - Awaitable[checkoutsettings.CheckoutSettings]]: + def update_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + Awaitable[checkoutsettings.CheckoutSettings], + ]: r"""Return a callable for the update checkout settings method over gRPC. Updates ``CheckoutSettings`` for the given merchant. @@ -387,18 +410,20 @@ def update_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_checkout_settings' not in self._stubs: - self._stubs['update_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/UpdateCheckoutSettings', + if "update_checkout_settings" not in self._stubs: + self._stubs["update_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/UpdateCheckoutSettings", request_serializer=checkoutsettings.UpdateCheckoutSettingsRequest.serialize, response_deserializer=checkoutsettings.CheckoutSettings.deserialize, ) - return self._stubs['update_checkout_settings'] + return self._stubs["update_checkout_settings"] @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - Awaitable[empty_pb2.Empty]]: + def delete_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.DeleteCheckoutSettingsRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete checkout settings method over gRPC. Deletes ``CheckoutSettings`` and unenrolls merchant from @@ -414,16 +439,16 @@ def delete_checkout_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_checkout_settings' not in self._stubs: - self._stubs['delete_checkout_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.CheckoutSettingsService/DeleteCheckoutSettings', + if "delete_checkout_settings" not in self._stubs: + self._stubs["delete_checkout_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.CheckoutSettingsService/DeleteCheckoutSettings", request_serializer=checkoutsettings.DeleteCheckoutSettingsRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_checkout_settings'] + return self._stubs["delete_checkout_settings"] 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.get_checkout_settings: self._wrap_method( self.get_checkout_settings, @@ -460,6 +485,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'CheckoutSettingsServiceGrpcAsyncIOTransport', -) +__all__ = ("CheckoutSettingsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py similarity index 69% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py index fb7a3b6b9e44..c857646b3015 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_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_accounts_v1.types import checkoutsettings - -from .rest_base import _BaseCheckoutSettingsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseCheckoutSettingsServiceRestTransport 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 @@ -111,7 +106,15 @@ def post_update_checkout_settings(self, response): """ - def pre_create_checkout_settings(self, request: checkoutsettings.CreateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CreateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_checkout_settings( + self, + request: checkoutsettings.CreateCheckoutSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.CreateCheckoutSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_checkout_settings Override in a subclass to manipulate the request or metadata @@ -119,7 +122,9 @@ def pre_create_checkout_settings(self, request: checkoutsettings.CreateCheckoutS """ return request, metadata - def post_create_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + def post_create_checkout_settings( + self, response: checkoutsettings.CheckoutSettings + ) -> checkoutsettings.CheckoutSettings: """Post-rpc interceptor for create_checkout_settings DEPRECATED. Please use the `post_create_checkout_settings_with_metadata` @@ -132,7 +137,13 @@ def post_create_checkout_settings(self, response: checkoutsettings.CheckoutSetti """ return response - def post_create_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_checkout_settings_with_metadata( + self, + response: checkoutsettings.CheckoutSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for create_checkout_settings Override in a subclass to read or manipulate the response or metadata after it @@ -147,7 +158,14 @@ def post_create_checkout_settings_with_metadata(self, response: checkoutsettings """ return response, metadata - def pre_delete_checkout_settings(self, request: checkoutsettings.DeleteCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.DeleteCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_checkout_settings( + self, + request: checkoutsettings.DeleteCheckoutSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.DeleteCheckoutSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_checkout_settings Override in a subclass to manipulate the request or metadata @@ -155,7 +173,14 @@ def pre_delete_checkout_settings(self, request: checkoutsettings.DeleteCheckoutS """ return request, metadata - def pre_get_checkout_settings(self, request: checkoutsettings.GetCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.GetCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_checkout_settings( + self, + request: checkoutsettings.GetCheckoutSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.GetCheckoutSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_checkout_settings Override in a subclass to manipulate the request or metadata @@ -163,7 +188,9 @@ def pre_get_checkout_settings(self, request: checkoutsettings.GetCheckoutSetting """ return request, metadata - def post_get_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + def post_get_checkout_settings( + self, response: checkoutsettings.CheckoutSettings + ) -> checkoutsettings.CheckoutSettings: """Post-rpc interceptor for get_checkout_settings DEPRECATED. Please use the `post_get_checkout_settings_with_metadata` @@ -176,7 +203,13 @@ def post_get_checkout_settings(self, response: checkoutsettings.CheckoutSettings """ return response - def post_get_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_checkout_settings_with_metadata( + self, + response: checkoutsettings.CheckoutSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_checkout_settings Override in a subclass to read or manipulate the response or metadata after it @@ -191,7 +224,14 @@ def post_get_checkout_settings_with_metadata(self, response: checkoutsettings.Ch """ return response, metadata - def pre_update_checkout_settings(self, request: checkoutsettings.UpdateCheckoutSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.UpdateCheckoutSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_checkout_settings( + self, + request: checkoutsettings.UpdateCheckoutSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.UpdateCheckoutSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_checkout_settings Override in a subclass to manipulate the request or metadata @@ -199,7 +239,9 @@ def pre_update_checkout_settings(self, request: checkoutsettings.UpdateCheckoutS """ return request, metadata - def post_update_checkout_settings(self, response: checkoutsettings.CheckoutSettings) -> checkoutsettings.CheckoutSettings: + def post_update_checkout_settings( + self, response: checkoutsettings.CheckoutSettings + ) -> checkoutsettings.CheckoutSettings: """Post-rpc interceptor for update_checkout_settings DEPRECATED. Please use the `post_update_checkout_settings_with_metadata` @@ -212,7 +254,13 @@ def post_update_checkout_settings(self, response: checkoutsettings.CheckoutSetti """ return response - def post_update_checkout_settings_with_metadata(self, response: checkoutsettings.CheckoutSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_checkout_settings_with_metadata( + self, + response: checkoutsettings.CheckoutSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + checkoutsettings.CheckoutSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for update_checkout_settings Override in a subclass to read or manipulate the response or metadata after it @@ -248,20 +296,21 @@ class CheckoutSettingsServiceRestTransport(_BaseCheckoutSettingsServiceRestTrans 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[CheckoutSettingsServiceRestInterceptor] = 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[CheckoutSettingsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -304,16 +353,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 CheckoutSettingsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings, CheckoutSettingsServiceRestStub): + class _CreateCheckoutSettings( + _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings, + CheckoutSettingsServiceRestStub, + ): def __hash__(self): return hash("CheckoutSettingsServiceRestTransport.CreateCheckoutSettings") @@ -325,27 +378,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: checkoutsettings.CreateCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> checkoutsettings.CheckoutSettings: + def __call__( + self, + request: checkoutsettings.CreateCheckoutSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Call the create checkout settings method over HTTP. Args: @@ -367,32 +422,46 @@ def __call__(self, """ - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_http_options() + http_options = ( + _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_create_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_checkout_settings( + request, metadata + ) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_transcoded_request( + http_options, request + ) - body = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_request_body_json(transcoded_request) + body = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.CreateCheckoutSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "CreateCheckoutSettings", "httpRequest": http_request, @@ -401,7 +470,15 @@ def __call__(self, ) # Send the request - response = CheckoutSettingsServiceRestTransport._CreateCheckoutSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CheckoutSettingsServiceRestTransport._CreateCheckoutSettings._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. @@ -416,20 +493,26 @@ def __call__(self, resp = self._interceptor.post_create_checkout_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_checkout_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_checkout_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = checkoutsettings.CheckoutSettings.to_json(response) + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1.CheckoutSettingsServiceClient.create_checkout_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "CreateCheckoutSettings", "metadata": http_response["headers"], @@ -438,7 +521,10 @@ def __call__(self, ) return resp - class _DeleteCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings, CheckoutSettingsServiceRestStub): + class _DeleteCheckoutSettings( + _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings, + CheckoutSettingsServiceRestStub, + ): def __hash__(self): return hash("CheckoutSettingsServiceRestTransport.DeleteCheckoutSettings") @@ -450,26 +536,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: checkoutsettings.DeleteCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: checkoutsettings.DeleteCheckoutSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete checkout settings method over HTTP. Args: @@ -485,30 +573,42 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_http_options() + http_options = ( + _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_checkout_settings( + request, metadata + ) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.DeleteCheckoutSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "DeleteCheckoutSettings", "httpRequest": http_request, @@ -517,14 +617,24 @@ def __call__(self, ) # Send the request - response = CheckoutSettingsServiceRestTransport._DeleteCheckoutSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = CheckoutSettingsServiceRestTransport._DeleteCheckoutSettings._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 _GetCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings, CheckoutSettingsServiceRestStub): + class _GetCheckoutSettings( + _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings, + CheckoutSettingsServiceRestStub, + ): def __hash__(self): return hash("CheckoutSettingsServiceRestTransport.GetCheckoutSettings") @@ -536,26 +646,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: checkoutsettings.GetCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> checkoutsettings.CheckoutSettings: + def __call__( + self, + request: checkoutsettings.GetCheckoutSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Call the get checkout settings method over HTTP. Args: @@ -576,30 +688,42 @@ def __call__(self, """ - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_http_options() + http_options = ( + _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_get_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_checkout_settings( + request, metadata + ) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.GetCheckoutSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "GetCheckoutSettings", "httpRequest": http_request, @@ -608,7 +732,16 @@ def __call__(self, ) # Send the request - response = CheckoutSettingsServiceRestTransport._GetCheckoutSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + CheckoutSettingsServiceRestTransport._GetCheckoutSettings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -623,20 +756,26 @@ def __call__(self, resp = self._interceptor.post_get_checkout_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_checkout_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_checkout_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = checkoutsettings.CheckoutSettings.to_json(response) + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1.CheckoutSettingsServiceClient.get_checkout_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "GetCheckoutSettings", "metadata": http_response["headers"], @@ -645,7 +784,10 @@ def __call__(self, ) return resp - class _UpdateCheckoutSettings(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings, CheckoutSettingsServiceRestStub): + class _UpdateCheckoutSettings( + _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings, + CheckoutSettingsServiceRestStub, + ): def __hash__(self): return hash("CheckoutSettingsServiceRestTransport.UpdateCheckoutSettings") @@ -657,27 +799,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: checkoutsettings.UpdateCheckoutSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> checkoutsettings.CheckoutSettings: + def __call__( + self, + request: checkoutsettings.UpdateCheckoutSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> checkoutsettings.CheckoutSettings: r"""Call the update checkout settings method over HTTP. Args: @@ -699,32 +843,46 @@ def __call__(self, """ - http_options = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_http_options() + http_options = ( + _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_update_checkout_settings(request, metadata) - transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_checkout_settings( + request, metadata + ) + transcoded_request = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_transcoded_request( + http_options, request + ) - body = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_request_body_json(transcoded_request) + body = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.CheckoutSettingsServiceClient.UpdateCheckoutSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "UpdateCheckoutSettings", "httpRequest": http_request, @@ -733,7 +891,15 @@ def __call__(self, ) # Send the request - response = CheckoutSettingsServiceRestTransport._UpdateCheckoutSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = CheckoutSettingsServiceRestTransport._UpdateCheckoutSettings._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. @@ -748,20 +914,26 @@ def __call__(self, resp = self._interceptor.post_update_checkout_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_checkout_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_checkout_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = checkoutsettings.CheckoutSettings.to_json(response) + response_payload = checkoutsettings.CheckoutSettings.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.accounts_v1.CheckoutSettingsServiceClient.update_checkout_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.CheckoutSettingsService", "rpcName": "UpdateCheckoutSettings", "metadata": http_response["headers"], @@ -771,36 +943,44 @@ def __call__(self, return resp @property - def create_checkout_settings(self) -> Callable[ - [checkoutsettings.CreateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: + def create_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.CreateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings, + ]: # 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._CreateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + return self._CreateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore @property - def delete_checkout_settings(self) -> Callable[ - [checkoutsettings.DeleteCheckoutSettingsRequest], - empty_pb2.Empty]: + def delete_checkout_settings( + self, + ) -> Callable[[checkoutsettings.DeleteCheckoutSettingsRequest], 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._DeleteCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore @property - def get_checkout_settings(self) -> Callable[ - [checkoutsettings.GetCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: + def get_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.GetCheckoutSettingsRequest], checkoutsettings.CheckoutSettings + ]: # 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._GetCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + return self._GetCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore @property - def update_checkout_settings(self) -> Callable[ - [checkoutsettings.UpdateCheckoutSettingsRequest], - checkoutsettings.CheckoutSettings]: + def update_checkout_settings( + self, + ) -> Callable[ + [checkoutsettings.UpdateCheckoutSettingsRequest], + checkoutsettings.CheckoutSettings, + ]: # 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._UpdateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateCheckoutSettings(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -810,6 +990,4 @@ def close(self): self._session.close() -__all__=( - 'CheckoutSettingsServiceRestTransport', -) +__all__ = ("CheckoutSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py index 1add45fb12e2..3cf3fc0be902 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/checkout_settings_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/checkout_settings_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 CheckoutSettingsServiceTransport, 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_accounts_v1.types import checkoutsettings +from .base import DEFAULT_CLIENT_INFO, CheckoutSettingsServiceTransport + class _BaseCheckoutSettingsServiceRestTransport(CheckoutSettingsServiceTransport): """Base REST backend transport for CheckoutSettingsService. @@ -41,14 +39,16 @@ class _BaseCheckoutSettingsServiceRestTransport(CheckoutSettingsServiceTransport 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,27 +85,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseCreateCheckoutSettings: 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': '/accounts/v1/{parent=accounts/*/programs/*}/checkoutSettings', - 'body': 'checkout_settings', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*/programs/*}/checkoutSettings", + "body": "checkout_settings", + }, ] return http_options @@ -118,17 +124,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(_BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._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( + _BaseCheckoutSettingsServiceRestTransport._BaseCreateCheckoutSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -137,19 +149,23 @@ class _BaseDeleteCheckoutSettings: 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': '/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}", + }, ] return http_options @@ -161,11 +177,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(_BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._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( + _BaseCheckoutSettingsServiceRestTransport._BaseDeleteCheckoutSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,19 +196,23 @@ class _BaseGetCheckoutSettings: 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': '/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}", + }, ] return http_options @@ -198,11 +224,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(_BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._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( + _BaseCheckoutSettingsServiceRestTransport._BaseGetCheckoutSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -211,20 +243,26 @@ class _BaseUpdateCheckoutSettings: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}', - 'body': 'checkout_settings', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}", + "body": "checkout_settings", + }, ] return http_options @@ -239,22 +277,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._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( + _BaseCheckoutSettingsServiceRestTransport._BaseUpdateCheckoutSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseCheckoutSettingsServiceRestTransport', -) +__all__ = ("_BaseCheckoutSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py index ccbe5e8935bc..5fea4e4f9ec2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import DeveloperRegistrationServiceClient from .async_client import DeveloperRegistrationServiceAsyncClient +from .client import DeveloperRegistrationServiceClient __all__ = ( - 'DeveloperRegistrationServiceClient', - 'DeveloperRegistrationServiceAsyncClient', + "DeveloperRegistrationServiceClient", + "DeveloperRegistrationServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py index 408ff307a080..13e16c0b47a9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,18 +45,21 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.shopping.merchant_accounts_v1.types import developerregistration -from .transports.base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport + from .client import DeveloperRegistrationServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, DeveloperRegistrationServiceTransport +from .transports.grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport 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 DeveloperRegistrationServiceAsyncClient: """Service to access Developer Registration.""" @@ -56,21 +69,47 @@ class DeveloperRegistrationServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = DeveloperRegistrationServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE - developer_registration_path = staticmethod(DeveloperRegistrationServiceClient.developer_registration_path) - parse_developer_registration_path = staticmethod(DeveloperRegistrationServiceClient.parse_developer_registration_path) - common_billing_account_path = staticmethod(DeveloperRegistrationServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DeveloperRegistrationServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DeveloperRegistrationServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DeveloperRegistrationServiceClient.common_project_path) - parse_common_project_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_project_path) - common_location_path = staticmethod(DeveloperRegistrationServiceClient.common_location_path) - parse_common_location_path = staticmethod(DeveloperRegistrationServiceClient.parse_common_location_path) + developer_registration_path = staticmethod( + DeveloperRegistrationServiceClient.developer_registration_path + ) + parse_developer_registration_path = staticmethod( + DeveloperRegistrationServiceClient.parse_developer_registration_path + ) + common_billing_account_path = staticmethod( + DeveloperRegistrationServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DeveloperRegistrationServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + DeveloperRegistrationServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + DeveloperRegistrationServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + DeveloperRegistrationServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + DeveloperRegistrationServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + DeveloperRegistrationServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + DeveloperRegistrationServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + DeveloperRegistrationServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + DeveloperRegistrationServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -106,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: @@ -169,12 +210,20 @@ def universe_domain(self) -> str: get_transport_class = DeveloperRegistrationServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DeveloperRegistrationServiceTransport, Callable[..., DeveloperRegistrationServiceTransport]]] = "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, + DeveloperRegistrationServiceTransport, + Callable[..., DeveloperRegistrationServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the developer registration service async client. Args: @@ -229,30 +278,38 @@ 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.accounts_v1.DeveloperRegistrationServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", - "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.accounts.v1.DeveloperRegistrationService", "credentialsType": None, - } + }, ) - async def register_gcp(self, - request: Optional[Union[developerregistration.RegisterGcpRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developerregistration.DeveloperRegistration: + async def register_gcp( + self, + request: Optional[Union[developerregistration.RegisterGcpRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: r"""Registers the GCP used for the API call to the shopping account passed in the request. Will create a user with an "API developer" and add the "developer_email" as a contact with "API @@ -310,14 +367,14 @@ async def sample_register_gcp(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.register_gcp] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.register_gcp + ] # 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. @@ -334,14 +391,17 @@ async def sample_register_gcp(): # Done; return the response. return response - async def get_developer_registration(self, - request: Optional[Union[developerregistration.GetDeveloperRegistrationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developerregistration.DeveloperRegistration: + async def get_developer_registration( + self, + request: Optional[ + Union[developerregistration.GetDeveloperRegistrationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: r"""Retrieves a developer registration for a merchant. .. code-block:: python @@ -399,14 +459,20 @@ async def sample_get_developer_registration(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, developerregistration.GetDeveloperRegistrationRequest): + if not isinstance( + request, developerregistration.GetDeveloperRegistrationRequest + ): request = developerregistration.GetDeveloperRegistrationRequest(request) # If we have keyword arguments corresponding to fields on the @@ -416,14 +482,14 @@ async def sample_get_developer_registration(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_developer_registration] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_developer_registration + ] # 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. @@ -440,13 +506,16 @@ async def sample_get_developer_registration(): # Done; return the response. return response - async def unregister_gcp(self, - request: Optional[Union[developerregistration.UnregisterGcpRequest, dict]] = 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 unregister_gcp( + self, + request: Optional[ + Union[developerregistration.UnregisterGcpRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Unregister the calling GCP from the calling shopping account. Note that the GCP will still be able to access the API for at most 1 day from the unregister succussful @@ -495,14 +564,14 @@ async def sample_unregister_gcp(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.unregister_gcp] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.unregister_gcp + ] # 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. @@ -522,12 +591,13 @@ async def __aenter__(self) -> "DeveloperRegistrationServiceAsyncClient": 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__ = ( - "DeveloperRegistrationServiceAsyncClient", -) +__all__ = ("DeveloperRegistrationServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py index 5ae1c105c7a1..47a305d53994 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,7 +62,8 @@ _LOGGER = std_logging.getLogger(__name__) from google.shopping.merchant_accounts_v1.types import developerregistration -from .transports.base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, DeveloperRegistrationServiceTransport from .transports.grpc import DeveloperRegistrationServiceGrpcTransport from .transports.grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport from .transports.rest import DeveloperRegistrationServiceRestTransport @@ -62,14 +76,20 @@ class DeveloperRegistrationServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DeveloperRegistrationServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[DeveloperRegistrationServiceTransport]] _transport_registry["grpc"] = DeveloperRegistrationServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DeveloperRegistrationServiceGrpcAsyncIOTransport + _transport_registry[ + "grpc_asyncio" + ] = DeveloperRegistrationServiceGrpcAsyncIOTransport _transport_registry["rest"] = DeveloperRegistrationServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DeveloperRegistrationServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[DeveloperRegistrationServiceTransport]: """Returns an appropriate transport class. Args: @@ -88,7 +108,9 @@ def get_transport_class(cls, return next(iter(cls._transport_registry.values())) -class DeveloperRegistrationServiceClient(metaclass=DeveloperRegistrationServiceClientMeta): +class DeveloperRegistrationServiceClient( + metaclass=DeveloperRegistrationServiceClientMeta +): """Service to access Developer Registration.""" @staticmethod @@ -161,8 +183,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: DeveloperRegistrationServiceClient: 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) @@ -179,73 +200,101 @@ def transport(self) -> DeveloperRegistrationServiceTransport: return self._transport @staticmethod - def developer_registration_path(account: str,) -> str: + def developer_registration_path( + account: str, + ) -> str: """Returns a fully-qualified developer_registration string.""" - return "accounts/{account}/developerRegistration".format(account=account, ) + return "accounts/{account}/developerRegistration".format( + account=account, + ) @staticmethod - def parse_developer_registration_path(path: str) -> Dict[str,str]: + def parse_developer_registration_path(path: str) -> Dict[str, str]: """Parses a developer_registration path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/developerRegistration$", 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: @@ -277,16 +326,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 @@ -299,7 +354,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 @@ -320,13 +377,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 @@ -349,7 +412,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): """Return the API endpoint used by the client. Args: @@ -365,17 +430,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 = DeveloperRegistrationServiceClient._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 = DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + DeveloperRegistrationServiceClient._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: @@ -411,15 +486,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 @@ -452,12 +530,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DeveloperRegistrationServiceTransport, Callable[..., DeveloperRegistrationServiceTransport]]] = 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, + DeveloperRegistrationServiceTransport, + Callable[..., DeveloperRegistrationServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the developer registration service client. Args: @@ -512,14 +598,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 = DeveloperRegistrationServiceClient._read_environment_variables() - self._client_cert_source = DeveloperRegistrationServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = DeveloperRegistrationServiceClient._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, + ) = DeveloperRegistrationServiceClient._read_environment_variables() + self._client_cert_source = ( + DeveloperRegistrationServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = DeveloperRegistrationServiceClient._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 @@ -530,17 +628,23 @@ 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 # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, DeveloperRegistrationServiceTransport) + transport_provided = isinstance( + transport, DeveloperRegistrationServiceTransport + ) if transport_provided: # transport is a DeveloperRegistrationServiceTransport 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 " @@ -549,23 +653,35 @@ def __init__(self, *, self._transport = cast(DeveloperRegistrationServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - DeveloperRegistrationServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or DeveloperRegistrationServiceClient._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[DeveloperRegistrationServiceTransport], Callable[..., DeveloperRegistrationServiceTransport]] = ( + transport_init: Union[ + Type[DeveloperRegistrationServiceTransport], + Callable[..., DeveloperRegistrationServiceTransport], + ] = ( DeveloperRegistrationServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None - else cast(Callable[..., DeveloperRegistrationServiceTransport], transport) + else cast( + Callable[..., DeveloperRegistrationServiceTransport], transport + ) ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -581,27 +697,36 @@ 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.accounts_v1.DeveloperRegistrationServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", - "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.accounts.v1.DeveloperRegistrationService", "credentialsType": None, - } + }, ) - def register_gcp(self, - request: Optional[Union[developerregistration.RegisterGcpRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developerregistration.DeveloperRegistration: + def register_gcp( + self, + request: Optional[Union[developerregistration.RegisterGcpRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: r"""Registers the GCP used for the API call to the shopping account passed in the request. Will create a user with an "API developer" and add the "developer_email" as a contact with "API @@ -664,9 +789,7 @@ def sample_register_gcp(): # 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. @@ -683,14 +806,17 @@ def sample_register_gcp(): # Done; return the response. return response - def get_developer_registration(self, - request: Optional[Union[developerregistration.GetDeveloperRegistrationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developerregistration.DeveloperRegistration: + def get_developer_registration( + self, + request: Optional[ + Union[developerregistration.GetDeveloperRegistrationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: r"""Retrieves a developer registration for a merchant. .. code-block:: python @@ -748,14 +874,20 @@ def sample_get_developer_registration(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, developerregistration.GetDeveloperRegistrationRequest): + if not isinstance( + request, developerregistration.GetDeveloperRegistrationRequest + ): request = developerregistration.GetDeveloperRegistrationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -764,14 +896,14 @@ def sample_get_developer_registration(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_developer_registration] + rpc = self._transport._wrapped_methods[ + self._transport.get_developer_registration + ] # 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. @@ -788,13 +920,16 @@ def sample_get_developer_registration(): # Done; return the response. return response - def unregister_gcp(self, - request: Optional[Union[developerregistration.UnregisterGcpRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> None: + def unregister_gcp( + self, + request: Optional[ + Union[developerregistration.UnregisterGcpRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: r"""Unregister the calling GCP from the calling shopping account. Note that the GCP will still be able to access the API for at most 1 day from the unregister succussful @@ -848,9 +983,7 @@ def sample_unregister_gcp(): # 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. @@ -878,16 +1011,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__ = ( - "DeveloperRegistrationServiceClient", -) +__all__ = ("DeveloperRegistrationServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py index d6f2a783cf1f..11de16c3ec56 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import DeveloperRegistrationServiceTransport from .grpc import DeveloperRegistrationServiceGrpcTransport from .grpc_asyncio import DeveloperRegistrationServiceGrpcAsyncIOTransport -from .rest import DeveloperRegistrationServiceRestTransport -from .rest import DeveloperRegistrationServiceRestInterceptor - +from .rest import ( + DeveloperRegistrationServiceRestInterceptor, + DeveloperRegistrationServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DeveloperRegistrationServiceTransport]] -_transport_registry['grpc'] = DeveloperRegistrationServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DeveloperRegistrationServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DeveloperRegistrationServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[DeveloperRegistrationServiceTransport]] +_transport_registry["grpc"] = DeveloperRegistrationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = DeveloperRegistrationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DeveloperRegistrationServiceRestTransport __all__ = ( - 'DeveloperRegistrationServiceTransport', - 'DeveloperRegistrationServiceGrpcTransport', - 'DeveloperRegistrationServiceGrpcAsyncIOTransport', - 'DeveloperRegistrationServiceRestTransport', - 'DeveloperRegistrationServiceRestInterceptor', + "DeveloperRegistrationServiceTransport", + "DeveloperRegistrationServiceGrpcTransport", + "DeveloperRegistrationServiceGrpcAsyncIOTransport", + "DeveloperRegistrationServiceRestTransport", + "DeveloperRegistrationServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py index ac935c33c08f..695171513df9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import developerregistration -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 DeveloperRegistrationServiceTransport(abc.ABC): """Abstract transport class for DeveloperRegistrationService.""" - 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 register_gcp(self) -> Callable[ - [developerregistration.RegisterGcpRequest], - Union[ - developerregistration.DeveloperRegistration, - Awaitable[developerregistration.DeveloperRegistration] - ]]: + def register_gcp( + self, + ) -> Callable[ + [developerregistration.RegisterGcpRequest], + Union[ + developerregistration.DeveloperRegistration, + Awaitable[developerregistration.DeveloperRegistration], + ], + ]: raise NotImplementedError() @property - def get_developer_registration(self) -> Callable[ - [developerregistration.GetDeveloperRegistrationRequest], - Union[ - developerregistration.DeveloperRegistration, - Awaitable[developerregistration.DeveloperRegistration] - ]]: + def get_developer_registration( + self, + ) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + Union[ + developerregistration.DeveloperRegistration, + Awaitable[developerregistration.DeveloperRegistration], + ], + ]: raise NotImplementedError() @property - def unregister_gcp(self) -> Callable[ - [developerregistration.UnregisterGcpRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def unregister_gcp( + self, + ) -> Callable[ + [developerregistration.UnregisterGcpRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -183,6 +197,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'DeveloperRegistrationServiceTransport', -) +__all__ = ("DeveloperRegistrationServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py index 4816cd413bfd..c88b1385657e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_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_accounts_v1.types import developerregistration -from .base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, DeveloperRegistrationServiceTransport 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.accounts.v1.DeveloperRegistrationService", "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.accounts.v1.DeveloperRegistrationService", "rpcName": client_call_details.method, "response": grpc_response, @@ -114,23 +120,26 @@ class DeveloperRegistrationServiceGrpcTransport(DeveloperRegistrationServiceTran 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 register_gcp(self) -> Callable[ - [developerregistration.RegisterGcpRequest], - developerregistration.DeveloperRegistration]: + def register_gcp( + self, + ) -> Callable[ + [developerregistration.RegisterGcpRequest], + developerregistration.DeveloperRegistration, + ]: r"""Return a callable for the register gcp method over gRPC. Registers the GCP used for the API call to the shopping account @@ -329,18 +344,21 @@ def register_gcp(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'register_gcp' not in self._stubs: - self._stubs['register_gcp'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/RegisterGcp', + if "register_gcp" not in self._stubs: + self._stubs["register_gcp"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/RegisterGcp", request_serializer=developerregistration.RegisterGcpRequest.serialize, response_deserializer=developerregistration.DeveloperRegistration.deserialize, ) - return self._stubs['register_gcp'] + return self._stubs["register_gcp"] @property - def get_developer_registration(self) -> Callable[ - [developerregistration.GetDeveloperRegistrationRequest], - developerregistration.DeveloperRegistration]: + def get_developer_registration( + self, + ) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + developerregistration.DeveloperRegistration, + ]: r"""Return a callable for the get developer registration method over gRPC. Retrieves a developer registration for a merchant. @@ -355,18 +373,20 @@ def get_developer_registration(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_developer_registration' not in self._stubs: - self._stubs['get_developer_registration'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/GetDeveloperRegistration', + if "get_developer_registration" not in self._stubs: + self._stubs[ + "get_developer_registration" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/GetDeveloperRegistration", request_serializer=developerregistration.GetDeveloperRegistrationRequest.serialize, response_deserializer=developerregistration.DeveloperRegistration.deserialize, ) - return self._stubs['get_developer_registration'] + return self._stubs["get_developer_registration"] @property - def unregister_gcp(self) -> Callable[ - [developerregistration.UnregisterGcpRequest], - empty_pb2.Empty]: + def unregister_gcp( + self, + ) -> Callable[[developerregistration.UnregisterGcpRequest], empty_pb2.Empty]: r"""Return a callable for the unregister gcp method over gRPC. Unregister the calling GCP from the calling shopping @@ -384,13 +404,13 @@ def unregister_gcp(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'unregister_gcp' not in self._stubs: - self._stubs['unregister_gcp'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/UnregisterGcp', + if "unregister_gcp" not in self._stubs: + self._stubs["unregister_gcp"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/UnregisterGcp", request_serializer=developerregistration.UnregisterGcpRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['unregister_gcp'] + return self._stubs["unregister_gcp"] def close(self): self._logged_channel.close() @@ -400,6 +420,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'DeveloperRegistrationServiceGrpcTransport', -) +__all__ = ("DeveloperRegistrationServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py index 807deb598ada..24963c70f5e2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_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_accounts_v1.types import developerregistration -from .base import DeveloperRegistrationServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, DeveloperRegistrationServiceTransport from .grpc import DeveloperRegistrationServiceGrpcTransport 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.accounts.v1.DeveloperRegistrationService", "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.accounts.v1.DeveloperRegistrationService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -106,7 +114,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request return response -class DeveloperRegistrationServiceGrpcAsyncIOTransport(DeveloperRegistrationServiceTransport): +class DeveloperRegistrationServiceGrpcAsyncIOTransport( + DeveloperRegistrationServiceTransport +): """gRPC AsyncIO backend transport for DeveloperRegistrationService. Service to access Developer Registration. @@ -123,13 +133,15 @@ class DeveloperRegistrationServiceGrpcAsyncIOTransport(DeveloperRegistrationServ _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 +171,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 +314,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 +331,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def register_gcp(self) -> Callable[ - [developerregistration.RegisterGcpRequest], - Awaitable[developerregistration.DeveloperRegistration]]: + def register_gcp( + self, + ) -> Callable[ + [developerregistration.RegisterGcpRequest], + Awaitable[developerregistration.DeveloperRegistration], + ]: r"""Return a callable for the register gcp method over gRPC. Registers the GCP used for the API call to the shopping account @@ -335,18 +354,21 @@ def register_gcp(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'register_gcp' not in self._stubs: - self._stubs['register_gcp'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/RegisterGcp', + if "register_gcp" not in self._stubs: + self._stubs["register_gcp"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/RegisterGcp", request_serializer=developerregistration.RegisterGcpRequest.serialize, response_deserializer=developerregistration.DeveloperRegistration.deserialize, ) - return self._stubs['register_gcp'] + return self._stubs["register_gcp"] @property - def get_developer_registration(self) -> Callable[ - [developerregistration.GetDeveloperRegistrationRequest], - Awaitable[developerregistration.DeveloperRegistration]]: + def get_developer_registration( + self, + ) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + Awaitable[developerregistration.DeveloperRegistration], + ]: r"""Return a callable for the get developer registration method over gRPC. Retrieves a developer registration for a merchant. @@ -361,18 +383,22 @@ def get_developer_registration(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_developer_registration' not in self._stubs: - self._stubs['get_developer_registration'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/GetDeveloperRegistration', + if "get_developer_registration" not in self._stubs: + self._stubs[ + "get_developer_registration" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/GetDeveloperRegistration", request_serializer=developerregistration.GetDeveloperRegistrationRequest.serialize, response_deserializer=developerregistration.DeveloperRegistration.deserialize, ) - return self._stubs['get_developer_registration'] + return self._stubs["get_developer_registration"] @property - def unregister_gcp(self) -> Callable[ - [developerregistration.UnregisterGcpRequest], - Awaitable[empty_pb2.Empty]]: + def unregister_gcp( + self, + ) -> Callable[ + [developerregistration.UnregisterGcpRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the unregister gcp method over gRPC. Unregister the calling GCP from the calling shopping @@ -390,16 +416,16 @@ def unregister_gcp(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'unregister_gcp' not in self._stubs: - self._stubs['unregister_gcp'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/UnregisterGcp', + if "unregister_gcp" not in self._stubs: + self._stubs["unregister_gcp"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.DeveloperRegistrationService/UnregisterGcp", request_serializer=developerregistration.UnregisterGcpRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['unregister_gcp'] + return self._stubs["unregister_gcp"] 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.register_gcp: self._wrap_method( self.register_gcp, @@ -431,6 +457,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'DeveloperRegistrationServiceGrpcAsyncIOTransport', -) +__all__ = ("DeveloperRegistrationServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py index 652e8e0bc6dd..18ca6a41722e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_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_accounts_v1.types import developerregistration - -from .rest_base import _BaseDeveloperRegistrationServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseDeveloperRegistrationServiceRestTransport 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 pre_unregister_gcp(self, request, metadata): """ - def pre_get_developer_registration(self, request: developerregistration.GetDeveloperRegistrationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.GetDeveloperRegistrationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_developer_registration( + self, + request: developerregistration.GetDeveloperRegistrationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developerregistration.GetDeveloperRegistrationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_developer_registration Override in a subclass to manipulate the request or metadata @@ -111,7 +114,9 @@ def pre_get_developer_registration(self, request: developerregistration.GetDevel """ return request, metadata - def post_get_developer_registration(self, response: developerregistration.DeveloperRegistration) -> developerregistration.DeveloperRegistration: + def post_get_developer_registration( + self, response: developerregistration.DeveloperRegistration + ) -> developerregistration.DeveloperRegistration: """Post-rpc interceptor for get_developer_registration DEPRECATED. Please use the `post_get_developer_registration_with_metadata` @@ -124,7 +129,14 @@ def post_get_developer_registration(self, response: developerregistration.Develo """ return response - def post_get_developer_registration_with_metadata(self, response: developerregistration.DeveloperRegistration, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.DeveloperRegistration, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_developer_registration_with_metadata( + self, + response: developerregistration.DeveloperRegistration, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developerregistration.DeveloperRegistration, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for get_developer_registration Override in a subclass to read or manipulate the response or metadata after it @@ -139,7 +151,14 @@ def post_get_developer_registration_with_metadata(self, response: developerregis """ return response, metadata - def pre_register_gcp(self, request: developerregistration.RegisterGcpRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.RegisterGcpRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_register_gcp( + self, + request: developerregistration.RegisterGcpRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developerregistration.RegisterGcpRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for register_gcp Override in a subclass to manipulate the request or metadata @@ -147,7 +166,9 @@ def pre_register_gcp(self, request: developerregistration.RegisterGcpRequest, me """ return request, metadata - def post_register_gcp(self, response: developerregistration.DeveloperRegistration) -> developerregistration.DeveloperRegistration: + def post_register_gcp( + self, response: developerregistration.DeveloperRegistration + ) -> developerregistration.DeveloperRegistration: """Post-rpc interceptor for register_gcp DEPRECATED. Please use the `post_register_gcp_with_metadata` @@ -160,7 +181,14 @@ def post_register_gcp(self, response: developerregistration.DeveloperRegistratio """ return response - def post_register_gcp_with_metadata(self, response: developerregistration.DeveloperRegistration, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.DeveloperRegistration, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_register_gcp_with_metadata( + self, + response: developerregistration.DeveloperRegistration, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developerregistration.DeveloperRegistration, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for register_gcp Override in a subclass to read or manipulate the response or metadata after it @@ -175,7 +203,14 @@ def post_register_gcp_with_metadata(self, response: developerregistration.Develo """ return response, metadata - def pre_unregister_gcp(self, request: developerregistration.UnregisterGcpRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[developerregistration.UnregisterGcpRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_unregister_gcp( + self, + request: developerregistration.UnregisterGcpRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developerregistration.UnregisterGcpRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for unregister_gcp Override in a subclass to manipulate the request or metadata @@ -191,7 +226,9 @@ class DeveloperRegistrationServiceRestStub: _interceptor: DeveloperRegistrationServiceRestInterceptor -class DeveloperRegistrationServiceRestTransport(_BaseDeveloperRegistrationServiceRestTransport): +class DeveloperRegistrationServiceRestTransport( + _BaseDeveloperRegistrationServiceRestTransport +): """REST backend synchronous transport for DeveloperRegistrationService. Service to access Developer Registration. @@ -203,20 +240,21 @@ class DeveloperRegistrationServiceRestTransport(_BaseDeveloperRegistrationServic 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[DeveloperRegistrationServiceRestInterceptor] = 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[DeveloperRegistrationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -259,18 +297,24 @@ 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 DeveloperRegistrationServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetDeveloperRegistration(_BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration, DeveloperRegistrationServiceRestStub): + class _GetDeveloperRegistration( + _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration, + DeveloperRegistrationServiceRestStub, + ): def __hash__(self): - return hash("DeveloperRegistrationServiceRestTransport.GetDeveloperRegistration") + return hash( + "DeveloperRegistrationServiceRestTransport.GetDeveloperRegistration" + ) @staticmethod def _get_response( @@ -280,72 +324,86 @@ 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: developerregistration.GetDeveloperRegistrationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> developerregistration.DeveloperRegistration: + def __call__( + self, + request: developerregistration.GetDeveloperRegistrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: r"""Call the get developer - registration method over HTTP. - - Args: - request (~.developerregistration.GetDeveloperRegistrationRequest): - The request object. Request message for the - GetDeveloperRegistration 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: - ~.developerregistration.DeveloperRegistration: - Represents a developer registration - owned by a Merchant account. + registration method over HTTP. + + Args: + request (~.developerregistration.GetDeveloperRegistrationRequest): + The request object. Request message for the + GetDeveloperRegistration 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: + ~.developerregistration.DeveloperRegistration: + Represents a developer registration + owned by a Merchant account. """ - http_options = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_http_options() + http_options = ( + _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_http_options() + ) - request, metadata = self._interceptor.pre_get_developer_registration(request, metadata) - transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_developer_registration( + request, metadata + ) + transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.DeveloperRegistrationServiceClient.GetDeveloperRegistration", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", "rpcName": "GetDeveloperRegistration", "httpRequest": http_request, @@ -354,7 +412,14 @@ def __call__(self, ) # Send the request - response = DeveloperRegistrationServiceRestTransport._GetDeveloperRegistration._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = DeveloperRegistrationServiceRestTransport._GetDeveloperRegistration._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -369,20 +434,26 @@ def __call__(self, resp = self._interceptor.post_get_developer_registration(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_developer_registration_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_developer_registration_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = developerregistration.DeveloperRegistration.to_json(response) + response_payload = ( + developerregistration.DeveloperRegistration.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.accounts_v1.DeveloperRegistrationServiceClient.get_developer_registration", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", "rpcName": "GetDeveloperRegistration", "metadata": http_response["headers"], @@ -391,7 +462,10 @@ def __call__(self, ) return resp - class _RegisterGcp(_BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp, DeveloperRegistrationServiceRestStub): + class _RegisterGcp( + _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp, + DeveloperRegistrationServiceRestStub, + ): def __hash__(self): return hash("DeveloperRegistrationServiceRestTransport.RegisterGcp") @@ -403,27 +477,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: developerregistration.RegisterGcpRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> developerregistration.DeveloperRegistration: + def __call__( + self, + request: developerregistration.RegisterGcpRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developerregistration.DeveloperRegistration: r"""Call the register gcp method over HTTP. Args: @@ -445,32 +521,44 @@ def __call__(self, """ - http_options = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_http_options() + http_options = ( + _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_http_options() + ) request, metadata = self._interceptor.pre_register_gcp(request, metadata) - transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_transcoded_request(http_options, request) + transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_transcoded_request( + http_options, request + ) - body = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_request_body_json(transcoded_request) + body = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.DeveloperRegistrationServiceClient.RegisterGcp", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", "rpcName": "RegisterGcp", "httpRequest": http_request, @@ -479,7 +567,17 @@ def __call__(self, ) # Send the request - response = DeveloperRegistrationServiceRestTransport._RegisterGcp._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + DeveloperRegistrationServiceRestTransport._RegisterGcp._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. @@ -494,20 +592,26 @@ def __call__(self, resp = self._interceptor.post_register_gcp(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_register_gcp_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_register_gcp_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = developerregistration.DeveloperRegistration.to_json(response) + response_payload = ( + developerregistration.DeveloperRegistration.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.accounts_v1.DeveloperRegistrationServiceClient.register_gcp", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", "rpcName": "RegisterGcp", "metadata": http_response["headers"], @@ -516,7 +620,10 @@ def __call__(self, ) return resp - class _UnregisterGcp(_BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp, DeveloperRegistrationServiceRestStub): + class _UnregisterGcp( + _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp, + DeveloperRegistrationServiceRestStub, + ): def __hash__(self): return hash("DeveloperRegistrationServiceRestTransport.UnregisterGcp") @@ -528,27 +635,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: developerregistration.UnregisterGcpRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: developerregistration.UnregisterGcpRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the unregister gcp method over HTTP. Args: @@ -564,32 +673,44 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_http_options() + http_options = ( + _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_http_options() + ) request, metadata = self._interceptor.pre_unregister_gcp(request, metadata) - transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_transcoded_request(http_options, request) + transcoded_request = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_transcoded_request( + http_options, request + ) - body = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_request_body_json(transcoded_request) + body = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.DeveloperRegistrationServiceClient.UnregisterGcp", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.DeveloperRegistrationService", "rpcName": "UnregisterGcp", "httpRequest": http_request, @@ -598,7 +719,17 @@ def __call__(self, ) # Send the request - response = DeveloperRegistrationServiceRestTransport._UnregisterGcp._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ( + DeveloperRegistrationServiceRestTransport._UnregisterGcp._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. @@ -606,28 +737,34 @@ def __call__(self, raise core_exceptions.from_http_response(response) @property - def get_developer_registration(self) -> Callable[ - [developerregistration.GetDeveloperRegistrationRequest], - developerregistration.DeveloperRegistration]: + def get_developer_registration( + self, + ) -> Callable[ + [developerregistration.GetDeveloperRegistrationRequest], + developerregistration.DeveloperRegistration, + ]: # 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._GetDeveloperRegistration(self._session, self._host, self._interceptor) # type: ignore + return self._GetDeveloperRegistration(self._session, self._host, self._interceptor) # type: ignore @property - def register_gcp(self) -> Callable[ - [developerregistration.RegisterGcpRequest], - developerregistration.DeveloperRegistration]: + def register_gcp( + self, + ) -> Callable[ + [developerregistration.RegisterGcpRequest], + developerregistration.DeveloperRegistration, + ]: # 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._RegisterGcp(self._session, self._host, self._interceptor) # type: ignore + return self._RegisterGcp(self._session, self._host, self._interceptor) # type: ignore @property - def unregister_gcp(self) -> Callable[ - [developerregistration.UnregisterGcpRequest], - empty_pb2.Empty]: + def unregister_gcp( + self, + ) -> Callable[[developerregistration.UnregisterGcpRequest], 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._UnregisterGcp(self._session, self._host, self._interceptor) # type: ignore + return self._UnregisterGcp(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -637,6 +774,4 @@ def close(self): self._session.close() -__all__=( - 'DeveloperRegistrationServiceRestTransport', -) +__all__ = ("DeveloperRegistrationServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py index 5cf6937a4b0e..53a463c65324 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/developer_registration_service/transports/rest_base.py @@ -14,21 +14,21 @@ # 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 DeveloperRegistrationServiceTransport, 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_accounts_v1.types import developerregistration +from .base import DEFAULT_CLIENT_INFO, DeveloperRegistrationServiceTransport -class _BaseDeveloperRegistrationServiceRestTransport(DeveloperRegistrationServiceTransport): + +class _BaseDeveloperRegistrationServiceRestTransport( + DeveloperRegistrationServiceTransport +): """Base REST backend transport for DeveloperRegistrationService. Note: This class is not meant to be used directly. Use its sync and @@ -41,14 +41,16 @@ class _BaseDeveloperRegistrationServiceRestTransport(DeveloperRegistrationServic 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 +74,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -83,42 +87,54 @@ 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 _BaseGetDeveloperRegistration: 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': '/accounts/v1/{name=accounts/*/developerRegistration}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/developerRegistration}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = developerregistration.GetDeveloperRegistrationRequest.pb(request) + pb_request = developerregistration.GetDeveloperRegistrationRequest.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(_BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._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( + _BaseDeveloperRegistrationServiceRestTransport._BaseGetDeveloperRegistration._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -127,20 +143,24 @@ class _BaseRegisterGcp: 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': '/accounts/v1/{name=accounts/*/developerRegistration}:registerGcp', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/developerRegistration}:registerGcp", + "body": "*", + }, ] return http_options @@ -155,17 +175,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(_BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._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( + _BaseDeveloperRegistrationServiceRestTransport._BaseRegisterGcp._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,20 +200,24 @@ class _BaseUnregisterGcp: 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': '/accounts/v1/{name=accounts/*/developerRegistration}:unregisterGcp', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/developerRegistration}:unregisterGcp", + "body": "*", + }, ] return http_options @@ -202,22 +232,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._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( + _BaseDeveloperRegistrationServiceRestTransport._BaseUnregisterGcp._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseDeveloperRegistrationServiceRestTransport', -) +__all__ = ("_BaseDeveloperRegistrationServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py index d5ee3fce97c1..3d257987b684 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import EmailPreferencesServiceClient from .async_client import EmailPreferencesServiceAsyncClient +from .client import EmailPreferencesServiceClient __all__ = ( - 'EmailPreferencesServiceClient', - 'EmailPreferencesServiceAsyncClient', + "EmailPreferencesServiceClient", + "EmailPreferencesServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py index bba2855beda3..5cb74504c134 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,19 +45,23 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import emailpreferences -from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport + from .client import EmailPreferencesServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, EmailPreferencesServiceTransport +from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport 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 EmailPreferencesServiceAsyncClient: """Service to support the ``EmailPreferences`` API.""" @@ -57,21 +71,45 @@ class EmailPreferencesServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - email_preferences_path = staticmethod(EmailPreferencesServiceClient.email_preferences_path) - parse_email_preferences_path = staticmethod(EmailPreferencesServiceClient.parse_email_preferences_path) - common_billing_account_path = staticmethod(EmailPreferencesServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EmailPreferencesServiceClient.parse_common_billing_account_path) + email_preferences_path = staticmethod( + EmailPreferencesServiceClient.email_preferences_path + ) + parse_email_preferences_path = staticmethod( + EmailPreferencesServiceClient.parse_email_preferences_path + ) + common_billing_account_path = staticmethod( + EmailPreferencesServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EmailPreferencesServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(EmailPreferencesServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(EmailPreferencesServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(EmailPreferencesServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(EmailPreferencesServiceClient.parse_common_organization_path) - common_project_path = staticmethod(EmailPreferencesServiceClient.common_project_path) - parse_common_project_path = staticmethod(EmailPreferencesServiceClient.parse_common_project_path) - common_location_path = staticmethod(EmailPreferencesServiceClient.common_location_path) - parse_common_location_path = staticmethod(EmailPreferencesServiceClient.parse_common_location_path) + parse_common_folder_path = staticmethod( + EmailPreferencesServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + EmailPreferencesServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + EmailPreferencesServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + EmailPreferencesServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + EmailPreferencesServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + EmailPreferencesServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + EmailPreferencesServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -107,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: @@ -170,12 +210,20 @@ def universe_domain(self) -> str: get_transport_class = EmailPreferencesServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = "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, + EmailPreferencesServiceTransport, + Callable[..., EmailPreferencesServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the email preferences service async client. Args: @@ -230,35 +278,45 @@ 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.accounts_v1.EmailPreferencesServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", - "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.accounts.v1.EmailPreferencesService", "credentialsType": None, - } + }, ) - async def get_email_preferences(self, - request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: + async def get_email_preferences( + self, + request: Optional[ + Union[emailpreferences.GetEmailPreferencesRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: r"""Returns the email preferences for a Merchant Center account user. This service only permits retrieving and updating email preferences for the authenticated user. Use the - name=accounts/*/users/me/emailPreferences alias to get + `name=accounts/*/users/me/emailPreferences` alias to get preferences for the authenticated user. .. code-block:: python @@ -320,10 +378,14 @@ async def sample_get_email_preferences(): # - 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. @@ -337,14 +399,14 @@ async def sample_get_email_preferences(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_email_preferences] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_email_preferences + ] # 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. @@ -361,15 +423,18 @@ async def sample_get_email_preferences(): # Done; return the response. return response - async def update_email_preferences(self, - request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, - *, - email_preferences: Optional[emailpreferences.EmailPreferences] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: + async def update_email_preferences( + self, + request: Optional[ + Union[emailpreferences.UpdateEmailPreferencesRequest, dict] + ] = None, + *, + email_preferences: Optional[emailpreferences.EmailPreferences] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: r"""Updates the email preferences for a Merchant Center account user. Advanced account users should specify the advanced account rather than a sub-account of the advanced account. @@ -380,7 +445,7 @@ async def update_email_preferences(self, It is invalid for updates to specify an UNCONFIRMED opt-in status value. - Use the name=accounts/*/users/me/emailPreferences alias to + Use the `name=accounts/*/users/me/emailPreferences` alias to update preferences for the authenticated user. .. code-block:: python @@ -451,10 +516,14 @@ async def sample_update_email_preferences(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [email_preferences, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -470,14 +539,16 @@ async def sample_update_email_preferences(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_email_preferences] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_email_preferences + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("email_preferences.name", request.email_preferences.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("email_preferences.name", request.email_preferences.name),) + ), ) # Validate the universe domain. @@ -500,12 +571,13 @@ async def __aenter__(self) -> "EmailPreferencesServiceAsyncClient": 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__ = ( - "EmailPreferencesServiceAsyncClient", -) +__all__ = ("EmailPreferencesServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py index cd208c085680..d04ff34d5ce6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,8 +62,10 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.types import emailpreferences -from .transports.base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, EmailPreferencesServiceTransport from .transports.grpc import EmailPreferencesServiceGrpcTransport from .transports.grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport from .transports.rest import EmailPreferencesServiceRestTransport @@ -63,14 +78,18 @@ class EmailPreferencesServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[EmailPreferencesServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[EmailPreferencesServiceTransport]] _transport_registry["grpc"] = EmailPreferencesServiceGrpcTransport _transport_registry["grpc_asyncio"] = EmailPreferencesServiceGrpcAsyncIOTransport _transport_registry["rest"] = EmailPreferencesServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EmailPreferencesServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EmailPreferencesServiceTransport]: """Returns an appropriate transport class. Args: @@ -162,8 +181,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EmailPreferencesServiceClient: 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) @@ -180,73 +198,105 @@ def transport(self) -> EmailPreferencesServiceTransport: return self._transport @staticmethod - def email_preferences_path(account: str,email: str,) -> str: + def email_preferences_path( + account: str, + email: str, + ) -> str: """Returns a fully-qualified email_preferences string.""" - return "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) + return "accounts/{account}/users/{email}/emailPreferences".format( + account=account, + email=email, + ) @staticmethod - def parse_email_preferences_path(path: str) -> Dict[str,str]: + def parse_email_preferences_path(path: str) -> Dict[str, str]: """Parses a email_preferences path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/users/(?P.+?)/emailPreferences$", path) + m = re.match( + r"^accounts/(?P.+?)/users/(?P.+?)/emailPreferences$", 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: @@ -278,16 +328,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 @@ -300,7 +356,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 @@ -321,13 +379,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 @@ -350,7 +414,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: @@ -366,17 +432,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 = EmailPreferencesServiceClient._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 = EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + EmailPreferencesServiceClient._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: @@ -412,15 +488,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 @@ -453,12 +532,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EmailPreferencesServiceTransport, Callable[..., EmailPreferencesServiceTransport]]] = 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, + EmailPreferencesServiceTransport, + Callable[..., EmailPreferencesServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the email preferences service client. Args: @@ -513,14 +600,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 = EmailPreferencesServiceClient._read_environment_variables() - self._client_cert_source = EmailPreferencesServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EmailPreferencesServiceClient._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, + ) = EmailPreferencesServiceClient._read_environment_variables() + self._client_cert_source = ( + EmailPreferencesServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = EmailPreferencesServiceClient._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 @@ -531,7 +630,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 @@ -540,8 +641,10 @@ def __init__(self, *, if transport_provided: # transport is a EmailPreferencesServiceTransport 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 " @@ -550,20 +653,30 @@ def __init__(self, *, self._transport = cast(EmailPreferencesServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - EmailPreferencesServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or EmailPreferencesServiceClient._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[EmailPreferencesServiceTransport], Callable[..., EmailPreferencesServiceTransport]] = ( + transport_init: Union[ + Type[EmailPreferencesServiceTransport], + Callable[..., EmailPreferencesServiceTransport], + ] = ( EmailPreferencesServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., EmailPreferencesServiceTransport], transport) @@ -582,32 +695,43 @@ 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.accounts_v1.EmailPreferencesServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", - "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.accounts.v1.EmailPreferencesService", "credentialsType": None, - } + }, ) - def get_email_preferences(self, - request: Optional[Union[emailpreferences.GetEmailPreferencesRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: + def get_email_preferences( + self, + request: Optional[ + Union[emailpreferences.GetEmailPreferencesRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: r"""Returns the email preferences for a Merchant Center account user. This service only permits retrieving and updating email preferences for the authenticated user. Use the - name=accounts/*/users/me/emailPreferences alias to get + `name=accounts/*/users/me/emailPreferences` alias to get preferences for the authenticated user. .. code-block:: python @@ -669,10 +793,14 @@ def sample_get_email_preferences(): # - 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. @@ -690,9 +818,7 @@ def sample_get_email_preferences(): # 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. @@ -709,15 +835,18 @@ def sample_get_email_preferences(): # Done; return the response. return response - def update_email_preferences(self, - request: Optional[Union[emailpreferences.UpdateEmailPreferencesRequest, dict]] = None, - *, - email_preferences: Optional[emailpreferences.EmailPreferences] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> emailpreferences.EmailPreferences: + def update_email_preferences( + self, + request: Optional[ + Union[emailpreferences.UpdateEmailPreferencesRequest, dict] + ] = None, + *, + email_preferences: Optional[emailpreferences.EmailPreferences] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: r"""Updates the email preferences for a Merchant Center account user. Advanced account users should specify the advanced account rather than a sub-account of the advanced account. @@ -728,7 +857,7 @@ def update_email_preferences(self, It is invalid for updates to specify an UNCONFIRMED opt-in status value. - Use the name=accounts/*/users/me/emailPreferences alias to + Use the `name=accounts/*/users/me/emailPreferences` alias to update preferences for the authenticated user. .. code-block:: python @@ -799,10 +928,14 @@ def sample_update_email_preferences(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [email_preferences, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -822,9 +955,9 @@ def sample_update_email_preferences(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("email_preferences.name", request.email_preferences.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("email_preferences.name", request.email_preferences.name),) + ), ) # Validate the universe domain. @@ -855,16 +988,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__ = ( - "EmailPreferencesServiceClient", -) +__all__ = ("EmailPreferencesServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py index 3bfd9590e738..c141c8b96c4e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/email_preferences_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import EmailPreferencesServiceTransport from .grpc import EmailPreferencesServiceGrpcTransport from .grpc_asyncio import EmailPreferencesServiceGrpcAsyncIOTransport -from .rest import EmailPreferencesServiceRestTransport -from .rest import EmailPreferencesServiceRestInterceptor - +from .rest import ( + EmailPreferencesServiceRestInterceptor, + EmailPreferencesServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EmailPreferencesServiceTransport]] -_transport_registry['grpc'] = EmailPreferencesServiceGrpcTransport -_transport_registry['grpc_asyncio'] = EmailPreferencesServiceGrpcAsyncIOTransport -_transport_registry['rest'] = EmailPreferencesServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[EmailPreferencesServiceTransport]] +_transport_registry["grpc"] = EmailPreferencesServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EmailPreferencesServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EmailPreferencesServiceRestTransport __all__ = ( - 'EmailPreferencesServiceTransport', - 'EmailPreferencesServiceGrpcTransport', - 'EmailPreferencesServiceGrpcAsyncIOTransport', - 'EmailPreferencesServiceRestTransport', - 'EmailPreferencesServiceRestInterceptor', + "EmailPreferencesServiceTransport", + "EmailPreferencesServiceGrpcTransport", + "EmailPreferencesServiceGrpcAsyncIOTransport", + "EmailPreferencesServiceRestTransport", + "EmailPreferencesServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py index 0a3c86442a93..98f076ff7f14 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import emailpreferences -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__ @@ -38,24 +39,23 @@ class EmailPreferencesServiceTransport(abc.ABC): """Abstract transport class for EmailPreferencesService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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 get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - Union[ - emailpreferences.EmailPreferences, - Awaitable[emailpreferences.EmailPreferences] - ]]: + def get_email_preferences( + self, + ) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + Union[ + emailpreferences.EmailPreferences, + Awaitable[emailpreferences.EmailPreferences], + ], + ]: raise NotImplementedError() @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - Union[ - emailpreferences.EmailPreferences, - Awaitable[emailpreferences.EmailPreferences] - ]]: + def update_email_preferences( + self, + ) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + Union[ + emailpreferences.EmailPreferences, + Awaitable[emailpreferences.EmailPreferences], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'EmailPreferencesServiceTransport', -) +__all__ = ("EmailPreferencesServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py index 0cde092fb452..e4b1d520a6d2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import emailpreferences -from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, EmailPreferencesServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": client_call_details.method, "response": grpc_response, @@ -113,23 +119,26 @@ class EmailPreferencesServiceGrpcTransport(EmailPreferencesServiceTransport): 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: @@ -251,19 +260,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. @@ -298,25 +311,26 @@ 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 get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - emailpreferences.EmailPreferences]: + def get_email_preferences( + self, + ) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], emailpreferences.EmailPreferences + ]: r"""Return a callable for the get email preferences method over gRPC. Returns the email preferences for a Merchant Center account user. This service only permits retrieving and updating email preferences for the authenticated user. Use the - name=accounts/*/users/me/emailPreferences alias to get + `name=accounts/*/users/me/emailPreferences` alias to get preferences for the authenticated user. Returns: @@ -329,18 +343,21 @@ def get_email_preferences(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_email_preferences' not in self._stubs: - self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.EmailPreferencesService/GetEmailPreferences', + if "get_email_preferences" not in self._stubs: + self._stubs["get_email_preferences"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.EmailPreferencesService/GetEmailPreferences", request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, response_deserializer=emailpreferences.EmailPreferences.deserialize, ) - return self._stubs['get_email_preferences'] + return self._stubs["get_email_preferences"] @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - emailpreferences.EmailPreferences]: + def update_email_preferences( + self, + ) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + emailpreferences.EmailPreferences, + ]: r"""Return a callable for the update email preferences method over gRPC. Updates the email preferences for a Merchant Center account @@ -353,7 +370,7 @@ def update_email_preferences(self) -> Callable[ It is invalid for updates to specify an UNCONFIRMED opt-in status value. - Use the name=accounts/*/users/me/emailPreferences alias to + Use the `name=accounts/*/users/me/emailPreferences` alias to update preferences for the authenticated user. Returns: @@ -366,13 +383,13 @@ def update_email_preferences(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_email_preferences' not in self._stubs: - self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.EmailPreferencesService/UpdateEmailPreferences', + if "update_email_preferences" not in self._stubs: + self._stubs["update_email_preferences"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.EmailPreferencesService/UpdateEmailPreferences", request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, response_deserializer=emailpreferences.EmailPreferences.deserialize, ) - return self._stubs['update_email_preferences'] + return self._stubs["update_email_preferences"] def close(self): self._logged_channel.close() @@ -382,6 +399,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'EmailPreferencesServiceGrpcTransport', -) +__all__ = ("EmailPreferencesServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py index 31d51f56cf1f..d3a80a6aaee6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import emailpreferences -from .base import EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, EmailPreferencesServiceTransport from .grpc import EmailPreferencesServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -122,13 +130,15 @@ class EmailPreferencesServiceGrpcAsyncIOTransport(EmailPreferencesServiceTranspo _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. @@ -158,24 +168,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: @@ -299,7 +311,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) @@ -314,15 +328,18 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - Awaitable[emailpreferences.EmailPreferences]]: + def get_email_preferences( + self, + ) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], + Awaitable[emailpreferences.EmailPreferences], + ]: r"""Return a callable for the get email preferences method over gRPC. Returns the email preferences for a Merchant Center account user. This service only permits retrieving and updating email preferences for the authenticated user. Use the - name=accounts/*/users/me/emailPreferences alias to get + `name=accounts/*/users/me/emailPreferences` alias to get preferences for the authenticated user. Returns: @@ -335,18 +352,21 @@ def get_email_preferences(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_email_preferences' not in self._stubs: - self._stubs['get_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.EmailPreferencesService/GetEmailPreferences', + if "get_email_preferences" not in self._stubs: + self._stubs["get_email_preferences"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.EmailPreferencesService/GetEmailPreferences", request_serializer=emailpreferences.GetEmailPreferencesRequest.serialize, response_deserializer=emailpreferences.EmailPreferences.deserialize, ) - return self._stubs['get_email_preferences'] + return self._stubs["get_email_preferences"] @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - Awaitable[emailpreferences.EmailPreferences]]: + def update_email_preferences( + self, + ) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + Awaitable[emailpreferences.EmailPreferences], + ]: r"""Return a callable for the update email preferences method over gRPC. Updates the email preferences for a Merchant Center account @@ -359,7 +379,7 @@ def update_email_preferences(self) -> Callable[ It is invalid for updates to specify an UNCONFIRMED opt-in status value. - Use the name=accounts/*/users/me/emailPreferences alias to + Use the `name=accounts/*/users/me/emailPreferences` alias to update preferences for the authenticated user. Returns: @@ -372,16 +392,16 @@ def update_email_preferences(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_email_preferences' not in self._stubs: - self._stubs['update_email_preferences'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.EmailPreferencesService/UpdateEmailPreferences', + if "update_email_preferences" not in self._stubs: + self._stubs["update_email_preferences"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.EmailPreferencesService/UpdateEmailPreferences", request_serializer=emailpreferences.UpdateEmailPreferencesRequest.serialize, response_deserializer=emailpreferences.EmailPreferences.deserialize, ) - return self._stubs['update_email_preferences'] + return self._stubs["update_email_preferences"] 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.get_email_preferences: self._wrap_method( self.get_email_preferences, @@ -408,6 +428,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'EmailPreferencesServiceGrpcAsyncIOTransport', -) +__all__ = ("EmailPreferencesServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py index ca3c521edd9d..1d0fa9eb5b28 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import emailpreferences - -from .rest_base import _BaseEmailPreferencesServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseEmailPreferencesServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,15 @@ def post_update_email_preferences(self, response): """ - def pre_get_email_preferences(self, request: emailpreferences.GetEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.GetEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_email_preferences( + self, + request: emailpreferences.GetEmailPreferencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + emailpreferences.GetEmailPreferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_email_preferences Override in a subclass to manipulate the request or metadata @@ -106,7 +109,9 @@ def pre_get_email_preferences(self, request: emailpreferences.GetEmailPreference """ return request, metadata - def post_get_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: + def post_get_email_preferences( + self, response: emailpreferences.EmailPreferences + ) -> emailpreferences.EmailPreferences: """Post-rpc interceptor for get_email_preferences DEPRECATED. Please use the `post_get_email_preferences_with_metadata` @@ -119,7 +124,13 @@ def post_get_email_preferences(self, response: emailpreferences.EmailPreferences """ return response - def post_get_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_email_preferences_with_metadata( + self, + response: emailpreferences.EmailPreferences, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_email_preferences Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +145,14 @@ def post_get_email_preferences_with_metadata(self, response: emailpreferences.Em """ return response, metadata - def pre_update_email_preferences(self, request: emailpreferences.UpdateEmailPreferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.UpdateEmailPreferencesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_email_preferences( + self, + request: emailpreferences.UpdateEmailPreferencesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + emailpreferences.UpdateEmailPreferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_email_preferences Override in a subclass to manipulate the request or metadata @@ -142,7 +160,9 @@ def pre_update_email_preferences(self, request: emailpreferences.UpdateEmailPref """ return request, metadata - def post_update_email_preferences(self, response: emailpreferences.EmailPreferences) -> emailpreferences.EmailPreferences: + def post_update_email_preferences( + self, response: emailpreferences.EmailPreferences + ) -> emailpreferences.EmailPreferences: """Post-rpc interceptor for update_email_preferences DEPRECATED. Please use the `post_update_email_preferences_with_metadata` @@ -155,7 +175,13 @@ def post_update_email_preferences(self, response: emailpreferences.EmailPreferen """ return response - def post_update_email_preferences_with_metadata(self, response: emailpreferences.EmailPreferences, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_email_preferences_with_metadata( + self, + response: emailpreferences.EmailPreferences, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + emailpreferences.EmailPreferences, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for update_email_preferences Override in a subclass to read or manipulate the response or metadata after it @@ -190,20 +216,21 @@ class EmailPreferencesServiceRestTransport(_BaseEmailPreferencesServiceRestTrans 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[EmailPreferencesServiceRestInterceptor] = 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[EmailPreferencesServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -246,16 +273,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 EmailPreferencesServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences, EmailPreferencesServiceRestStub): + class _GetEmailPreferences( + _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences, + EmailPreferencesServiceRestStub, + ): def __hash__(self): return hash("EmailPreferencesServiceRestTransport.GetEmailPreferences") @@ -267,26 +298,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: emailpreferences.GetEmailPreferencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> emailpreferences.EmailPreferences: + def __call__( + self, + request: emailpreferences.GetEmailPreferencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: r"""Call the get email preferences method over HTTP. Args: @@ -311,30 +344,42 @@ def __call__(self, """ - http_options = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_http_options() + http_options = ( + _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_http_options() + ) - request, metadata = self._interceptor.pre_get_email_preferences(request, metadata) - transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_email_preferences( + request, metadata + ) + transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.EmailPreferencesServiceClient.GetEmailPreferences", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": "GetEmailPreferences", "httpRequest": http_request, @@ -343,7 +388,16 @@ def __call__(self, ) # Send the request - response = EmailPreferencesServiceRestTransport._GetEmailPreferences._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + EmailPreferencesServiceRestTransport._GetEmailPreferences._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -358,20 +412,26 @@ def __call__(self, resp = self._interceptor.post_get_email_preferences(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_email_preferences_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_email_preferences_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = emailpreferences.EmailPreferences.to_json(response) + response_payload = emailpreferences.EmailPreferences.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.accounts_v1.EmailPreferencesServiceClient.get_email_preferences", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": "GetEmailPreferences", "metadata": http_response["headers"], @@ -380,7 +440,10 @@ def __call__(self, ) return resp - class _UpdateEmailPreferences(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences, EmailPreferencesServiceRestStub): + class _UpdateEmailPreferences( + _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences, + EmailPreferencesServiceRestStub, + ): def __hash__(self): return hash("EmailPreferencesServiceRestTransport.UpdateEmailPreferences") @@ -392,27 +455,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: emailpreferences.UpdateEmailPreferencesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> emailpreferences.EmailPreferences: + def __call__( + self, + request: emailpreferences.UpdateEmailPreferencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> emailpreferences.EmailPreferences: r"""Call the update email preferences method over HTTP. Args: @@ -437,32 +502,46 @@ def __call__(self, """ - http_options = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_http_options() + http_options = ( + _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_http_options() + ) - request, metadata = self._interceptor.pre_update_email_preferences(request, metadata) - transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_email_preferences( + request, metadata + ) + transcoded_request = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_transcoded_request( + http_options, request + ) - body = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_request_body_json(transcoded_request) + body = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.EmailPreferencesServiceClient.UpdateEmailPreferences", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": "UpdateEmailPreferences", "httpRequest": http_request, @@ -471,7 +550,15 @@ def __call__(self, ) # Send the request - response = EmailPreferencesServiceRestTransport._UpdateEmailPreferences._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = EmailPreferencesServiceRestTransport._UpdateEmailPreferences._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. @@ -486,20 +573,26 @@ def __call__(self, resp = self._interceptor.post_update_email_preferences(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_email_preferences_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_email_preferences_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = emailpreferences.EmailPreferences.to_json(response) + response_payload = emailpreferences.EmailPreferences.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.accounts_v1.EmailPreferencesServiceClient.update_email_preferences", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.EmailPreferencesService", "rpcName": "UpdateEmailPreferences", "metadata": http_response["headers"], @@ -509,20 +602,25 @@ def __call__(self, return resp @property - def get_email_preferences(self) -> Callable[ - [emailpreferences.GetEmailPreferencesRequest], - emailpreferences.EmailPreferences]: + def get_email_preferences( + self, + ) -> Callable[ + [emailpreferences.GetEmailPreferencesRequest], emailpreferences.EmailPreferences + ]: # 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._GetEmailPreferences(self._session, self._host, self._interceptor) # type: ignore + return self._GetEmailPreferences(self._session, self._host, self._interceptor) # type: ignore @property - def update_email_preferences(self) -> Callable[ - [emailpreferences.UpdateEmailPreferencesRequest], - emailpreferences.EmailPreferences]: + def update_email_preferences( + self, + ) -> Callable[ + [emailpreferences.UpdateEmailPreferencesRequest], + emailpreferences.EmailPreferences, + ]: # 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._UpdateEmailPreferences(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateEmailPreferences(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -532,6 +630,4 @@ def close(self): self._session.close() -__all__=( - 'EmailPreferencesServiceRestTransport', -) +__all__ = ("EmailPreferencesServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py similarity index 64% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py index 89575492b481..46107ef344b1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/email_preferences_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 EmailPreferencesServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import emailpreferences +from .base import DEFAULT_CLIENT_INFO, EmailPreferencesServiceTransport + class _BaseEmailPreferencesServiceRestTransport(EmailPreferencesServiceTransport): """Base REST backend transport for EmailPreferencesService. @@ -40,14 +38,16 @@ class _BaseEmailPreferencesServiceRestTransport(EmailPreferencesServiceTransport 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseGetEmailPreferences: 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': '/accounts/v1/{name=accounts/*/users/*/emailPreferences}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/users/*/emailPreferences}", + }, ] return http_options @@ -113,11 +119,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(_BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._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( + _BaseEmailPreferencesServiceRestTransport._BaseGetEmailPreferences._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,20 +138,26 @@ class _BaseUpdateEmailPreferences: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{email_preferences.name=accounts/*/users/*/emailPreferences}', - 'body': 'email_preferences', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{email_preferences.name=accounts/*/users/*/emailPreferences}", + "body": "email_preferences", + }, ] return http_options @@ -154,22 +172,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._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( + _BaseEmailPreferencesServiceRestTransport._BaseUpdateEmailPreferences._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseEmailPreferencesServiceRestTransport', -) +__all__ = ("_BaseEmailPreferencesServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py index 38f66e5e7f00..71ba1921a2cc 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import GbpAccountsServiceClient from .async_client import GbpAccountsServiceAsyncClient +from .client import GbpAccountsServiceClient __all__ = ( - 'GbpAccountsServiceClient', - 'GbpAccountsServiceAsyncClient', + "GbpAccountsServiceClient", + "GbpAccountsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py index f6b60872b221..07d73c61f4c0 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,20 +45,24 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import empty_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import pagers from google.shopping.merchant_accounts_v1.types import gbpaccounts -from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport + from .client import GbpAccountsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, GbpAccountsServiceTransport +from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport 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 GbpAccountsServiceAsyncClient: """The service facilitates the management of a merchant's Google Business Profile (GBP) account settings. This API defines the @@ -69,17 +83,33 @@ class GbpAccountsServiceAsyncClient: account_path = staticmethod(GbpAccountsServiceClient.account_path) parse_account_path = staticmethod(GbpAccountsServiceClient.parse_account_path) gbp_account_path = staticmethod(GbpAccountsServiceClient.gbp_account_path) - parse_gbp_account_path = staticmethod(GbpAccountsServiceClient.parse_gbp_account_path) - common_billing_account_path = staticmethod(GbpAccountsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(GbpAccountsServiceClient.parse_common_billing_account_path) + parse_gbp_account_path = staticmethod( + GbpAccountsServiceClient.parse_gbp_account_path + ) + common_billing_account_path = staticmethod( + GbpAccountsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + GbpAccountsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(GbpAccountsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(GbpAccountsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(GbpAccountsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(GbpAccountsServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + GbpAccountsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + GbpAccountsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + GbpAccountsServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(GbpAccountsServiceClient.common_project_path) - parse_common_project_path = staticmethod(GbpAccountsServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + GbpAccountsServiceClient.parse_common_project_path + ) common_location_path = staticmethod(GbpAccountsServiceClient.common_location_path) - parse_common_location_path = staticmethod(GbpAccountsServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + GbpAccountsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -115,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: @@ -178,12 +210,20 @@ def universe_domain(self) -> str: get_transport_class = GbpAccountsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = "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, + GbpAccountsServiceTransport, + Callable[..., GbpAccountsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the gbp accounts service async client. Args: @@ -238,31 +278,39 @@ 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.accounts_v1.GbpAccountsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", - "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.accounts.v1.GbpAccountsService", "credentialsType": None, - } + }, ) - async def list_gbp_accounts(self, - request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsAsyncPager: + async def list_gbp_accounts( + self, + request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsAsyncPager: r"""List the GBP accounts for a given merchant. .. code-block:: python @@ -325,10 +373,14 @@ async def sample_list_gbp_accounts(): # - 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 +394,14 @@ async def sample_list_gbp_accounts(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_gbp_accounts] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_gbp_accounts + ] # 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,14 +429,15 @@ async def sample_list_gbp_accounts(): # Done; return the response. return response - async def link_gbp_account(self, - request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), - ) -> gbpaccounts.LinkGbpAccountResponse: + async def link_gbp_account( + self, + request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: r"""Link the specified merchant to a GBP account for all countries. To run this method, you must have admin access to the Merchant @@ -448,10 +501,14 @@ async def sample_link_gbp_account(): # - 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. @@ -465,14 +522,14 @@ async def sample_link_gbp_account(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.link_gbp_account] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.link_gbp_account + ] # 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. @@ -495,12 +552,13 @@ async def __aenter__(self) -> "GbpAccountsServiceAsyncClient": 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__ = ( - "GbpAccountsServiceAsyncClient", -) +__all__ = ("GbpAccountsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py index 9e573d3a5f79..ab2ce90ba760 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,9 +62,11 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import empty_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import pagers from google.shopping.merchant_accounts_v1.types import gbpaccounts -from .transports.base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, GbpAccountsServiceTransport from .transports.grpc import GbpAccountsServiceGrpcTransport from .transports.grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport from .transports.rest import GbpAccountsServiceRestTransport @@ -64,14 +79,18 @@ class GbpAccountsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[GbpAccountsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[GbpAccountsServiceTransport]] _transport_registry["grpc"] = GbpAccountsServiceGrpcTransport _transport_registry["grpc_asyncio"] = GbpAccountsServiceGrpcAsyncIOTransport _transport_registry["rest"] = GbpAccountsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[GbpAccountsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[GbpAccountsServiceTransport]: """Returns an appropriate transport class. Args: @@ -168,8 +187,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: GbpAccountsServiceClient: 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) @@ -186,84 +204,120 @@ def transport(self) -> GbpAccountsServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def gbp_account_path(account: str,gbp_account: str,) -> str: + def gbp_account_path( + account: str, + gbp_account: str, + ) -> str: """Returns a fully-qualified gbp_account string.""" - return "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) + return "accounts/{account}/gbpAccounts/{gbp_account}".format( + account=account, + gbp_account=gbp_account, + ) @staticmethod - def parse_gbp_account_path(path: str) -> Dict[str,str]: + def parse_gbp_account_path(path: str) -> Dict[str, str]: """Parses a gbp_account path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/gbpAccounts/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/gbpAccounts/(?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: @@ -295,16 +349,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 @@ -317,7 +377,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 @@ -338,13 +400,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 @@ -367,7 +435,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): """Return the API endpoint used by the client. Args: @@ -383,17 +453,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = GbpAccountsServiceClient._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 = GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -429,15 +507,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -470,12 +551,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, GbpAccountsServiceTransport, Callable[..., GbpAccountsServiceTransport]]] = 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, + GbpAccountsServiceTransport, + Callable[..., GbpAccountsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the gbp accounts service client. Args: @@ -530,14 +619,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 = GbpAccountsServiceClient._read_environment_variables() - self._client_cert_source = GbpAccountsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = GbpAccountsServiceClient._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, + ) = GbpAccountsServiceClient._read_environment_variables() + self._client_cert_source = GbpAccountsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = GbpAccountsServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -548,7 +647,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -557,8 +658,10 @@ def __init__(self, *, if transport_provided: # transport is a GbpAccountsServiceTransport 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 " @@ -567,20 +670,30 @@ def __init__(self, *, self._transport = cast(GbpAccountsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - GbpAccountsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or GbpAccountsServiceClient._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[GbpAccountsServiceTransport], Callable[..., GbpAccountsServiceTransport]] = ( + transport_init: Union[ + Type[GbpAccountsServiceTransport], + Callable[..., GbpAccountsServiceTransport], + ] = ( GbpAccountsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., GbpAccountsServiceTransport], transport) @@ -599,28 +712,37 @@ 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.accounts_v1.GbpAccountsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", - "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.accounts.v1.GbpAccountsService", "credentialsType": None, - } + }, ) - def list_gbp_accounts(self, - request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsPager: + def list_gbp_accounts( + self, + request: Optional[Union[gbpaccounts.ListGbpAccountsRequest, 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.ListGbpAccountsPager: r"""List the GBP accounts for a given merchant. .. code-block:: python @@ -683,10 +805,14 @@ def sample_list_gbp_accounts(): # - 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. @@ -704,9 +830,7 @@ def sample_list_gbp_accounts(): # 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. @@ -734,14 +858,15 @@ def sample_list_gbp_accounts(): # Done; return the response. return response - def link_gbp_account(self, - request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), - ) -> gbpaccounts.LinkGbpAccountResponse: + def link_gbp_account( + self, + request: Optional[Union[gbpaccounts.LinkGbpAccountRequest, 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]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: r"""Link the specified merchant to a GBP account for all countries. To run this method, you must have admin access to the Merchant @@ -805,10 +930,14 @@ def sample_link_gbp_account(): # - 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. @@ -826,9 +955,7 @@ def sample_link_gbp_account(): # 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. @@ -859,16 +986,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__ = ( - "GbpAccountsServiceClient", -) +__all__ = ("GbpAccountsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py index 53128ed34e45..6bd1a64cac74 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_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 ListGbpAccountsPager: 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[..., gbpaccounts.ListGbpAccountsResponse], - request: gbpaccounts.ListGbpAccountsRequest, - response: gbpaccounts.ListGbpAccountsResponse, - *, - 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[..., gbpaccounts.ListGbpAccountsResponse], + request: gbpaccounts.ListGbpAccountsRequest, + response: gbpaccounts.ListGbpAccountsResponse, + *, + 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[gbpaccounts.ListGbpAccountsResponse]: 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[gbpaccounts.GbpAccount]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[gbpaccounts.GbpAccount]: yield from page.gbp_accounts 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 ListGbpAccountsAsyncPager: @@ -112,14 +134,17 @@ class ListGbpAccountsAsyncPager: 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[gbpaccounts.ListGbpAccountsResponse]], - request: gbpaccounts.ListGbpAccountsRequest, - response: gbpaccounts.ListGbpAccountsResponse, - *, - 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[gbpaccounts.ListGbpAccountsResponse]], + request: gbpaccounts.ListGbpAccountsRequest, + response: gbpaccounts.ListGbpAccountsResponse, + *, + 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[gbpaccounts.ListGbpAccountsResponse]: 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[gbpaccounts.GbpAccount]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py index 6576bf17bbcf..149eb40d1ed5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/gbp_accounts_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/__init__.py @@ -19,20 +19,20 @@ from .base import GbpAccountsServiceTransport from .grpc import GbpAccountsServiceGrpcTransport from .grpc_asyncio import GbpAccountsServiceGrpcAsyncIOTransport -from .rest import GbpAccountsServiceRestTransport -from .rest import GbpAccountsServiceRestInterceptor - +from .rest import GbpAccountsServiceRestInterceptor, GbpAccountsServiceRestTransport # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[GbpAccountsServiceTransport]] -_transport_registry['grpc'] = GbpAccountsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = GbpAccountsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = GbpAccountsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[GbpAccountsServiceTransport]] +_transport_registry["grpc"] = GbpAccountsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = GbpAccountsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = GbpAccountsServiceRestTransport __all__ = ( - 'GbpAccountsServiceTransport', - 'GbpAccountsServiceGrpcTransport', - 'GbpAccountsServiceGrpcAsyncIOTransport', - 'GbpAccountsServiceRestTransport', - 'GbpAccountsServiceRestInterceptor', + "GbpAccountsServiceTransport", + "GbpAccountsServiceGrpcTransport", + "GbpAccountsServiceGrpcAsyncIOTransport", + "GbpAccountsServiceRestTransport", + "GbpAccountsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py index e2cfc1cb53de..2e4bf03a386e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import gbpaccounts -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__ @@ -38,24 +39,23 @@ class GbpAccountsServiceTransport(abc.ABC): """Abstract transport class for GbpAccountsService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - Union[ - gbpaccounts.ListGbpAccountsResponse, - Awaitable[gbpaccounts.ListGbpAccountsResponse] - ]]: + def list_gbp_accounts( + self, + ) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + Union[ + gbpaccounts.ListGbpAccountsResponse, + Awaitable[gbpaccounts.ListGbpAccountsResponse], + ], + ]: raise NotImplementedError() @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - Union[ - gbpaccounts.LinkGbpAccountResponse, - Awaitable[gbpaccounts.LinkGbpAccountResponse] - ]]: + def link_gbp_account( + self, + ) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + Union[ + gbpaccounts.LinkGbpAccountResponse, + Awaitable[gbpaccounts.LinkGbpAccountResponse], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'GbpAccountsServiceTransport', -) +__all__ = ("GbpAccountsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py index 1ea218d00ddd..99253ff57fb3 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import gbpaccounts -from .base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, GbpAccountsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -117,23 +123,26 @@ class GbpAccountsServiceGrpcTransport(GbpAccountsServiceTransport): 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: @@ -255,19 +264,23 @@ def __init__(self, *, ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = '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. @@ -302,19 +315,20 @@ 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_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - gbpaccounts.ListGbpAccountsResponse]: + def list_gbp_accounts( + self, + ) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], gbpaccounts.ListGbpAccountsResponse + ]: r"""Return a callable for the list gbp accounts method over gRPC. List the GBP accounts for a given merchant. @@ -329,18 +343,20 @@ def list_gbp_accounts(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_gbp_accounts' not in self._stubs: - self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.GbpAccountsService/ListGbpAccounts', + if "list_gbp_accounts" not in self._stubs: + self._stubs["list_gbp_accounts"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.GbpAccountsService/ListGbpAccounts", request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, ) - return self._stubs['list_gbp_accounts'] + return self._stubs["list_gbp_accounts"] @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - gbpaccounts.LinkGbpAccountResponse]: + def link_gbp_account( + self, + ) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], gbpaccounts.LinkGbpAccountResponse + ]: r"""Return a callable for the link gbp account method over gRPC. Link the specified merchant to a GBP account for all countries. @@ -360,13 +376,13 @@ def link_gbp_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'link_gbp_account' not in self._stubs: - self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.GbpAccountsService/LinkGbpAccount', + if "link_gbp_account" not in self._stubs: + self._stubs["link_gbp_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.GbpAccountsService/LinkGbpAccount", request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, ) - return self._stubs['link_gbp_account'] + return self._stubs["link_gbp_account"] def close(self): self._logged_channel.close() @@ -376,6 +392,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'GbpAccountsServiceGrpcTransport', -) +__all__ = ("GbpAccountsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py index f13033cb46c3..b8ffeebb1976 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import gbpaccounts -from .base import GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, GbpAccountsServiceTransport from .grpc import GbpAccountsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -126,13 +134,15 @@ class GbpAccountsServiceGrpcAsyncIOTransport(GbpAccountsServiceTransport): _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. @@ -162,24 +172,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = '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: @@ -303,7 +315,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) @@ -318,9 +332,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def list_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - Awaitable[gbpaccounts.ListGbpAccountsResponse]]: + def list_gbp_accounts( + self, + ) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], + Awaitable[gbpaccounts.ListGbpAccountsResponse], + ]: r"""Return a callable for the list gbp accounts method over gRPC. List the GBP accounts for a given merchant. @@ -335,18 +352,21 @@ def list_gbp_accounts(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_gbp_accounts' not in self._stubs: - self._stubs['list_gbp_accounts'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.GbpAccountsService/ListGbpAccounts', + if "list_gbp_accounts" not in self._stubs: + self._stubs["list_gbp_accounts"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.GbpAccountsService/ListGbpAccounts", request_serializer=gbpaccounts.ListGbpAccountsRequest.serialize, response_deserializer=gbpaccounts.ListGbpAccountsResponse.deserialize, ) - return self._stubs['list_gbp_accounts'] + return self._stubs["list_gbp_accounts"] @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - Awaitable[gbpaccounts.LinkGbpAccountResponse]]: + def link_gbp_account( + self, + ) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], + Awaitable[gbpaccounts.LinkGbpAccountResponse], + ]: r"""Return a callable for the link gbp account method over gRPC. Link the specified merchant to a GBP account for all countries. @@ -366,16 +386,16 @@ def link_gbp_account(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'link_gbp_account' not in self._stubs: - self._stubs['link_gbp_account'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.GbpAccountsService/LinkGbpAccount', + if "link_gbp_account" not in self._stubs: + self._stubs["link_gbp_account"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.GbpAccountsService/LinkGbpAccount", request_serializer=gbpaccounts.LinkGbpAccountRequest.serialize, response_deserializer=gbpaccounts.LinkGbpAccountResponse.deserialize, ) - return self._stubs['link_gbp_account'] + return self._stubs["link_gbp_account"] 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_gbp_accounts: self._wrap_method( self.list_gbp_accounts, @@ -402,6 +422,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'GbpAccountsServiceGrpcAsyncIOTransport', -) +__all__ = ("GbpAccountsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py similarity index 73% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py index f616ee81f402..de5cc1c305cc 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import gbpaccounts - -from .rest_base import _BaseGbpAccountsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseGbpAccountsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,14 @@ def post_list_gbp_accounts(self, response): """ - def pre_link_gbp_account(self, request: gbpaccounts.LinkGbpAccountRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_link_gbp_account( + self, + request: gbpaccounts.LinkGbpAccountRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gbpaccounts.LinkGbpAccountRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for link_gbp_account Override in a subclass to manipulate the request or metadata @@ -106,7 +108,9 @@ def pre_link_gbp_account(self, request: gbpaccounts.LinkGbpAccountRequest, metad """ return request, metadata - def post_link_gbp_account(self, response: gbpaccounts.LinkGbpAccountResponse) -> gbpaccounts.LinkGbpAccountResponse: + def post_link_gbp_account( + self, response: gbpaccounts.LinkGbpAccountResponse + ) -> gbpaccounts.LinkGbpAccountResponse: """Post-rpc interceptor for link_gbp_account DEPRECATED. Please use the `post_link_gbp_account_with_metadata` @@ -119,7 +123,13 @@ def post_link_gbp_account(self, response: gbpaccounts.LinkGbpAccountResponse) -> """ return response - def post_link_gbp_account_with_metadata(self, response: gbpaccounts.LinkGbpAccountResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.LinkGbpAccountResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_link_gbp_account_with_metadata( + self, + response: gbpaccounts.LinkGbpAccountResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gbpaccounts.LinkGbpAccountResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for link_gbp_account Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +144,13 @@ def post_link_gbp_account_with_metadata(self, response: gbpaccounts.LinkGbpAccou """ return response, metadata - def pre_list_gbp_accounts(self, request: gbpaccounts.ListGbpAccountsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_gbp_accounts( + self, + request: gbpaccounts.ListGbpAccountsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gbpaccounts.ListGbpAccountsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_gbp_accounts Override in a subclass to manipulate the request or metadata @@ -142,7 +158,9 @@ def pre_list_gbp_accounts(self, request: gbpaccounts.ListGbpAccountsRequest, met """ return request, metadata - def post_list_gbp_accounts(self, response: gbpaccounts.ListGbpAccountsResponse) -> gbpaccounts.ListGbpAccountsResponse: + def post_list_gbp_accounts( + self, response: gbpaccounts.ListGbpAccountsResponse + ) -> gbpaccounts.ListGbpAccountsResponse: """Post-rpc interceptor for list_gbp_accounts DEPRECATED. Please use the `post_list_gbp_accounts_with_metadata` @@ -155,7 +173,13 @@ def post_list_gbp_accounts(self, response: gbpaccounts.ListGbpAccountsResponse) """ return response - def post_list_gbp_accounts_with_metadata(self, response: gbpaccounts.ListGbpAccountsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gbpaccounts.ListGbpAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_gbp_accounts_with_metadata( + self, + response: gbpaccounts.ListGbpAccountsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gbpaccounts.ListGbpAccountsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for list_gbp_accounts Override in a subclass to read or manipulate the response or metadata after it @@ -194,20 +218,21 @@ class GbpAccountsServiceRestTransport(_BaseGbpAccountsServiceRestTransport): 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[GbpAccountsServiceRestInterceptor] = 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[GbpAccountsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -250,16 +275,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 GbpAccountsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _LinkGbpAccount(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount, GbpAccountsServiceRestStub): + class _LinkGbpAccount( + _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount, + GbpAccountsServiceRestStub, + ): def __hash__(self): return hash("GbpAccountsServiceRestTransport.LinkGbpAccount") @@ -271,27 +300,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: gbpaccounts.LinkGbpAccountRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gbpaccounts.LinkGbpAccountResponse: + def __call__( + self, + request: gbpaccounts.LinkGbpAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gbpaccounts.LinkGbpAccountResponse: r"""Call the link gbp account method over HTTP. Args: @@ -313,32 +344,46 @@ def __call__(self, """ - http_options = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_http_options() + http_options = ( + _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_http_options() + ) - request, metadata = self._interceptor.pre_link_gbp_account(request, metadata) - transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_link_gbp_account( + request, metadata + ) + transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_transcoded_request( + http_options, request + ) - body = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_request_body_json(transcoded_request) + body = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.GbpAccountsServiceClient.LinkGbpAccount", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": "LinkGbpAccount", "httpRequest": http_request, @@ -347,7 +392,15 @@ def __call__(self, ) # Send the request - response = GbpAccountsServiceRestTransport._LinkGbpAccount._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = GbpAccountsServiceRestTransport._LinkGbpAccount._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. @@ -362,20 +415,26 @@ def __call__(self, resp = self._interceptor.post_link_gbp_account(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_link_gbp_account_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_link_gbp_account_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = gbpaccounts.LinkGbpAccountResponse.to_json(response) + response_payload = gbpaccounts.LinkGbpAccountResponse.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.accounts_v1.GbpAccountsServiceClient.link_gbp_account", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": "LinkGbpAccount", "metadata": http_response["headers"], @@ -384,7 +443,10 @@ def __call__(self, ) return resp - class _ListGbpAccounts(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts, GbpAccountsServiceRestStub): + class _ListGbpAccounts( + _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts, + GbpAccountsServiceRestStub, + ): def __hash__(self): return hash("GbpAccountsServiceRestTransport.ListGbpAccounts") @@ -396,26 +458,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: gbpaccounts.ListGbpAccountsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gbpaccounts.ListGbpAccountsResponse: + def __call__( + self, + request: gbpaccounts.ListGbpAccountsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gbpaccounts.ListGbpAccountsResponse: r"""Call the list gbp accounts method over HTTP. Args: @@ -437,30 +501,42 @@ def __call__(self, """ - http_options = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_http_options() + http_options = ( + _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_http_options() + ) - request, metadata = self._interceptor.pre_list_gbp_accounts(request, metadata) - transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_gbp_accounts( + request, metadata + ) + transcoded_request = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.GbpAccountsServiceClient.ListGbpAccounts", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": "ListGbpAccounts", "httpRequest": http_request, @@ -469,7 +545,14 @@ def __call__(self, ) # Send the request - response = GbpAccountsServiceRestTransport._ListGbpAccounts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = GbpAccountsServiceRestTransport._ListGbpAccounts._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -484,20 +567,26 @@ def __call__(self, resp = self._interceptor.post_list_gbp_accounts(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_gbp_accounts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_gbp_accounts_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = gbpaccounts.ListGbpAccountsResponse.to_json(response) + response_payload = gbpaccounts.ListGbpAccountsResponse.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.accounts_v1.GbpAccountsServiceClient.list_gbp_accounts", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.GbpAccountsService", "rpcName": "ListGbpAccounts", "metadata": http_response["headers"], @@ -507,20 +596,24 @@ def __call__(self, return resp @property - def link_gbp_account(self) -> Callable[ - [gbpaccounts.LinkGbpAccountRequest], - gbpaccounts.LinkGbpAccountResponse]: + def link_gbp_account( + self, + ) -> Callable[ + [gbpaccounts.LinkGbpAccountRequest], gbpaccounts.LinkGbpAccountResponse + ]: # 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._LinkGbpAccount(self._session, self._host, self._interceptor) # type: ignore + return self._LinkGbpAccount(self._session, self._host, self._interceptor) # type: ignore @property - def list_gbp_accounts(self) -> Callable[ - [gbpaccounts.ListGbpAccountsRequest], - gbpaccounts.ListGbpAccountsResponse]: + def list_gbp_accounts( + self, + ) -> Callable[ + [gbpaccounts.ListGbpAccountsRequest], gbpaccounts.ListGbpAccountsResponse + ]: # 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._ListGbpAccounts(self._session, self._host, self._interceptor) # type: ignore + return self._ListGbpAccounts(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -530,6 +623,4 @@ def close(self): self._session.close() -__all__=( - 'GbpAccountsServiceRestTransport', -) +__all__ = ("GbpAccountsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py index be9f189e498a..2901acb52eb1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/gbp_accounts_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 GbpAccountsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import gbpaccounts +from .base import DEFAULT_CLIENT_INFO, GbpAccountsServiceTransport + class _BaseGbpAccountsServiceRestTransport(GbpAccountsServiceTransport): """Base REST backend transport for GbpAccountsService. @@ -40,14 +38,16 @@ class _BaseGbpAccountsServiceRestTransport(GbpAccountsServiceTransport): 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,27 +84,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseLinkGbpAccount: 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': '/accounts/v1/{parent=accounts/*}/gbpAccounts:linkGbpAccount', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/gbpAccounts:linkGbpAccount", + "body": "*", + }, ] return http_options @@ -117,17 +123,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._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( + _BaseGbpAccountsServiceRestTransport._BaseLinkGbpAccount._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -136,19 +148,23 @@ class _BaseListGbpAccounts: 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': '/accounts/v1/{parent=accounts/*}/gbpAccounts', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/gbpAccounts", + }, ] return http_options @@ -160,16 +176,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(_BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._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( + _BaseGbpAccountsServiceRestTransport._BaseListGbpAccounts._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseGbpAccountsServiceRestTransport', -) +__all__ = ("_BaseGbpAccountsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py index 96d41fc82ad2..a34bfab3a49e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import HomepageServiceClient from .async_client import HomepageServiceAsyncClient +from .client import HomepageServiceClient __all__ = ( - 'HomepageServiceClient', - 'HomepageServiceAsyncClient', + "HomepageServiceClient", + "HomepageServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py index 64e59d797ca1..4b7ca073d72f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,20 +45,24 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import homepage + from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage -from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport +from google.shopping.merchant_accounts_v1.types import homepage + from .client import HomepageServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, HomepageServiceTransport +from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport 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 HomepageServiceAsyncClient: """Service to support an API for a store's homepage.""" @@ -63,16 +77,30 @@ class HomepageServiceAsyncClient: homepage_path = staticmethod(HomepageServiceClient.homepage_path) parse_homepage_path = staticmethod(HomepageServiceClient.parse_homepage_path) - common_billing_account_path = staticmethod(HomepageServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(HomepageServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + HomepageServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + HomepageServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(HomepageServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(HomepageServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(HomepageServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(HomepageServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + HomepageServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + HomepageServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + HomepageServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(HomepageServiceClient.common_project_path) - parse_common_project_path = staticmethod(HomepageServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + HomepageServiceClient.parse_common_project_path + ) common_location_path = staticmethod(HomepageServiceClient.common_location_path) - parse_common_location_path = staticmethod(HomepageServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + HomepageServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -108,7 +136,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 +201,18 @@ def universe_domain(self) -> str: get_transport_class = HomepageServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = "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, HomepageServiceTransport, Callable[..., HomepageServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the homepage service async client. Args: @@ -231,31 +267,39 @@ 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.accounts_v1.HomepageServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", - "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.accounts.v1.HomepageService", "credentialsType": None, - } + }, ) - async def get_homepage(self, - request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: + async def get_homepage( + self, + request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Retrieves a store's homepage. .. code-block:: python @@ -321,10 +365,14 @@ async def sample_get_homepage(): # - 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. @@ -338,14 +386,14 @@ async def sample_get_homepage(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_homepage] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_homepage + ] # 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. @@ -362,15 +410,16 @@ async def sample_get_homepage(): # Done; return the response. return response - async def update_homepage(self, - request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, - *, - homepage: Optional[gsma_homepage.Homepage] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_homepage.Homepage: + async def update_homepage( + self, + request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, + *, + homepage: Optional[gsma_homepage.Homepage] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: r"""Updates a store's homepage. Executing this method requires admin access. @@ -447,10 +496,14 @@ async def sample_update_homepage(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [homepage, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -466,14 +519,16 @@ async def sample_update_homepage(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_homepage] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_homepage + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("homepage.name", request.homepage.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("homepage.name", request.homepage.name),) + ), ) # Validate the universe domain. @@ -490,13 +545,14 @@ async def sample_update_homepage(): # Done; return the response. return response - async def claim_homepage(self, - request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: + async def claim_homepage( + self, + request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Claims a store's homepage. Executing this method requires admin access. @@ -582,14 +638,14 @@ async def sample_claim_homepage(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.claim_homepage] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.claim_homepage + ] # 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. @@ -606,13 +662,14 @@ async def sample_claim_homepage(): # Done; return the response. return response - async def unclaim_homepage(self, - request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: + async def unclaim_homepage( + self, + request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Unclaims a store's homepage. Executing this method requires admin access. @@ -676,14 +733,14 @@ async def sample_unclaim_homepage(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.unclaim_homepage] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.unclaim_homepage + ] # 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. @@ -706,12 +763,13 @@ async def __aenter__(self) -> "HomepageServiceAsyncClient": 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__ = ( - "HomepageServiceAsyncClient", -) +__all__ = ("HomepageServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/client.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/client.py index 8cbb69d643b9..59fc11d0a38c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,9 +62,11 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import homepage + from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage -from .transports.base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_accounts_v1.types import homepage + +from .transports.base import DEFAULT_CLIENT_INFO, HomepageServiceTransport from .transports.grpc import HomepageServiceGrpcTransport from .transports.grpc_asyncio import HomepageServiceGrpcAsyncIOTransport from .transports.rest import HomepageServiceRestTransport @@ -64,14 +79,18 @@ class HomepageServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[HomepageServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[HomepageServiceTransport]] _transport_registry["grpc"] = HomepageServiceGrpcTransport _transport_registry["grpc_asyncio"] = HomepageServiceGrpcAsyncIOTransport _transport_registry["rest"] = HomepageServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[HomepageServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[HomepageServiceTransport]: """Returns an appropriate transport class. Args: @@ -163,8 +182,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: HomepageServiceClient: 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 +199,101 @@ def transport(self) -> HomepageServiceTransport: return self._transport @staticmethod - def homepage_path(account: str,) -> str: + def homepage_path( + account: str, + ) -> str: """Returns a fully-qualified homepage string.""" - return "accounts/{account}/homepage".format(account=account, ) + return "accounts/{account}/homepage".format( + account=account, + ) @staticmethod - def parse_homepage_path(path: str) -> Dict[str,str]: + def parse_homepage_path(path: str) -> Dict[str, str]: """Parses a homepage path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/homepage$", 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 +325,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 +353,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 +376,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 +411,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 +429,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = HomepageServiceClient._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 = HomepageServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = HomepageServiceClient._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 +483,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 +527,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, HomepageServiceTransport, Callable[..., HomepageServiceTransport]]] = 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, HomepageServiceTransport, Callable[..., HomepageServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the homepage service client. Args: @@ -514,14 +593,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 = HomepageServiceClient._read_environment_variables() - self._client_cert_source = HomepageServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = HomepageServiceClient._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, + ) = HomepageServiceClient._read_environment_variables() + self._client_cert_source = HomepageServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = HomepageServiceClient._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 +621,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 +632,10 @@ def __init__(self, *, if transport_provided: # transport is a HomepageServiceTransport 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 +644,29 @@ def __init__(self, *, self._transport = cast(HomepageServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - HomepageServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or HomepageServiceClient._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[HomepageServiceTransport], Callable[..., HomepageServiceTransport]] = ( + transport_init: Union[ + Type[HomepageServiceTransport], Callable[..., HomepageServiceTransport] + ] = ( HomepageServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., HomepageServiceTransport], transport) @@ -583,28 +685,37 @@ 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.accounts_v1.HomepageServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", - "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.accounts.v1.HomepageService", "credentialsType": None, - } + }, ) - def get_homepage(self, - request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: + def get_homepage( + self, + request: Optional[Union[homepage.GetHomepageRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Retrieves a store's homepage. .. code-block:: python @@ -670,10 +781,14 @@ def sample_get_homepage(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -691,9 +806,7 @@ def sample_get_homepage(): # 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. @@ -710,15 +823,16 @@ def sample_get_homepage(): # Done; return the response. return response - def update_homepage(self, - request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, - *, - homepage: Optional[gsma_homepage.Homepage] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_homepage.Homepage: + def update_homepage( + self, + request: Optional[Union[gsma_homepage.UpdateHomepageRequest, dict]] = None, + *, + homepage: Optional[gsma_homepage.Homepage] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: r"""Updates a store's homepage. Executing this method requires admin access. @@ -795,10 +909,14 @@ def sample_update_homepage(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [homepage, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -818,9 +936,9 @@ def sample_update_homepage(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("homepage.name", request.homepage.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("homepage.name", request.homepage.name),) + ), ) # Validate the universe domain. @@ -837,13 +955,14 @@ def sample_update_homepage(): # Done; return the response. return response - def claim_homepage(self, - request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: + def claim_homepage( + self, + request: Optional[Union[homepage.ClaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Claims a store's homepage. Executing this method requires admin access. @@ -934,9 +1053,7 @@ def sample_claim_homepage(): # 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. @@ -953,13 +1070,14 @@ def sample_claim_homepage(): # Done; return the response. return response - def unclaim_homepage(self, - request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> homepage.Homepage: + def unclaim_homepage( + self, + request: Optional[Union[homepage.UnclaimHomepageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Unclaims a store's homepage. Executing this method requires admin access. @@ -1028,9 +1146,7 @@ def sample_unclaim_homepage(): # 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. @@ -1061,16 +1177,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__ = ( - "HomepageServiceClient", -) +__all__ = ("HomepageServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py index e935fb45c364..e05ddbb1f705 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import HomepageServiceTransport from .grpc import HomepageServiceGrpcTransport from .grpc_asyncio import HomepageServiceGrpcAsyncIOTransport -from .rest import HomepageServiceRestTransport -from .rest import HomepageServiceRestInterceptor - +from .rest import HomepageServiceRestInterceptor, HomepageServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[HomepageServiceTransport]] -_transport_registry['grpc'] = HomepageServiceGrpcTransport -_transport_registry['grpc_asyncio'] = HomepageServiceGrpcAsyncIOTransport -_transport_registry['rest'] = HomepageServiceRestTransport +_transport_registry["grpc"] = HomepageServiceGrpcTransport +_transport_registry["grpc_asyncio"] = HomepageServiceGrpcAsyncIOTransport +_transport_registry["rest"] = HomepageServiceRestTransport __all__ = ( - 'HomepageServiceTransport', - 'HomepageServiceGrpcTransport', - 'HomepageServiceGrpcAsyncIOTransport', - 'HomepageServiceRestTransport', - 'HomepageServiceRestInterceptor', + "HomepageServiceTransport", + "HomepageServiceGrpcTransport", + "HomepageServiceGrpcAsyncIOTransport", + "HomepageServiceRestTransport", + "HomepageServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py index 6e27e1763dd5..282b5a8f5764 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1.types import homepage +from google.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from google.shopping.merchant_accounts_v1.types import homepage -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 HomepageServiceTransport(abc.ABC): """Abstract transport class for HomepageService.""" - 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 @@ -145,51 +153,51 @@ 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 get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - Union[ - homepage.Homepage, - Awaitable[homepage.Homepage] - ]]: + def get_homepage( + self, + ) -> Callable[ + [homepage.GetHomepageRequest], + Union[homepage.Homepage, Awaitable[homepage.Homepage]], + ]: raise NotImplementedError() @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - Union[ - gsma_homepage.Homepage, - Awaitable[gsma_homepage.Homepage] - ]]: + def update_homepage( + self, + ) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], + Union[gsma_homepage.Homepage, Awaitable[gsma_homepage.Homepage]], + ]: raise NotImplementedError() @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - Union[ - homepage.Homepage, - Awaitable[homepage.Homepage] - ]]: + def claim_homepage( + self, + ) -> Callable[ + [homepage.ClaimHomepageRequest], + Union[homepage.Homepage, Awaitable[homepage.Homepage]], + ]: raise NotImplementedError() @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - Union[ - homepage.Homepage, - Awaitable[homepage.Homepage] - ]]: + def unclaim_homepage( + self, + ) -> Callable[ + [homepage.UnclaimHomepageRequest], + Union[homepage.Homepage, Awaitable[homepage.Homepage]], + ]: raise NotImplementedError() @property @@ -197,6 +205,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'HomepageServiceTransport', -) +__all__ = ("HomepageServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py index 7fc6a4728c81..2d0aa0e8d090 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore -from google.shopping.merchant_accounts_v1.types import homepage from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage -from .base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_accounts_v1.types import homepage + +from .base import DEFAULT_CLIENT_INFO, HomepageServiceTransport 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.accounts.v1.HomepageService", "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.accounts.v1.HomepageService", "rpcName": client_call_details.method, "response": grpc_response, @@ -114,23 +120,26 @@ class HomepageServiceGrpcTransport(HomepageServiceTransport): 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,18 @@ 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 get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - homepage.Homepage]: + def get_homepage( + self, + ) -> Callable[[homepage.GetHomepageRequest], homepage.Homepage]: r"""Return a callable for the get homepage method over gRPC. Retrieves a store's homepage. @@ -326,18 +338,18 @@ def get_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_homepage' not in self._stubs: - self._stubs['get_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/GetHomepage', + if "get_homepage" not in self._stubs: + self._stubs["get_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/GetHomepage", request_serializer=homepage.GetHomepageRequest.serialize, response_deserializer=homepage.Homepage.deserialize, ) - return self._stubs['get_homepage'] + return self._stubs["get_homepage"] @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - gsma_homepage.Homepage]: + def update_homepage( + self, + ) -> Callable[[gsma_homepage.UpdateHomepageRequest], gsma_homepage.Homepage]: r"""Return a callable for the update homepage method over gRPC. Updates a store's homepage. Executing this method @@ -353,18 +365,18 @@ def update_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_homepage' not in self._stubs: - self._stubs['update_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/UpdateHomepage', + if "update_homepage" not in self._stubs: + self._stubs["update_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/UpdateHomepage", request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, response_deserializer=gsma_homepage.Homepage.deserialize, ) - return self._stubs['update_homepage'] + return self._stubs["update_homepage"] @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - homepage.Homepage]: + def claim_homepage( + self, + ) -> Callable[[homepage.ClaimHomepageRequest], homepage.Homepage]: r"""Return a callable for the claim homepage method over gRPC. Claims a store's homepage. Executing this method requires admin @@ -402,18 +414,18 @@ def claim_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'claim_homepage' not in self._stubs: - self._stubs['claim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/ClaimHomepage', + if "claim_homepage" not in self._stubs: + self._stubs["claim_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/ClaimHomepage", request_serializer=homepage.ClaimHomepageRequest.serialize, response_deserializer=homepage.Homepage.deserialize, ) - return self._stubs['claim_homepage'] + return self._stubs["claim_homepage"] @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - homepage.Homepage]: + def unclaim_homepage( + self, + ) -> Callable[[homepage.UnclaimHomepageRequest], homepage.Homepage]: r"""Return a callable for the unclaim homepage method over gRPC. Unclaims a store's homepage. Executing this method @@ -429,13 +441,13 @@ def unclaim_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'unclaim_homepage' not in self._stubs: - self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/UnclaimHomepage', + if "unclaim_homepage" not in self._stubs: + self._stubs["unclaim_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/UnclaimHomepage", request_serializer=homepage.UnclaimHomepageRequest.serialize, response_deserializer=homepage.Homepage.deserialize, ) - return self._stubs['unclaim_homepage'] + return self._stubs["unclaim_homepage"] def close(self): self._logged_channel.close() @@ -445,6 +457,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'HomepageServiceGrpcTransport', -) +__all__ = ("HomepageServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py index aa284e548951..f703fb675a93 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_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.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.shopping.merchant_accounts_v1.types import homepage from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage -from .base import HomepageServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_accounts_v1.types import homepage + +from .base import DEFAULT_CLIENT_INFO, HomepageServiceTransport from .grpc import HomepageServiceGrpcTransport 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.accounts.v1.HomepageService", "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.accounts.v1.HomepageService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -123,13 +131,15 @@ class HomepageServiceGrpcAsyncIOTransport(HomepageServiceTransport): _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,9 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - Awaitable[homepage.Homepage]]: + def get_homepage( + self, + ) -> Callable[[homepage.GetHomepageRequest], Awaitable[homepage.Homepage]]: r"""Return a callable for the get homepage method over gRPC. Retrieves a store's homepage. @@ -332,18 +346,20 @@ def get_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_homepage' not in self._stubs: - self._stubs['get_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/GetHomepage', + if "get_homepage" not in self._stubs: + self._stubs["get_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/GetHomepage", request_serializer=homepage.GetHomepageRequest.serialize, response_deserializer=homepage.Homepage.deserialize, ) - return self._stubs['get_homepage'] + return self._stubs["get_homepage"] @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - Awaitable[gsma_homepage.Homepage]]: + def update_homepage( + self, + ) -> Callable[ + [gsma_homepage.UpdateHomepageRequest], Awaitable[gsma_homepage.Homepage] + ]: r"""Return a callable for the update homepage method over gRPC. Updates a store's homepage. Executing this method @@ -359,18 +375,18 @@ def update_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_homepage' not in self._stubs: - self._stubs['update_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/UpdateHomepage', + if "update_homepage" not in self._stubs: + self._stubs["update_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/UpdateHomepage", request_serializer=gsma_homepage.UpdateHomepageRequest.serialize, response_deserializer=gsma_homepage.Homepage.deserialize, ) - return self._stubs['update_homepage'] + return self._stubs["update_homepage"] @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - Awaitable[homepage.Homepage]]: + def claim_homepage( + self, + ) -> Callable[[homepage.ClaimHomepageRequest], Awaitable[homepage.Homepage]]: r"""Return a callable for the claim homepage method over gRPC. Claims a store's homepage. Executing this method requires admin @@ -408,18 +424,18 @@ def claim_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'claim_homepage' not in self._stubs: - self._stubs['claim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/ClaimHomepage', + if "claim_homepage" not in self._stubs: + self._stubs["claim_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/ClaimHomepage", request_serializer=homepage.ClaimHomepageRequest.serialize, response_deserializer=homepage.Homepage.deserialize, ) - return self._stubs['claim_homepage'] + return self._stubs["claim_homepage"] @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - Awaitable[homepage.Homepage]]: + def unclaim_homepage( + self, + ) -> Callable[[homepage.UnclaimHomepageRequest], Awaitable[homepage.Homepage]]: r"""Return a callable for the unclaim homepage method over gRPC. Unclaims a store's homepage. Executing this method @@ -435,16 +451,16 @@ def unclaim_homepage(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'unclaim_homepage' not in self._stubs: - self._stubs['unclaim_homepage'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.HomepageService/UnclaimHomepage', + if "unclaim_homepage" not in self._stubs: + self._stubs["unclaim_homepage"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.HomepageService/UnclaimHomepage", request_serializer=homepage.UnclaimHomepageRequest.serialize, response_deserializer=homepage.Homepage.deserialize, ) - return self._stubs['unclaim_homepage'] + return self._stubs["unclaim_homepage"] 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.get_homepage: self._wrap_method( self.get_homepage, @@ -481,6 +497,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'HomepageServiceGrpcAsyncIOTransport', -) +__all__ = ("HomepageServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py similarity index 73% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py index ac3d6aafaed9..d89d30ac7039 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_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 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.shopping.merchant_accounts_v1.types import homepage from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from google.shopping.merchant_accounts_v1.types import homepage - -from .rest_base import _BaseHomepageServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseHomepageServiceRestTransport 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 @@ -115,7 +110,12 @@ def post_update_homepage(self, response): """ - def pre_claim_homepage(self, request: homepage.ClaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_claim_homepage( + self, + request: homepage.ClaimHomepageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[homepage.ClaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for claim_homepage Override in a subclass to manipulate the request or metadata @@ -136,7 +136,11 @@ def post_claim_homepage(self, response: homepage.Homepage) -> homepage.Homepage: """ return response - def post_claim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_claim_homepage_with_metadata( + self, + response: homepage.Homepage, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for claim_homepage Override in a subclass to read or manipulate the response or metadata after it @@ -151,7 +155,11 @@ def post_claim_homepage_with_metadata(self, response: homepage.Homepage, metadat """ return response, metadata - def pre_get_homepage(self, request: homepage.GetHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_homepage( + self, + request: homepage.GetHomepageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[homepage.GetHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_homepage Override in a subclass to manipulate the request or metadata @@ -172,7 +180,11 @@ def post_get_homepage(self, response: homepage.Homepage) -> homepage.Homepage: """ return response - def post_get_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_homepage_with_metadata( + self, + response: homepage.Homepage, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_homepage Override in a subclass to read or manipulate the response or metadata after it @@ -187,7 +199,13 @@ def post_get_homepage_with_metadata(self, response: homepage.Homepage, metadata: """ return response, metadata - def pre_unclaim_homepage(self, request: homepage.UnclaimHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.UnclaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_unclaim_homepage( + self, + request: homepage.UnclaimHomepageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + homepage.UnclaimHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for unclaim_homepage Override in a subclass to manipulate the request or metadata @@ -208,7 +226,11 @@ def post_unclaim_homepage(self, response: homepage.Homepage) -> homepage.Homepag """ return response - def post_unclaim_homepage_with_metadata(self, response: homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_unclaim_homepage_with_metadata( + self, + response: homepage.Homepage, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for unclaim_homepage Override in a subclass to read or manipulate the response or metadata after it @@ -223,7 +245,13 @@ def post_unclaim_homepage_with_metadata(self, response: homepage.Homepage, metad """ return response, metadata - def pre_update_homepage(self, request: gsma_homepage.UpdateHomepageRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_homepage( + self, + request: gsma_homepage.UpdateHomepageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gsma_homepage.UpdateHomepageRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for update_homepage Override in a subclass to manipulate the request or metadata @@ -231,7 +259,9 @@ def pre_update_homepage(self, request: gsma_homepage.UpdateHomepageRequest, meta """ return request, metadata - def post_update_homepage(self, response: gsma_homepage.Homepage) -> gsma_homepage.Homepage: + def post_update_homepage( + self, response: gsma_homepage.Homepage + ) -> gsma_homepage.Homepage: """Post-rpc interceptor for update_homepage DEPRECATED. Please use the `post_update_homepage_with_metadata` @@ -244,7 +274,11 @@ def post_update_homepage(self, response: gsma_homepage.Homepage) -> gsma_homepag """ return response - def post_update_homepage_with_metadata(self, response: gsma_homepage.Homepage, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_homepage_with_metadata( + self, + response: gsma_homepage.Homepage, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gsma_homepage.Homepage, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_homepage Override in a subclass to read or manipulate the response or metadata after it @@ -279,20 +313,21 @@ class HomepageServiceRestTransport(_BaseHomepageServiceRestTransport): 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[HomepageServiceRestInterceptor] = 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[HomepageServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -335,16 +370,19 @@ 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 HomepageServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _ClaimHomepage(_BaseHomepageServiceRestTransport._BaseClaimHomepage, HomepageServiceRestStub): + class _ClaimHomepage( + _BaseHomepageServiceRestTransport._BaseClaimHomepage, HomepageServiceRestStub + ): def __hash__(self): return hash("HomepageServiceRestTransport.ClaimHomepage") @@ -356,27 +394,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: homepage.ClaimHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> homepage.Homepage: + def __call__( + self, + request: homepage.ClaimHomepageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Call the claim homepage method over HTTP. Args: @@ -406,32 +446,44 @@ def __call__(self, """ - http_options = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_http_options() + http_options = ( + _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_http_options() + ) request, metadata = self._interceptor.pre_claim_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_transcoded_request(http_options, request) + transcoded_request = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_transcoded_request( + http_options, request + ) - body = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_request_body_json(transcoded_request) + body = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.ClaimHomepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "ClaimHomepage", "httpRequest": http_request, @@ -440,7 +492,15 @@ def __call__(self, ) # Send the request - response = HomepageServiceRestTransport._ClaimHomepage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = HomepageServiceRestTransport._ClaimHomepage._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. @@ -455,20 +515,24 @@ def __call__(self, resp = self._interceptor.post_claim_homepage(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_claim_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_claim_homepage_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = homepage.Homepage.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.accounts_v1.HomepageServiceClient.claim_homepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "ClaimHomepage", "metadata": http_response["headers"], @@ -477,7 +541,9 @@ def __call__(self, ) return resp - class _GetHomepage(_BaseHomepageServiceRestTransport._BaseGetHomepage, HomepageServiceRestStub): + class _GetHomepage( + _BaseHomepageServiceRestTransport._BaseGetHomepage, HomepageServiceRestStub + ): def __hash__(self): return hash("HomepageServiceRestTransport.GetHomepage") @@ -489,26 +555,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: homepage.GetHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> homepage.Homepage: + def __call__( + self, + request: homepage.GetHomepageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Call the get homepage method over HTTP. Args: @@ -538,30 +606,40 @@ def __call__(self, """ - http_options = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_http_options() + http_options = ( + _BaseHomepageServiceRestTransport._BaseGetHomepage._get_http_options() + ) request, metadata = self._interceptor.pre_get_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_transcoded_request(http_options, request) + transcoded_request = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseHomepageServiceRestTransport._BaseGetHomepage._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.GetHomepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "GetHomepage", "httpRequest": http_request, @@ -570,7 +648,14 @@ def __call__(self, ) # Send the request - response = HomepageServiceRestTransport._GetHomepage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = HomepageServiceRestTransport._GetHomepage._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 +670,24 @@ def __call__(self, resp = self._interceptor.post_get_homepage(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_homepage_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = homepage.Homepage.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.accounts_v1.HomepageServiceClient.get_homepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "GetHomepage", "metadata": http_response["headers"], @@ -607,7 +696,9 @@ def __call__(self, ) return resp - class _UnclaimHomepage(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage, HomepageServiceRestStub): + class _UnclaimHomepage( + _BaseHomepageServiceRestTransport._BaseUnclaimHomepage, HomepageServiceRestStub + ): def __hash__(self): return hash("HomepageServiceRestTransport.UnclaimHomepage") @@ -619,27 +710,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: homepage.UnclaimHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> homepage.Homepage: + def __call__( + self, + request: homepage.UnclaimHomepageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> homepage.Homepage: r"""Call the unclaim homepage method over HTTP. Args: @@ -669,32 +762,46 @@ def __call__(self, """ - http_options = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_http_options() + http_options = ( + _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_http_options() + ) - request, metadata = self._interceptor.pre_unclaim_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_unclaim_homepage( + request, metadata + ) + transcoded_request = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_transcoded_request( + http_options, request + ) - body = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_request_body_json(transcoded_request) + body = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.UnclaimHomepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "UnclaimHomepage", "httpRequest": http_request, @@ -703,7 +810,15 @@ def __call__(self, ) # Send the request - response = HomepageServiceRestTransport._UnclaimHomepage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = HomepageServiceRestTransport._UnclaimHomepage._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. @@ -718,20 +833,24 @@ def __call__(self, resp = self._interceptor.post_unclaim_homepage(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_unclaim_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_unclaim_homepage_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = homepage.Homepage.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.accounts_v1.HomepageServiceClient.unclaim_homepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "UnclaimHomepage", "metadata": http_response["headers"], @@ -740,7 +859,9 @@ def __call__(self, ) return resp - class _UpdateHomepage(_BaseHomepageServiceRestTransport._BaseUpdateHomepage, HomepageServiceRestStub): + class _UpdateHomepage( + _BaseHomepageServiceRestTransport._BaseUpdateHomepage, HomepageServiceRestStub + ): def __hash__(self): return hash("HomepageServiceRestTransport.UpdateHomepage") @@ -752,27 +873,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: gsma_homepage.UpdateHomepageRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_homepage.Homepage: + def __call__( + self, + request: gsma_homepage.UpdateHomepageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_homepage.Homepage: r"""Call the update homepage method over HTTP. Args: @@ -802,32 +925,44 @@ def __call__(self, """ - http_options = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_http_options() + http_options = ( + _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_http_options() + ) request, metadata = self._interceptor.pre_update_homepage(request, metadata) - transcoded_request = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_transcoded_request(http_options, request) + transcoded_request = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_transcoded_request( + http_options, request + ) - body = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_request_body_json(transcoded_request) + body = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.HomepageServiceClient.UpdateHomepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "UpdateHomepage", "httpRequest": http_request, @@ -836,7 +971,15 @@ def __call__(self, ) # Send the request - response = HomepageServiceRestTransport._UpdateHomepage._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = HomepageServiceRestTransport._UpdateHomepage._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. @@ -851,20 +994,24 @@ def __call__(self, resp = self._interceptor.post_update_homepage(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_homepage_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_homepage_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = gsma_homepage.Homepage.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.accounts_v1.HomepageServiceClient.update_homepage", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.HomepageService", "rpcName": "UpdateHomepage", "metadata": http_response["headers"], @@ -874,36 +1021,36 @@ def __call__(self, return resp @property - def claim_homepage(self) -> Callable[ - [homepage.ClaimHomepageRequest], - homepage.Homepage]: + def claim_homepage( + self, + ) -> Callable[[homepage.ClaimHomepageRequest], homepage.Homepage]: # 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._ClaimHomepage(self._session, self._host, self._interceptor) # type: ignore + return self._ClaimHomepage(self._session, self._host, self._interceptor) # type: ignore @property - def get_homepage(self) -> Callable[ - [homepage.GetHomepageRequest], - homepage.Homepage]: + def get_homepage( + self, + ) -> Callable[[homepage.GetHomepageRequest], homepage.Homepage]: # 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._GetHomepage(self._session, self._host, self._interceptor) # type: ignore + return self._GetHomepage(self._session, self._host, self._interceptor) # type: ignore @property - def unclaim_homepage(self) -> Callable[ - [homepage.UnclaimHomepageRequest], - homepage.Homepage]: + def unclaim_homepage( + self, + ) -> Callable[[homepage.UnclaimHomepageRequest], homepage.Homepage]: # 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._UnclaimHomepage(self._session, self._host, self._interceptor) # type: ignore + return self._UnclaimHomepage(self._session, self._host, self._interceptor) # type: ignore @property - def update_homepage(self) -> Callable[ - [gsma_homepage.UpdateHomepageRequest], - gsma_homepage.Homepage]: + def update_homepage( + self, + ) -> Callable[[gsma_homepage.UpdateHomepageRequest], gsma_homepage.Homepage]: # 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._UpdateHomepage(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateHomepage(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -913,6 +1060,4 @@ def close(self): self._session.close() -__all__=( - 'HomepageServiceRestTransport', -) +__all__ = ("HomepageServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py index 5dde88abe3b1..3f4343a4c07b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/homepage_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 HomepageServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format -from google.shopping.merchant_accounts_v1.types import homepage from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from google.shopping.merchant_accounts_v1.types import homepage + +from .base import DEFAULT_CLIENT_INFO, HomepageServiceTransport class _BaseHomepageServiceRestTransport(HomepageServiceTransport): @@ -41,14 +39,16 @@ class _BaseHomepageServiceRestTransport(HomepageServiceTransport): 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,27 +85,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseClaimHomepage: 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': '/accounts/v1/{name=accounts/*/homepage}:claim', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/homepage}:claim", + "body": "*", + }, ] return http_options @@ -118,17 +124,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(_BaseHomepageServiceRestTransport._BaseClaimHomepage._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( + _BaseHomepageServiceRestTransport._BaseClaimHomepage._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -137,19 +149,23 @@ class _BaseGetHomepage: 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': '/accounts/v1/{name=accounts/*/homepage}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/homepage}", + }, ] return http_options @@ -161,11 +177,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(_BaseHomepageServiceRestTransport._BaseGetHomepage._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( + _BaseHomepageServiceRestTransport._BaseGetHomepage._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,20 +196,24 @@ class _BaseUnclaimHomepage: 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': '/accounts/v1/{name=accounts/*/homepage}:unclaim', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/homepage}:unclaim", + "body": "*", + }, ] return http_options @@ -202,17 +228,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(_BaseHomepageServiceRestTransport._BaseUnclaimHomepage._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( + _BaseHomepageServiceRestTransport._BaseUnclaimHomepage._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -221,20 +253,24 @@ class _BaseUpdateHomepage: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{homepage.name=accounts/*/homepage}', - 'body': 'homepage', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{homepage.name=accounts/*/homepage}", + "body": "homepage", + }, ] return http_options @@ -249,22 +285,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseHomepageServiceRestTransport._BaseUpdateHomepage._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( + _BaseHomepageServiceRestTransport._BaseUpdateHomepage._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseHomepageServiceRestTransport', -) +__all__ = ("_BaseHomepageServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py index bdfa6c11d195..bdea15e39f87 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import LfpProvidersServiceClient from .async_client import LfpProvidersServiceAsyncClient +from .client import LfpProvidersServiceClient __all__ = ( - 'LfpProvidersServiceClient', - 'LfpProvidersServiceAsyncClient', + "LfpProvidersServiceClient", + "LfpProvidersServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py index d85ddd3eb7f7..e67d125dee33 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,20 +45,24 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import empty_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.lfp_providers_service import pagers from google.shopping.merchant_accounts_v1.types import lfpproviders -from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport + from .client import LfpProvidersServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, LfpProvidersServiceTransport +from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport 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 LfpProvidersServiceAsyncClient: """The service facilitates the management of a merchant's LFP provider settings. This API defines the following resource model: @@ -66,19 +80,39 @@ class LfpProvidersServiceAsyncClient: _DEFAULT_UNIVERSE = LfpProvidersServiceClient._DEFAULT_UNIVERSE lfp_provider_path = staticmethod(LfpProvidersServiceClient.lfp_provider_path) - parse_lfp_provider_path = staticmethod(LfpProvidersServiceClient.parse_lfp_provider_path) - omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.omnichannel_setting_path) - parse_omnichannel_setting_path = staticmethod(LfpProvidersServiceClient.parse_omnichannel_setting_path) - common_billing_account_path = staticmethod(LfpProvidersServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(LfpProvidersServiceClient.parse_common_billing_account_path) + parse_lfp_provider_path = staticmethod( + LfpProvidersServiceClient.parse_lfp_provider_path + ) + omnichannel_setting_path = staticmethod( + LfpProvidersServiceClient.omnichannel_setting_path + ) + parse_omnichannel_setting_path = staticmethod( + LfpProvidersServiceClient.parse_omnichannel_setting_path + ) + common_billing_account_path = staticmethod( + LfpProvidersServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LfpProvidersServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(LfpProvidersServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(LfpProvidersServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(LfpProvidersServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(LfpProvidersServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + LfpProvidersServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + LfpProvidersServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + LfpProvidersServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(LfpProvidersServiceClient.common_project_path) - parse_common_project_path = staticmethod(LfpProvidersServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + LfpProvidersServiceClient.parse_common_project_path + ) common_location_path = staticmethod(LfpProvidersServiceClient.common_location_path) - parse_common_location_path = staticmethod(LfpProvidersServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + LfpProvidersServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -114,7 +148,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: @@ -177,12 +213,20 @@ def universe_domain(self) -> str: get_transport_class = LfpProvidersServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = "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, + LfpProvidersServiceTransport, + Callable[..., LfpProvidersServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the lfp providers service async client. Args: @@ -237,31 +281,39 @@ 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.accounts_v1.LfpProvidersServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", - "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.accounts.v1.LfpProvidersService", "credentialsType": None, - } + }, ) - async def find_lfp_providers(self, - request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersAsyncPager: + async def find_lfp_providers( + self, + request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersAsyncPager: r"""Find the LFP provider candidates in a given country. .. code-block:: python @@ -324,10 +376,14 @@ async def sample_find_lfp_providers(): # - 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. @@ -341,14 +397,14 @@ async def sample_find_lfp_providers(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.find_lfp_providers] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.find_lfp_providers + ] # 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. @@ -376,14 +432,15 @@ async def sample_find_lfp_providers(): # Done; return the response. return response - async def link_lfp_provider(self, - request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpproviders.LinkLfpProviderResponse: + async def link_lfp_provider( + self, + request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: r"""Link the specified merchant to a LFP provider for the specified country. @@ -445,10 +502,14 @@ async def sample_link_lfp_provider(): # - 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. @@ -462,14 +523,14 @@ async def sample_link_lfp_provider(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.link_lfp_provider] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.link_lfp_provider + ] # 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. @@ -492,12 +553,13 @@ async def __aenter__(self) -> "LfpProvidersServiceAsyncClient": 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__ = ( - "LfpProvidersServiceAsyncClient", -) +__all__ = ("LfpProvidersServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py index 329721f9aec6..23c126373f63 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,9 +62,11 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import empty_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.lfp_providers_service import pagers from google.shopping.merchant_accounts_v1.types import lfpproviders -from .transports.base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, LfpProvidersServiceTransport from .transports.grpc import LfpProvidersServiceGrpcTransport from .transports.grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport from .transports.rest import LfpProvidersServiceRestTransport @@ -64,14 +79,18 @@ class LfpProvidersServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[LfpProvidersServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[LfpProvidersServiceTransport]] _transport_registry["grpc"] = LfpProvidersServiceGrpcTransport _transport_registry["grpc_asyncio"] = LfpProvidersServiceGrpcAsyncIOTransport _transport_registry["rest"] = LfpProvidersServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[LfpProvidersServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[LfpProvidersServiceTransport]: """Returns an appropriate transport class. Args: @@ -167,8 +186,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: LfpProvidersServiceClient: 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) @@ -185,84 +203,128 @@ def transport(self) -> LfpProvidersServiceTransport: return self._transport @staticmethod - def lfp_provider_path(account: str,omnichannel_setting: str,lfp_provider: str,) -> str: + def lfp_provider_path( + account: str, + omnichannel_setting: str, + lfp_provider: str, + ) -> str: """Returns a fully-qualified lfp_provider string.""" - return "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format( + account=account, + omnichannel_setting=omnichannel_setting, + lfp_provider=lfp_provider, + ) @staticmethod - def parse_lfp_provider_path(path: str) -> Dict[str,str]: + def parse_lfp_provider_path(path: str) -> Dict[str, str]: """Parses a lfp_provider path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)/lfpProviders/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)/lfpProviders/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: + def omnichannel_setting_path( + account: str, + omnichannel_setting: str, + ) -> str: """Returns a fully-qualified omnichannel_setting string.""" - return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format( + account=account, + omnichannel_setting=omnichannel_setting, + ) @staticmethod - def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: + def parse_omnichannel_setting_path(path: str) -> Dict[str, str]: """Parses a omnichannel_setting path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/omnichannelSettings/(?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: @@ -294,16 +356,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 @@ -316,7 +384,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 @@ -337,13 +407,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 @@ -366,7 +442,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: @@ -382,17 +460,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = LfpProvidersServiceClient._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 = LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = LfpProvidersServiceClient._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: @@ -428,15 +514,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 @@ -469,12 +558,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, LfpProvidersServiceTransport, Callable[..., LfpProvidersServiceTransport]]] = 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, + LfpProvidersServiceTransport, + Callable[..., LfpProvidersServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the lfp providers service client. Args: @@ -529,14 +626,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 = LfpProvidersServiceClient._read_environment_variables() - self._client_cert_source = LfpProvidersServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = LfpProvidersServiceClient._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, + ) = LfpProvidersServiceClient._read_environment_variables() + self._client_cert_source = LfpProvidersServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = LfpProvidersServiceClient._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 @@ -547,7 +654,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 @@ -556,8 +665,10 @@ def __init__(self, *, if transport_provided: # transport is a LfpProvidersServiceTransport 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 " @@ -566,20 +677,30 @@ def __init__(self, *, self._transport = cast(LfpProvidersServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - LfpProvidersServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or LfpProvidersServiceClient._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[LfpProvidersServiceTransport], Callable[..., LfpProvidersServiceTransport]] = ( + transport_init: Union[ + Type[LfpProvidersServiceTransport], + Callable[..., LfpProvidersServiceTransport], + ] = ( LfpProvidersServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., LfpProvidersServiceTransport], transport) @@ -598,28 +719,37 @@ 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.accounts_v1.LfpProvidersServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", - "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.accounts.v1.LfpProvidersService", "credentialsType": None, - } + }, ) - def find_lfp_providers(self, - request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersPager: + def find_lfp_providers( + self, + request: Optional[Union[lfpproviders.FindLfpProvidersRequest, 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.FindLfpProvidersPager: r"""Find the LFP provider candidates in a given country. .. code-block:: python @@ -682,10 +812,14 @@ def sample_find_lfp_providers(): # - 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. @@ -703,9 +837,7 @@ def sample_find_lfp_providers(): # 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. @@ -733,14 +865,15 @@ def sample_find_lfp_providers(): # Done; return the response. return response - def link_lfp_provider(self, - request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> lfpproviders.LinkLfpProviderResponse: + def link_lfp_provider( + self, + request: Optional[Union[lfpproviders.LinkLfpProviderRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: r"""Link the specified merchant to a LFP provider for the specified country. @@ -802,10 +935,14 @@ def sample_link_lfp_provider(): # - 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. @@ -823,9 +960,7 @@ def sample_link_lfp_provider(): # 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. @@ -856,16 +991,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__ = ( - "LfpProvidersServiceClient", -) +__all__ = ("LfpProvidersServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py index 53a009bf4800..ff918f413fa2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_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 FindLfpProvidersPager: 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[..., lfpproviders.FindLfpProvidersResponse], - request: lfpproviders.FindLfpProvidersRequest, - response: lfpproviders.FindLfpProvidersResponse, - *, - 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[..., lfpproviders.FindLfpProvidersResponse], + request: lfpproviders.FindLfpProvidersRequest, + response: lfpproviders.FindLfpProvidersResponse, + *, + 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[lfpproviders.FindLfpProvidersResponse]: 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[lfpproviders.LfpProvider]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[lfpproviders.LfpProvider]: yield from page.lfp_providers 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 FindLfpProvidersAsyncPager: @@ -112,14 +134,17 @@ class FindLfpProvidersAsyncPager: 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[lfpproviders.FindLfpProvidersResponse]], - request: lfpproviders.FindLfpProvidersRequest, - response: lfpproviders.FindLfpProvidersResponse, - *, - 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[lfpproviders.FindLfpProvidersResponse]], + request: lfpproviders.FindLfpProvidersRequest, + response: lfpproviders.FindLfpProvidersResponse, + *, + 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[lfpproviders.FindLfpProvidersResponse]: 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[lfpproviders.LfpProvider]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py index f6510b1f8477..8aa5bb8a032a 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/lfp_providers_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/__init__.py @@ -19,20 +19,20 @@ from .base import LfpProvidersServiceTransport from .grpc import LfpProvidersServiceGrpcTransport from .grpc_asyncio import LfpProvidersServiceGrpcAsyncIOTransport -from .rest import LfpProvidersServiceRestTransport -from .rest import LfpProvidersServiceRestInterceptor - +from .rest import LfpProvidersServiceRestInterceptor, LfpProvidersServiceRestTransport # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[LfpProvidersServiceTransport]] -_transport_registry['grpc'] = LfpProvidersServiceGrpcTransport -_transport_registry['grpc_asyncio'] = LfpProvidersServiceGrpcAsyncIOTransport -_transport_registry['rest'] = LfpProvidersServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[LfpProvidersServiceTransport]] +_transport_registry["grpc"] = LfpProvidersServiceGrpcTransport +_transport_registry["grpc_asyncio"] = LfpProvidersServiceGrpcAsyncIOTransport +_transport_registry["rest"] = LfpProvidersServiceRestTransport __all__ = ( - 'LfpProvidersServiceTransport', - 'LfpProvidersServiceGrpcTransport', - 'LfpProvidersServiceGrpcAsyncIOTransport', - 'LfpProvidersServiceRestTransport', - 'LfpProvidersServiceRestInterceptor', + "LfpProvidersServiceTransport", + "LfpProvidersServiceGrpcTransport", + "LfpProvidersServiceGrpcAsyncIOTransport", + "LfpProvidersServiceRestTransport", + "LfpProvidersServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py index c4a1d5c5a99f..fe5793334c14 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import lfpproviders -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__ @@ -38,24 +39,23 @@ class LfpProvidersServiceTransport(abc.ABC): """Abstract transport class for LfpProvidersService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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 find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - Union[ - lfpproviders.FindLfpProvidersResponse, - Awaitable[lfpproviders.FindLfpProvidersResponse] - ]]: + def find_lfp_providers( + self, + ) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + Union[ + lfpproviders.FindLfpProvidersResponse, + Awaitable[lfpproviders.FindLfpProvidersResponse], + ], + ]: raise NotImplementedError() @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - Union[ - lfpproviders.LinkLfpProviderResponse, - Awaitable[lfpproviders.LinkLfpProviderResponse] - ]]: + def link_lfp_provider( + self, + ) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + Union[ + lfpproviders.LinkLfpProviderResponse, + Awaitable[lfpproviders.LinkLfpProviderResponse], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'LfpProvidersServiceTransport', -) +__all__ = ("LfpProvidersServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py index b2712bf438f7..275aaf7a41a3 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import lfpproviders -from .base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LfpProvidersServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": client_call_details.method, "response": grpc_response, @@ -116,23 +122,26 @@ class LfpProvidersServiceGrpcTransport(LfpProvidersServiceTransport): 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: @@ -254,19 +263,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. @@ -301,19 +314,20 @@ 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 find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - lfpproviders.FindLfpProvidersResponse]: + def find_lfp_providers( + self, + ) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], lfpproviders.FindLfpProvidersResponse + ]: r"""Return a callable for the find lfp providers method over gRPC. Find the LFP provider candidates in a given country. @@ -328,18 +342,20 @@ def find_lfp_providers(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'find_lfp_providers' not in self._stubs: - self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.LfpProvidersService/FindLfpProviders', + if "find_lfp_providers" not in self._stubs: + self._stubs["find_lfp_providers"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.LfpProvidersService/FindLfpProviders", request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, ) - return self._stubs['find_lfp_providers'] + return self._stubs["find_lfp_providers"] @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - lfpproviders.LinkLfpProviderResponse]: + def link_lfp_provider( + self, + ) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], lfpproviders.LinkLfpProviderResponse + ]: r"""Return a callable for the link lfp provider method over gRPC. Link the specified merchant to a LFP provider for the @@ -355,13 +371,13 @@ def link_lfp_provider(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'link_lfp_provider' not in self._stubs: - self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.LfpProvidersService/LinkLfpProvider', + if "link_lfp_provider" not in self._stubs: + self._stubs["link_lfp_provider"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.LfpProvidersService/LinkLfpProvider", request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, ) - return self._stubs['link_lfp_provider'] + return self._stubs["link_lfp_provider"] def close(self): self._logged_channel.close() @@ -371,6 +387,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'LfpProvidersServiceGrpcTransport', -) +__all__ = ("LfpProvidersServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py index a6c7f3a46da0..c95373d7c3ef 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import lfpproviders -from .base import LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, LfpProvidersServiceTransport from .grpc import LfpProvidersServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -125,13 +133,15 @@ class LfpProvidersServiceGrpcAsyncIOTransport(LfpProvidersServiceTransport): _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. @@ -161,24 +171,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: @@ -302,7 +314,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) @@ -317,9 +331,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - Awaitable[lfpproviders.FindLfpProvidersResponse]]: + def find_lfp_providers( + self, + ) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], + Awaitable[lfpproviders.FindLfpProvidersResponse], + ]: r"""Return a callable for the find lfp providers method over gRPC. Find the LFP provider candidates in a given country. @@ -334,18 +351,21 @@ def find_lfp_providers(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'find_lfp_providers' not in self._stubs: - self._stubs['find_lfp_providers'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.LfpProvidersService/FindLfpProviders', + if "find_lfp_providers" not in self._stubs: + self._stubs["find_lfp_providers"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.LfpProvidersService/FindLfpProviders", request_serializer=lfpproviders.FindLfpProvidersRequest.serialize, response_deserializer=lfpproviders.FindLfpProvidersResponse.deserialize, ) - return self._stubs['find_lfp_providers'] + return self._stubs["find_lfp_providers"] @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - Awaitable[lfpproviders.LinkLfpProviderResponse]]: + def link_lfp_provider( + self, + ) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], + Awaitable[lfpproviders.LinkLfpProviderResponse], + ]: r"""Return a callable for the link lfp provider method over gRPC. Link the specified merchant to a LFP provider for the @@ -361,16 +381,16 @@ def link_lfp_provider(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'link_lfp_provider' not in self._stubs: - self._stubs['link_lfp_provider'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.LfpProvidersService/LinkLfpProvider', + if "link_lfp_provider" not in self._stubs: + self._stubs["link_lfp_provider"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.LfpProvidersService/LinkLfpProvider", request_serializer=lfpproviders.LinkLfpProviderRequest.serialize, response_deserializer=lfpproviders.LinkLfpProviderResponse.deserialize, ) - return self._stubs['link_lfp_provider'] + return self._stubs["link_lfp_provider"] 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.find_lfp_providers: self._wrap_method( self.find_lfp_providers, @@ -397,6 +417,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'LfpProvidersServiceGrpcAsyncIOTransport', -) +__all__ = ("LfpProvidersServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py index 57d1bb8ac958..2d978f9df2d7 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import lfpproviders - -from .rest_base import _BaseLfpProvidersServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseLfpProvidersServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,14 @@ def post_link_lfp_provider(self, response): """ - def pre_find_lfp_providers(self, request: lfpproviders.FindLfpProvidersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_find_lfp_providers( + self, + request: lfpproviders.FindLfpProvidersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + lfpproviders.FindLfpProvidersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for find_lfp_providers Override in a subclass to manipulate the request or metadata @@ -106,7 +108,9 @@ def pre_find_lfp_providers(self, request: lfpproviders.FindLfpProvidersRequest, """ return request, metadata - def post_find_lfp_providers(self, response: lfpproviders.FindLfpProvidersResponse) -> lfpproviders.FindLfpProvidersResponse: + def post_find_lfp_providers( + self, response: lfpproviders.FindLfpProvidersResponse + ) -> lfpproviders.FindLfpProvidersResponse: """Post-rpc interceptor for find_lfp_providers DEPRECATED. Please use the `post_find_lfp_providers_with_metadata` @@ -119,7 +123,13 @@ def post_find_lfp_providers(self, response: lfpproviders.FindLfpProvidersRespons """ return response - def post_find_lfp_providers_with_metadata(self, response: lfpproviders.FindLfpProvidersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.FindLfpProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_find_lfp_providers_with_metadata( + self, + response: lfpproviders.FindLfpProvidersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + lfpproviders.FindLfpProvidersResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for find_lfp_providers Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +144,13 @@ def post_find_lfp_providers_with_metadata(self, response: lfpproviders.FindLfpPr """ return response, metadata - def pre_link_lfp_provider(self, request: lfpproviders.LinkLfpProviderRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_link_lfp_provider( + self, + request: lfpproviders.LinkLfpProviderRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + lfpproviders.LinkLfpProviderRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for link_lfp_provider Override in a subclass to manipulate the request or metadata @@ -142,7 +158,9 @@ def pre_link_lfp_provider(self, request: lfpproviders.LinkLfpProviderRequest, me """ return request, metadata - def post_link_lfp_provider(self, response: lfpproviders.LinkLfpProviderResponse) -> lfpproviders.LinkLfpProviderResponse: + def post_link_lfp_provider( + self, response: lfpproviders.LinkLfpProviderResponse + ) -> lfpproviders.LinkLfpProviderResponse: """Post-rpc interceptor for link_lfp_provider DEPRECATED. Please use the `post_link_lfp_provider_with_metadata` @@ -155,7 +173,13 @@ def post_link_lfp_provider(self, response: lfpproviders.LinkLfpProviderResponse) """ return response - def post_link_lfp_provider_with_metadata(self, response: lfpproviders.LinkLfpProviderResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[lfpproviders.LinkLfpProviderResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_link_lfp_provider_with_metadata( + self, + response: lfpproviders.LinkLfpProviderResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + lfpproviders.LinkLfpProviderResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for link_lfp_provider Override in a subclass to read or manipulate the response or metadata after it @@ -193,20 +217,21 @@ class LfpProvidersServiceRestTransport(_BaseLfpProvidersServiceRestTransport): 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[LfpProvidersServiceRestInterceptor] = 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[LfpProvidersServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -249,16 +274,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 LfpProvidersServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _FindLfpProviders(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders, LfpProvidersServiceRestStub): + class _FindLfpProviders( + _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders, + LfpProvidersServiceRestStub, + ): def __hash__(self): return hash("LfpProvidersServiceRestTransport.FindLfpProviders") @@ -270,26 +299,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: lfpproviders.FindLfpProvidersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpproviders.FindLfpProvidersResponse: + def __call__( + self, + request: lfpproviders.FindLfpProvidersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.FindLfpProvidersResponse: r"""Call the find lfp providers method over HTTP. Args: @@ -311,30 +342,42 @@ def __call__(self, """ - http_options = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_http_options() + http_options = ( + _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_http_options() + ) - request, metadata = self._interceptor.pre_find_lfp_providers(request, metadata) - transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_find_lfp_providers( + request, metadata + ) + transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.LfpProvidersServiceClient.FindLfpProviders", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": "FindLfpProviders", "httpRequest": http_request, @@ -343,7 +386,14 @@ def __call__(self, ) # Send the request - response = LfpProvidersServiceRestTransport._FindLfpProviders._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = LfpProvidersServiceRestTransport._FindLfpProviders._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -358,20 +408,26 @@ def __call__(self, resp = self._interceptor.post_find_lfp_providers(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_find_lfp_providers_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_find_lfp_providers_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = lfpproviders.FindLfpProvidersResponse.to_json(response) + response_payload = lfpproviders.FindLfpProvidersResponse.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.accounts_v1.LfpProvidersServiceClient.find_lfp_providers", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": "FindLfpProviders", "metadata": http_response["headers"], @@ -380,7 +436,10 @@ def __call__(self, ) return resp - class _LinkLfpProvider(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider, LfpProvidersServiceRestStub): + class _LinkLfpProvider( + _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider, + LfpProvidersServiceRestStub, + ): def __hash__(self): return hash("LfpProvidersServiceRestTransport.LinkLfpProvider") @@ -392,27 +451,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: lfpproviders.LinkLfpProviderRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> lfpproviders.LinkLfpProviderResponse: + def __call__( + self, + request: lfpproviders.LinkLfpProviderRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> lfpproviders.LinkLfpProviderResponse: r"""Call the link lfp provider method over HTTP. Args: @@ -434,32 +495,46 @@ def __call__(self, """ - http_options = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_http_options() + http_options = ( + _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_http_options() + ) - request, metadata = self._interceptor.pre_link_lfp_provider(request, metadata) - transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_link_lfp_provider( + request, metadata + ) + transcoded_request = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_transcoded_request( + http_options, request + ) - body = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_request_body_json(transcoded_request) + body = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.LfpProvidersServiceClient.LinkLfpProvider", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": "LinkLfpProvider", "httpRequest": http_request, @@ -468,7 +543,15 @@ def __call__(self, ) # Send the request - response = LfpProvidersServiceRestTransport._LinkLfpProvider._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = LfpProvidersServiceRestTransport._LinkLfpProvider._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. @@ -483,20 +566,26 @@ def __call__(self, resp = self._interceptor.post_link_lfp_provider(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_link_lfp_provider_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_link_lfp_provider_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = lfpproviders.LinkLfpProviderResponse.to_json(response) + response_payload = lfpproviders.LinkLfpProviderResponse.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.accounts_v1.LfpProvidersServiceClient.link_lfp_provider", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.LfpProvidersService", "rpcName": "LinkLfpProvider", "metadata": http_response["headers"], @@ -506,20 +595,24 @@ def __call__(self, return resp @property - def find_lfp_providers(self) -> Callable[ - [lfpproviders.FindLfpProvidersRequest], - lfpproviders.FindLfpProvidersResponse]: + def find_lfp_providers( + self, + ) -> Callable[ + [lfpproviders.FindLfpProvidersRequest], lfpproviders.FindLfpProvidersResponse + ]: # 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._FindLfpProviders(self._session, self._host, self._interceptor) # type: ignore + return self._FindLfpProviders(self._session, self._host, self._interceptor) # type: ignore @property - def link_lfp_provider(self) -> Callable[ - [lfpproviders.LinkLfpProviderRequest], - lfpproviders.LinkLfpProviderResponse]: + def link_lfp_provider( + self, + ) -> Callable[ + [lfpproviders.LinkLfpProviderRequest], lfpproviders.LinkLfpProviderResponse + ]: # 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._LinkLfpProvider(self._session, self._host, self._interceptor) # type: ignore + return self._LinkLfpProvider(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -529,6 +622,4 @@ def close(self): self._session.close() -__all__=( - 'LfpProvidersServiceRestTransport', -) +__all__ = ("LfpProvidersServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py similarity index 64% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py index ad33e0ffb372..be841c81e205 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/lfp_providers_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 LfpProvidersServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import lfpproviders +from .base import DEFAULT_CLIENT_INFO, LfpProvidersServiceTransport + class _BaseLfpProvidersServiceRestTransport(LfpProvidersServiceTransport): """Base REST backend transport for LfpProvidersService. @@ -40,14 +38,16 @@ class _BaseLfpProvidersServiceRestTransport(LfpProvidersServiceTransport): 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseFindLfpProviders: 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': '/accounts/v1/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find", + }, ] return http_options @@ -113,11 +119,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(_BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._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( + _BaseLfpProvidersServiceRestTransport._BaseFindLfpProviders._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,20 +138,24 @@ class _BaseLinkLfpProvider: 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': '/accounts/v1/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider", + "body": "*", + }, ] return http_options @@ -154,22 +170,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._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( + _BaseLfpProvidersServiceRestTransport._BaseLinkLfpProvider._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseLfpProvidersServiceRestTransport', -) +__all__ = ("_BaseLfpProvidersServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py index 242598846a6e..eb6359dbd512 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import OmnichannelSettingsServiceClient from .async_client import OmnichannelSettingsServiceAsyncClient +from .client import OmnichannelSettingsServiceClient __all__ = ( - 'OmnichannelSettingsServiceClient', - 'OmnichannelSettingsServiceAsyncClient', + "OmnichannelSettingsServiceClient", + "OmnichannelSettingsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py index f321a178bbe4..5d6d9a6677cd 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,28 +45,32 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import pagers + +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import ( + pagers, +) from google.shopping.merchant_accounts_v1.types import omnichannelsettings -from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport + from .client import OmnichannelSettingsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, OmnichannelSettingsServiceTransport +from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport 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 OmnichannelSettingsServiceAsyncClient: """The service facilitates the management of a merchant's omnichannel settings. This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] """ _client: OmnichannelSettingsServiceClient @@ -65,23 +79,51 @@ class OmnichannelSettingsServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE account_path = staticmethod(OmnichannelSettingsServiceClient.account_path) - parse_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_account_path) - omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.omnichannel_setting_path) - parse_omnichannel_setting_path = staticmethod(OmnichannelSettingsServiceClient.parse_omnichannel_setting_path) - common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OmnichannelSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OmnichannelSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OmnichannelSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(OmnichannelSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(OmnichannelSettingsServiceClient.parse_common_location_path) + parse_account_path = staticmethod( + OmnichannelSettingsServiceClient.parse_account_path + ) + omnichannel_setting_path = staticmethod( + OmnichannelSettingsServiceClient.omnichannel_setting_path + ) + parse_omnichannel_setting_path = staticmethod( + OmnichannelSettingsServiceClient.parse_omnichannel_setting_path + ) + common_billing_account_path = staticmethod( + OmnichannelSettingsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + OmnichannelSettingsServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + OmnichannelSettingsServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + OmnichannelSettingsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + OmnichannelSettingsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + OmnichannelSettingsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + OmnichannelSettingsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + OmnichannelSettingsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + OmnichannelSettingsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + OmnichannelSettingsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -117,7 +159,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: @@ -180,12 +224,20 @@ def universe_domain(self) -> str: get_transport_class = OmnichannelSettingsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = "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, + OmnichannelSettingsServiceTransport, + Callable[..., OmnichannelSettingsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the omnichannel settings service async client. Args: @@ -240,31 +292,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.accounts_v1.OmnichannelSettingsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", - "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.accounts.v1.OmnichannelSettingsService", "credentialsType": None, - } + }, ) - async def get_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: + async def get_omnichannel_setting( + self, + request: Optional[ + Union[omnichannelsettings.GetOmnichannelSettingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Get the omnichannel settings for a given merchant. .. code-block:: python @@ -323,10 +385,14 @@ async def sample_get_omnichannel_setting(): # - 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. @@ -340,14 +406,14 @@ async def sample_get_omnichannel_setting(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_omnichannel_setting] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_omnichannel_setting + ] # 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. @@ -364,14 +430,17 @@ async def sample_get_omnichannel_setting(): # Done; return the response. return response - async def list_omnichannel_settings(self, - request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsAsyncPager: + async def list_omnichannel_settings( + self, + request: Optional[ + Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsAsyncPager: r"""List all the omnichannel settings for a given merchant. @@ -434,10 +503,14 @@ async def sample_list_omnichannel_settings(): # - 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. @@ -451,14 +524,14 @@ async def sample_list_omnichannel_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_omnichannel_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_omnichannel_settings + ] # 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. @@ -486,15 +559,18 @@ async def sample_list_omnichannel_settings(): # Done; return the response. return response - async def create_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, - *, - parent: Optional[str] = None, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: + async def create_omnichannel_setting( + self, + request: Optional[ + Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Create the omnichannel settings for a given merchant. .. code-block:: python @@ -564,10 +640,14 @@ async def sample_create_omnichannel_setting(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, omnichannel_setting] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -583,14 +663,14 @@ async def sample_create_omnichannel_setting(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_omnichannel_setting] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_omnichannel_setting + ] # 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. @@ -607,15 +687,18 @@ async def sample_create_omnichannel_setting(): # Done; return the response. return response - async def update_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, - *, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: + async def update_omnichannel_setting( + self, + request: Optional[ + Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict] + ] = None, + *, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Update the omnichannel setting for a given merchant in a given country. @@ -698,10 +781,14 @@ async def sample_update_omnichannel_setting(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [omnichannel_setting, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -717,14 +804,16 @@ async def sample_update_omnichannel_setting(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_omnichannel_setting] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_omnichannel_setting + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("omnichannel_setting.name", request.omnichannel_setting.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("omnichannel_setting.name", request.omnichannel_setting.name),) + ), ) # Validate the universe domain. @@ -741,14 +830,17 @@ async def sample_update_omnichannel_setting(): # Done; return the response. return response - async def request_inventory_verification(self, - request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.RequestInventoryVerificationResponse: + async def request_inventory_verification( + self, + request: Optional[ + Union[omnichannelsettings.RequestInventoryVerificationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: r"""Requests inventory verification for a given merchant in a given country. @@ -808,14 +900,20 @@ async def sample_request_inventory_verification(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, omnichannelsettings.RequestInventoryVerificationRequest): + if not isinstance( + request, omnichannelsettings.RequestInventoryVerificationRequest + ): request = omnichannelsettings.RequestInventoryVerificationRequest(request) # If we have keyword arguments corresponding to fields on the @@ -825,14 +923,14 @@ async def sample_request_inventory_verification(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.request_inventory_verification] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.request_inventory_verification + ] # 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. @@ -855,12 +953,13 @@ async def __aenter__(self) -> "OmnichannelSettingsServiceAsyncClient": 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__ = ( - "OmnichannelSettingsServiceAsyncClient", -) +__all__ = ("OmnichannelSettingsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py index 08b5ee2eb384..ca995045e82d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,9 +62,13 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import pagers + +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import ( + pagers, +) from google.shopping.merchant_accounts_v1.types import omnichannelsettings -from .transports.base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, OmnichannelSettingsServiceTransport from .transports.grpc import OmnichannelSettingsServiceGrpcTransport from .transports.grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport from .transports.rest import OmnichannelSettingsServiceRestTransport @@ -64,14 +81,18 @@ class OmnichannelSettingsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] _transport_registry["grpc"] = OmnichannelSettingsServiceGrpcTransport _transport_registry["grpc_asyncio"] = OmnichannelSettingsServiceGrpcAsyncIOTransport _transport_registry["rest"] = OmnichannelSettingsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[OmnichannelSettingsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[OmnichannelSettingsServiceTransport]: """Returns an appropriate transport class. Args: @@ -95,9 +116,7 @@ class OmnichannelSettingsServiceClient(metaclass=OmnichannelSettingsServiceClien settings. This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] """ @staticmethod @@ -170,8 +189,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: OmnichannelSettingsServiceClient: 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) @@ -188,84 +206,121 @@ def transport(self) -> OmnichannelSettingsServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def omnichannel_setting_path(account: str,omnichannel_setting: str,) -> str: + def omnichannel_setting_path( + account: str, + omnichannel_setting: str, + ) -> str: """Returns a fully-qualified omnichannel_setting string.""" - return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) + return "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format( + account=account, + omnichannel_setting=omnichannel_setting, + ) @staticmethod - def parse_omnichannel_setting_path(path: str) -> Dict[str,str]: + def parse_omnichannel_setting_path(path: str) -> Dict[str, str]: """Parses a omnichannel_setting path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/omnichannelSettings/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/omnichannelSettings/(?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: @@ -297,16 +352,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 @@ -319,7 +380,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 @@ -340,13 +403,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 @@ -369,7 +438,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: @@ -385,17 +456,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 = OmnichannelSettingsServiceClient._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 = OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + OmnichannelSettingsServiceClient._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: @@ -431,15 +512,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 @@ -472,12 +556,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OmnichannelSettingsServiceTransport, Callable[..., OmnichannelSettingsServiceTransport]]] = 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, + OmnichannelSettingsServiceTransport, + Callable[..., OmnichannelSettingsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the omnichannel settings service client. Args: @@ -532,14 +624,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 = OmnichannelSettingsServiceClient._read_environment_variables() - self._client_cert_source = OmnichannelSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = OmnichannelSettingsServiceClient._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, + ) = OmnichannelSettingsServiceClient._read_environment_variables() + self._client_cert_source = ( + OmnichannelSettingsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = OmnichannelSettingsServiceClient._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 @@ -550,7 +654,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 @@ -559,8 +665,10 @@ def __init__(self, *, if transport_provided: # transport is a OmnichannelSettingsServiceTransport 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 " @@ -569,20 +677,30 @@ def __init__(self, *, self._transport = cast(OmnichannelSettingsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - OmnichannelSettingsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or OmnichannelSettingsServiceClient._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[OmnichannelSettingsServiceTransport], Callable[..., OmnichannelSettingsServiceTransport]] = ( + transport_init: Union[ + Type[OmnichannelSettingsServiceTransport], + Callable[..., OmnichannelSettingsServiceTransport], + ] = ( OmnichannelSettingsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., OmnichannelSettingsServiceTransport], transport) @@ -601,28 +719,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.accounts_v1.OmnichannelSettingsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", - "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.accounts.v1.OmnichannelSettingsService", "credentialsType": None, - } + }, ) - def get_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.GetOmnichannelSettingRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: + def get_omnichannel_setting( + self, + request: Optional[ + Union[omnichannelsettings.GetOmnichannelSettingRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Get the omnichannel settings for a given merchant. .. code-block:: python @@ -681,10 +810,14 @@ def sample_get_omnichannel_setting(): # - 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. @@ -702,9 +835,7 @@ def sample_get_omnichannel_setting(): # 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. @@ -721,14 +852,17 @@ def sample_get_omnichannel_setting(): # Done; return the response. return response - def list_omnichannel_settings(self, - request: Optional[Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsPager: + def list_omnichannel_settings( + self, + request: Optional[ + Union[omnichannelsettings.ListOmnichannelSettingsRequest, 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.ListOmnichannelSettingsPager: r"""List all the omnichannel settings for a given merchant. @@ -791,10 +925,14 @@ def sample_list_omnichannel_settings(): # - 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. @@ -807,14 +945,14 @@ def sample_list_omnichannel_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_omnichannel_settings] + rpc = self._transport._wrapped_methods[ + self._transport.list_omnichannel_settings + ] # 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. @@ -842,15 +980,18 @@ def sample_list_omnichannel_settings(): # Done; return the response. return response - def create_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict]] = None, - *, - parent: Optional[str] = None, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: + def create_omnichannel_setting( + self, + request: Optional[ + Union[omnichannelsettings.CreateOmnichannelSettingRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Create the omnichannel settings for a given merchant. .. code-block:: python @@ -920,10 +1061,14 @@ def sample_create_omnichannel_setting(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, omnichannel_setting] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -938,14 +1083,14 @@ def sample_create_omnichannel_setting(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_omnichannel_setting] + rpc = self._transport._wrapped_methods[ + self._transport.create_omnichannel_setting + ] # 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. @@ -962,15 +1107,18 @@ def sample_create_omnichannel_setting(): # Done; return the response. return response - def update_omnichannel_setting(self, - request: Optional[Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict]] = None, - *, - omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.OmnichannelSetting: + def update_omnichannel_setting( + self, + request: Optional[ + Union[omnichannelsettings.UpdateOmnichannelSettingRequest, dict] + ] = None, + *, + omnichannel_setting: Optional[omnichannelsettings.OmnichannelSetting] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Update the omnichannel setting for a given merchant in a given country. @@ -1053,10 +1201,14 @@ def sample_update_omnichannel_setting(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [omnichannel_setting, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1071,14 +1223,16 @@ def sample_update_omnichannel_setting(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_omnichannel_setting] + rpc = self._transport._wrapped_methods[ + self._transport.update_omnichannel_setting + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("omnichannel_setting.name", request.omnichannel_setting.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("omnichannel_setting.name", request.omnichannel_setting.name),) + ), ) # Validate the universe domain. @@ -1095,14 +1249,17 @@ def sample_update_omnichannel_setting(): # Done; return the response. return response - def request_inventory_verification(self, - request: Optional[Union[omnichannelsettings.RequestInventoryVerificationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> omnichannelsettings.RequestInventoryVerificationResponse: + def request_inventory_verification( + self, + request: Optional[ + Union[omnichannelsettings.RequestInventoryVerificationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: r"""Requests inventory verification for a given merchant in a given country. @@ -1162,14 +1319,20 @@ def sample_request_inventory_verification(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, omnichannelsettings.RequestInventoryVerificationRequest): + if not isinstance( + request, omnichannelsettings.RequestInventoryVerificationRequest + ): request = omnichannelsettings.RequestInventoryVerificationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1178,14 +1341,14 @@ def sample_request_inventory_verification(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.request_inventory_verification] + rpc = self._transport._wrapped_methods[ + self._transport.request_inventory_verification + ] # 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. @@ -1216,16 +1379,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__ = ( - "OmnichannelSettingsServiceClient", -) +__all__ = ("OmnichannelSettingsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py index 3119bb94204c..5d517204f86c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_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 ListOmnichannelSettingsPager: 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[..., omnichannelsettings.ListOmnichannelSettingsResponse], - request: omnichannelsettings.ListOmnichannelSettingsRequest, - response: omnichannelsettings.ListOmnichannelSettingsResponse, - *, - 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[..., omnichannelsettings.ListOmnichannelSettingsResponse], + request: omnichannelsettings.ListOmnichannelSettingsRequest, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + *, + 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[omnichannelsettings.ListOmnichannelSettingsResponse] 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[omnichannelsettings.OmnichannelSetting]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[omnichannelsettings.OmnichannelSetting]: yield from page.omnichannel_settings 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 ListOmnichannelSettingsAsyncPager: @@ -112,14 +134,19 @@ class ListOmnichannelSettingsAsyncPager: 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[omnichannelsettings.ListOmnichannelSettingsResponse]], - request: omnichannelsettings.ListOmnichannelSettingsRequest, - response: omnichannelsettings.ListOmnichannelSettingsResponse, - *, - 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[omnichannelsettings.ListOmnichannelSettingsResponse] + ], + request: omnichannelsettings.ListOmnichannelSettingsRequest, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + *, + 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[omnichannelsettings.ListOmnichannelSettingsResponse]: + async def pages( + self, + ) -> AsyncIterator[omnichannelsettings.ListOmnichannelSettingsResponse]: 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[omnichannelsettings.OmnichannelSetting]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py index 60f6dbfcf9cd..4154ad1a0181 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import OmnichannelSettingsServiceTransport from .grpc import OmnichannelSettingsServiceGrpcTransport from .grpc_asyncio import OmnichannelSettingsServiceGrpcAsyncIOTransport -from .rest import OmnichannelSettingsServiceRestTransport -from .rest import OmnichannelSettingsServiceRestInterceptor - +from .rest import ( + OmnichannelSettingsServiceRestInterceptor, + OmnichannelSettingsServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] -_transport_registry['grpc'] = OmnichannelSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OmnichannelSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = OmnichannelSettingsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[OmnichannelSettingsServiceTransport]] +_transport_registry["grpc"] = OmnichannelSettingsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = OmnichannelSettingsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = OmnichannelSettingsServiceRestTransport __all__ = ( - 'OmnichannelSettingsServiceTransport', - 'OmnichannelSettingsServiceGrpcTransport', - 'OmnichannelSettingsServiceGrpcAsyncIOTransport', - 'OmnichannelSettingsServiceRestTransport', - 'OmnichannelSettingsServiceRestInterceptor', + "OmnichannelSettingsServiceTransport", + "OmnichannelSettingsServiceGrpcTransport", + "OmnichannelSettingsServiceGrpcAsyncIOTransport", + "OmnichannelSettingsServiceRestTransport", + "OmnichannelSettingsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py similarity index 63% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py index 0f5b4dadfbc9..8942c9ee82bb 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import omnichannelsettings -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__ @@ -38,24 +39,23 @@ class OmnichannelSettingsServiceTransport(abc.ABC): """Abstract transport class for OmnichannelSettingsService.""" - 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: @@ -91,30 +91,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 @@ -149,60 +157,75 @@ 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 get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - Union[ - omnichannelsettings.OmnichannelSetting, - Awaitable[omnichannelsettings.OmnichannelSetting] - ]]: + def get_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting], + ], + ]: raise NotImplementedError() @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - Union[ - omnichannelsettings.ListOmnichannelSettingsResponse, - Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse] - ]]: + def list_omnichannel_settings( + self, + ) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + Union[ + omnichannelsettings.ListOmnichannelSettingsResponse, + Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse], + ], + ]: raise NotImplementedError() @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - Union[ - omnichannelsettings.OmnichannelSetting, - Awaitable[omnichannelsettings.OmnichannelSetting] - ]]: + def create_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting], + ], + ]: raise NotImplementedError() @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - Union[ - omnichannelsettings.OmnichannelSetting, - Awaitable[omnichannelsettings.OmnichannelSetting] - ]]: + def update_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + Union[ + omnichannelsettings.OmnichannelSetting, + Awaitable[omnichannelsettings.OmnichannelSetting], + ], + ]: raise NotImplementedError() @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - Union[ - omnichannelsettings.RequestInventoryVerificationResponse, - Awaitable[omnichannelsettings.RequestInventoryVerificationResponse] - ]]: + def request_inventory_verification( + self, + ) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + Union[ + omnichannelsettings.RequestInventoryVerificationResponse, + Awaitable[omnichannelsettings.RequestInventoryVerificationResponse], + ], + ]: raise NotImplementedError() @property @@ -210,6 +233,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'OmnichannelSettingsServiceTransport', -) +__all__ = ("OmnichannelSettingsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py index 0cd69db8e3dc..dfc231fd1673 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import omnichannelsettings -from .base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, OmnichannelSettingsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -108,9 +114,7 @@ class OmnichannelSettingsServiceGrpcTransport(OmnichannelSettingsServiceTranspor settings. This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -119,23 +123,26 @@ class OmnichannelSettingsServiceGrpcTransport(OmnichannelSettingsServiceTranspor 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: @@ -257,19 +264,23 @@ def __init__(self, *, ) self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = '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. @@ -304,19 +315,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 get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: + def get_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting, + ]: r"""Return a callable for the get omnichannel setting method over gRPC. Get the omnichannel settings for a given merchant. @@ -331,18 +344,21 @@ def get_omnichannel_setting(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_omnichannel_setting' not in self._stubs: - self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/GetOmnichannelSetting', + if "get_omnichannel_setting" not in self._stubs: + self._stubs["get_omnichannel_setting"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/GetOmnichannelSetting", request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, ) - return self._stubs['get_omnichannel_setting'] + return self._stubs["get_omnichannel_setting"] @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - omnichannelsettings.ListOmnichannelSettingsResponse]: + def list_omnichannel_settings( + self, + ) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + omnichannelsettings.ListOmnichannelSettingsResponse, + ]: r"""Return a callable for the list omnichannel settings method over gRPC. List all the omnichannel settings for a given @@ -358,18 +374,21 @@ def list_omnichannel_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_omnichannel_settings' not in self._stubs: - self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/ListOmnichannelSettings', + if "list_omnichannel_settings" not in self._stubs: + self._stubs["list_omnichannel_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/ListOmnichannelSettings", request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, ) - return self._stubs['list_omnichannel_settings'] + return self._stubs["list_omnichannel_settings"] @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: + def create_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting, + ]: r"""Return a callable for the create omnichannel setting method over gRPC. Create the omnichannel settings for a given merchant. @@ -384,18 +403,23 @@ def create_omnichannel_setting(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_omnichannel_setting' not in self._stubs: - self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/CreateOmnichannelSetting', + if "create_omnichannel_setting" not in self._stubs: + self._stubs[ + "create_omnichannel_setting" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/CreateOmnichannelSetting", request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, ) - return self._stubs['create_omnichannel_setting'] + return self._stubs["create_omnichannel_setting"] @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: + def update_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting, + ]: r"""Return a callable for the update omnichannel setting method over gRPC. Update the omnichannel setting for a given merchant @@ -411,18 +435,23 @@ def update_omnichannel_setting(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_omnichannel_setting' not in self._stubs: - self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/UpdateOmnichannelSetting', + if "update_omnichannel_setting" not in self._stubs: + self._stubs[ + "update_omnichannel_setting" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/UpdateOmnichannelSetting", request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, ) - return self._stubs['update_omnichannel_setting'] + return self._stubs["update_omnichannel_setting"] @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - omnichannelsettings.RequestInventoryVerificationResponse]: + def request_inventory_verification( + self, + ) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + omnichannelsettings.RequestInventoryVerificationResponse, + ]: r"""Return a callable for the request inventory verification method over gRPC. Requests inventory verification for a given merchant @@ -438,13 +467,15 @@ def request_inventory_verification(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'request_inventory_verification' not in self._stubs: - self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/RequestInventoryVerification', + if "request_inventory_verification" not in self._stubs: + self._stubs[ + "request_inventory_verification" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/RequestInventoryVerification", request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, ) - return self._stubs['request_inventory_verification'] + return self._stubs["request_inventory_verification"] def close(self): self._logged_channel.close() @@ -454,6 +485,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'OmnichannelSettingsServiceGrpcTransport', -) +__all__ = ("OmnichannelSettingsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py index e7fa978af5f3..efb93adc2eb5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import omnichannelsettings -from .base import OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, OmnichannelSettingsServiceTransport from .grpc import OmnichannelSettingsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -105,16 +113,16 @@ async def intercept_unary_unary(self, continuation, client_call_details, request return response -class OmnichannelSettingsServiceGrpcAsyncIOTransport(OmnichannelSettingsServiceTransport): +class OmnichannelSettingsServiceGrpcAsyncIOTransport( + OmnichannelSettingsServiceTransport +): """gRPC AsyncIO backend transport for OmnichannelSettingsService. The service facilitates the management of a merchant's omnichannel settings. This API defines the following resource model: - ---------------------------------------------- - - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] + - [OmnichannelSetting][google.shopping.merchant.accounts.v1.OmnichannelSetting] This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -128,13 +136,15 @@ class OmnichannelSettingsServiceGrpcAsyncIOTransport(OmnichannelSettingsServiceT _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. @@ -164,24 +174,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: @@ -305,7 +317,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) @@ -320,9 +334,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - Awaitable[omnichannelsettings.OmnichannelSetting]]: + def get_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting], + ]: r"""Return a callable for the get omnichannel setting method over gRPC. Get the omnichannel settings for a given merchant. @@ -337,18 +354,21 @@ def get_omnichannel_setting(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_omnichannel_setting' not in self._stubs: - self._stubs['get_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/GetOmnichannelSetting', + if "get_omnichannel_setting" not in self._stubs: + self._stubs["get_omnichannel_setting"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/GetOmnichannelSetting", request_serializer=omnichannelsettings.GetOmnichannelSettingRequest.serialize, response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, ) - return self._stubs['get_omnichannel_setting'] + return self._stubs["get_omnichannel_setting"] @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse]]: + def list_omnichannel_settings( + self, + ) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + Awaitable[omnichannelsettings.ListOmnichannelSettingsResponse], + ]: r"""Return a callable for the list omnichannel settings method over gRPC. List all the omnichannel settings for a given @@ -364,18 +384,21 @@ def list_omnichannel_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_omnichannel_settings' not in self._stubs: - self._stubs['list_omnichannel_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/ListOmnichannelSettings', + if "list_omnichannel_settings" not in self._stubs: + self._stubs["list_omnichannel_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/ListOmnichannelSettings", request_serializer=omnichannelsettings.ListOmnichannelSettingsRequest.serialize, response_deserializer=omnichannelsettings.ListOmnichannelSettingsResponse.deserialize, ) - return self._stubs['list_omnichannel_settings'] + return self._stubs["list_omnichannel_settings"] @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - Awaitable[omnichannelsettings.OmnichannelSetting]]: + def create_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting], + ]: r"""Return a callable for the create omnichannel setting method over gRPC. Create the omnichannel settings for a given merchant. @@ -390,18 +413,23 @@ def create_omnichannel_setting(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_omnichannel_setting' not in self._stubs: - self._stubs['create_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/CreateOmnichannelSetting', + if "create_omnichannel_setting" not in self._stubs: + self._stubs[ + "create_omnichannel_setting" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/CreateOmnichannelSetting", request_serializer=omnichannelsettings.CreateOmnichannelSettingRequest.serialize, response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, ) - return self._stubs['create_omnichannel_setting'] + return self._stubs["create_omnichannel_setting"] @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - Awaitable[omnichannelsettings.OmnichannelSetting]]: + def update_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + Awaitable[omnichannelsettings.OmnichannelSetting], + ]: r"""Return a callable for the update omnichannel setting method over gRPC. Update the omnichannel setting for a given merchant @@ -417,18 +445,23 @@ def update_omnichannel_setting(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_omnichannel_setting' not in self._stubs: - self._stubs['update_omnichannel_setting'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/UpdateOmnichannelSetting', + if "update_omnichannel_setting" not in self._stubs: + self._stubs[ + "update_omnichannel_setting" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/UpdateOmnichannelSetting", request_serializer=omnichannelsettings.UpdateOmnichannelSettingRequest.serialize, response_deserializer=omnichannelsettings.OmnichannelSetting.deserialize, ) - return self._stubs['update_omnichannel_setting'] + return self._stubs["update_omnichannel_setting"] @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - Awaitable[omnichannelsettings.RequestInventoryVerificationResponse]]: + def request_inventory_verification( + self, + ) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + Awaitable[omnichannelsettings.RequestInventoryVerificationResponse], + ]: r"""Return a callable for the request inventory verification method over gRPC. Requests inventory verification for a given merchant @@ -444,16 +477,18 @@ def request_inventory_verification(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'request_inventory_verification' not in self._stubs: - self._stubs['request_inventory_verification'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/RequestInventoryVerification', + if "request_inventory_verification" not in self._stubs: + self._stubs[ + "request_inventory_verification" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OmnichannelSettingsService/RequestInventoryVerification", request_serializer=omnichannelsettings.RequestInventoryVerificationRequest.serialize, response_deserializer=omnichannelsettings.RequestInventoryVerificationResponse.deserialize, ) - return self._stubs['request_inventory_verification'] + return self._stubs["request_inventory_verification"] 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.get_omnichannel_setting: self._wrap_method( self.get_omnichannel_setting, @@ -495,6 +530,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'OmnichannelSettingsServiceGrpcAsyncIOTransport', -) +__all__ = ("OmnichannelSettingsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py similarity index 62% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py index 3b2e087d3189..21b7ee255b61 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import omnichannelsettings - -from .rest_base import _BaseOmnichannelSettingsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseOmnichannelSettingsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -122,7 +117,15 @@ def post_update_omnichannel_setting(self, response): """ - def pre_create_omnichannel_setting(self, request: omnichannelsettings.CreateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.CreateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_omnichannel_setting( + self, + request: omnichannelsettings.CreateOmnichannelSettingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.CreateOmnichannelSettingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_omnichannel_setting Override in a subclass to manipulate the request or metadata @@ -130,7 +133,9 @@ def pre_create_omnichannel_setting(self, request: omnichannelsettings.CreateOmni """ return request, metadata - def post_create_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + def post_create_omnichannel_setting( + self, response: omnichannelsettings.OmnichannelSetting + ) -> omnichannelsettings.OmnichannelSetting: """Post-rpc interceptor for create_omnichannel_setting DEPRECATED. Please use the `post_create_omnichannel_setting_with_metadata` @@ -143,7 +148,13 @@ def post_create_omnichannel_setting(self, response: omnichannelsettings.Omnichan """ return response - def post_create_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_omnichannel_setting_with_metadata( + self, + response: omnichannelsettings.OmnichannelSetting, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for create_omnichannel_setting Override in a subclass to read or manipulate the response or metadata after it @@ -158,7 +169,14 @@ def post_create_omnichannel_setting_with_metadata(self, response: omnichannelset """ return response, metadata - def pre_get_omnichannel_setting(self, request: omnichannelsettings.GetOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.GetOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_omnichannel_setting( + self, + request: omnichannelsettings.GetOmnichannelSettingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.GetOmnichannelSettingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_omnichannel_setting Override in a subclass to manipulate the request or metadata @@ -166,7 +184,9 @@ def pre_get_omnichannel_setting(self, request: omnichannelsettings.GetOmnichanne """ return request, metadata - def post_get_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + def post_get_omnichannel_setting( + self, response: omnichannelsettings.OmnichannelSetting + ) -> omnichannelsettings.OmnichannelSetting: """Post-rpc interceptor for get_omnichannel_setting DEPRECATED. Please use the `post_get_omnichannel_setting_with_metadata` @@ -179,7 +199,13 @@ def post_get_omnichannel_setting(self, response: omnichannelsettings.Omnichannel """ return response - def post_get_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_omnichannel_setting_with_metadata( + self, + response: omnichannelsettings.OmnichannelSetting, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_omnichannel_setting Override in a subclass to read or manipulate the response or metadata after it @@ -194,7 +220,14 @@ def post_get_omnichannel_setting_with_metadata(self, response: omnichannelsettin """ return response, metadata - def pre_list_omnichannel_settings(self, request: omnichannelsettings.ListOmnichannelSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_omnichannel_settings( + self, + request: omnichannelsettings.ListOmnichannelSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.ListOmnichannelSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_omnichannel_settings Override in a subclass to manipulate the request or metadata @@ -202,7 +235,9 @@ def pre_list_omnichannel_settings(self, request: omnichannelsettings.ListOmnicha """ return request, metadata - def post_list_omnichannel_settings(self, response: omnichannelsettings.ListOmnichannelSettingsResponse) -> omnichannelsettings.ListOmnichannelSettingsResponse: + def post_list_omnichannel_settings( + self, response: omnichannelsettings.ListOmnichannelSettingsResponse + ) -> omnichannelsettings.ListOmnichannelSettingsResponse: """Post-rpc interceptor for list_omnichannel_settings DEPRECATED. Please use the `post_list_omnichannel_settings_with_metadata` @@ -215,7 +250,14 @@ def post_list_omnichannel_settings(self, response: omnichannelsettings.ListOmnic """ return response - def post_list_omnichannel_settings_with_metadata(self, response: omnichannelsettings.ListOmnichannelSettingsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.ListOmnichannelSettingsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_omnichannel_settings_with_metadata( + self, + response: omnichannelsettings.ListOmnichannelSettingsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.ListOmnichannelSettingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_omnichannel_settings Override in a subclass to read or manipulate the response or metadata after it @@ -230,7 +272,14 @@ def post_list_omnichannel_settings_with_metadata(self, response: omnichannelsett """ return response, metadata - def pre_request_inventory_verification(self, request: omnichannelsettings.RequestInventoryVerificationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_request_inventory_verification( + self, + request: omnichannelsettings.RequestInventoryVerificationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.RequestInventoryVerificationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for request_inventory_verification Override in a subclass to manipulate the request or metadata @@ -238,7 +287,9 @@ def pre_request_inventory_verification(self, request: omnichannelsettings.Reques """ return request, metadata - def post_request_inventory_verification(self, response: omnichannelsettings.RequestInventoryVerificationResponse) -> omnichannelsettings.RequestInventoryVerificationResponse: + def post_request_inventory_verification( + self, response: omnichannelsettings.RequestInventoryVerificationResponse + ) -> omnichannelsettings.RequestInventoryVerificationResponse: """Post-rpc interceptor for request_inventory_verification DEPRECATED. Please use the `post_request_inventory_verification_with_metadata` @@ -251,7 +302,14 @@ def post_request_inventory_verification(self, response: omnichannelsettings.Requ """ return response - def post_request_inventory_verification_with_metadata(self, response: omnichannelsettings.RequestInventoryVerificationResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.RequestInventoryVerificationResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_request_inventory_verification_with_metadata( + self, + response: omnichannelsettings.RequestInventoryVerificationResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.RequestInventoryVerificationResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for request_inventory_verification Override in a subclass to read or manipulate the response or metadata after it @@ -266,7 +324,14 @@ def post_request_inventory_verification_with_metadata(self, response: omnichanne """ return response, metadata - def pre_update_omnichannel_setting(self, request: omnichannelsettings.UpdateOmnichannelSettingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.UpdateOmnichannelSettingRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_omnichannel_setting( + self, + request: omnichannelsettings.UpdateOmnichannelSettingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.UpdateOmnichannelSettingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for update_omnichannel_setting Override in a subclass to manipulate the request or metadata @@ -274,7 +339,9 @@ def pre_update_omnichannel_setting(self, request: omnichannelsettings.UpdateOmni """ return request, metadata - def post_update_omnichannel_setting(self, response: omnichannelsettings.OmnichannelSetting) -> omnichannelsettings.OmnichannelSetting: + def post_update_omnichannel_setting( + self, response: omnichannelsettings.OmnichannelSetting + ) -> omnichannelsettings.OmnichannelSetting: """Post-rpc interceptor for update_omnichannel_setting DEPRECATED. Please use the `post_update_omnichannel_setting_with_metadata` @@ -287,7 +354,13 @@ def post_update_omnichannel_setting(self, response: omnichannelsettings.Omnichan """ return response - def post_update_omnichannel_setting_with_metadata(self, response: omnichannelsettings.OmnichannelSetting, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_omnichannel_setting_with_metadata( + self, + response: omnichannelsettings.OmnichannelSetting, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + omnichannelsettings.OmnichannelSetting, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for update_omnichannel_setting Override in a subclass to read or manipulate the response or metadata after it @@ -310,7 +383,9 @@ class OmnichannelSettingsServiceRestStub: _interceptor: OmnichannelSettingsServiceRestInterceptor -class OmnichannelSettingsServiceRestTransport(_BaseOmnichannelSettingsServiceRestTransport): +class OmnichannelSettingsServiceRestTransport( + _BaseOmnichannelSettingsServiceRestTransport +): """REST backend synchronous transport for OmnichannelSettingsService. The service facilitates the management of a merchant's omnichannel @@ -328,20 +403,21 @@ class OmnichannelSettingsServiceRestTransport(_BaseOmnichannelSettingsServiceRes 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[OmnichannelSettingsServiceRestInterceptor] = 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[OmnichannelSettingsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -384,18 +460,24 @@ 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 OmnichannelSettingsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting, OmnichannelSettingsServiceRestStub): + class _CreateOmnichannelSetting( + _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting, + OmnichannelSettingsServiceRestStub, + ): def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.CreateOmnichannelSetting") + return hash( + "OmnichannelSettingsServiceRestTransport.CreateOmnichannelSetting" + ) @staticmethod def _get_response( @@ -405,75 +487,91 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: omnichannelsettings.CreateOmnichannelSettingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.OmnichannelSetting: + def __call__( + self, + request: omnichannelsettings.CreateOmnichannelSettingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Call the create omnichannel - setting method over HTTP. - - Args: - request (~.omnichannelsettings.CreateOmnichannelSettingRequest): - The request object. Request message for the - CreateOmnichannelSetting 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: - ~.omnichannelsettings.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. + setting method over HTTP. + + Args: + request (~.omnichannelsettings.CreateOmnichannelSettingRequest): + The request object. Request message for the + CreateOmnichannelSetting 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. """ - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_http_options() + http_options = ( + _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_http_options() + ) - request, metadata = self._interceptor.pre_create_omnichannel_setting(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_omnichannel_setting( + request, metadata + ) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_transcoded_request( + http_options, request + ) - body = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_request_body_json(transcoded_request) + body = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.CreateOmnichannelSetting", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "CreateOmnichannelSetting", "httpRequest": http_request, @@ -482,7 +580,15 @@ def __call__(self, ) # Send the request - response = OmnichannelSettingsServiceRestTransport._CreateOmnichannelSetting._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OmnichannelSettingsServiceRestTransport._CreateOmnichannelSetting._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. @@ -497,20 +603,26 @@ def __call__(self, resp = self._interceptor.post_create_omnichannel_setting(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_omnichannel_setting_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_omnichannel_setting_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = omnichannelsettings.OmnichannelSetting.to_json(response) + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1.OmnichannelSettingsServiceClient.create_omnichannel_setting", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "CreateOmnichannelSetting", "metadata": http_response["headers"], @@ -519,7 +631,10 @@ def __call__(self, ) return resp - class _GetOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting, OmnichannelSettingsServiceRestStub): + class _GetOmnichannelSetting( + _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting, + OmnichannelSettingsServiceRestStub, + ): def __hash__(self): return hash("OmnichannelSettingsServiceRestTransport.GetOmnichannelSetting") @@ -531,26 +646,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: omnichannelsettings.GetOmnichannelSettingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.OmnichannelSetting: + def __call__( + self, + request: omnichannelsettings.GetOmnichannelSettingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Call the get omnichannel setting method over HTTP. Args: @@ -572,30 +689,42 @@ def __call__(self, """ - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_http_options() + http_options = ( + _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_http_options() + ) - request, metadata = self._interceptor.pre_get_omnichannel_setting(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_omnichannel_setting( + request, metadata + ) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.GetOmnichannelSetting", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "GetOmnichannelSetting", "httpRequest": http_request, @@ -604,7 +733,14 @@ def __call__(self, ) # Send the request - response = OmnichannelSettingsServiceRestTransport._GetOmnichannelSetting._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OmnichannelSettingsServiceRestTransport._GetOmnichannelSetting._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -619,20 +755,26 @@ def __call__(self, resp = self._interceptor.post_get_omnichannel_setting(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_omnichannel_setting_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_omnichannel_setting_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = omnichannelsettings.OmnichannelSetting.to_json(response) + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1.OmnichannelSettingsServiceClient.get_omnichannel_setting", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "GetOmnichannelSetting", "metadata": http_response["headers"], @@ -641,9 +783,14 @@ def __call__(self, ) return resp - class _ListOmnichannelSettings(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings, OmnichannelSettingsServiceRestStub): + class _ListOmnichannelSettings( + _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings, + OmnichannelSettingsServiceRestStub, + ): def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.ListOmnichannelSettings") + return hash( + "OmnichannelSettingsServiceRestTransport.ListOmnichannelSettings" + ) @staticmethod def _get_response( @@ -653,26 +800,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: omnichannelsettings.ListOmnichannelSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.ListOmnichannelSettingsResponse: + def __call__( + self, + request: omnichannelsettings.ListOmnichannelSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.ListOmnichannelSettingsResponse: r"""Call the list omnichannel settings method over HTTP. Args: @@ -694,30 +843,42 @@ def __call__(self, """ - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_http_options() + http_options = ( + _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_list_omnichannel_settings(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_omnichannel_settings( + request, metadata + ) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.ListOmnichannelSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "ListOmnichannelSettings", "httpRequest": http_request, @@ -726,7 +887,14 @@ def __call__(self, ) # Send the request - response = OmnichannelSettingsServiceRestTransport._ListOmnichannelSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OmnichannelSettingsServiceRestTransport._ListOmnichannelSettings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -741,20 +909,28 @@ def __call__(self, resp = self._interceptor.post_list_omnichannel_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_omnichannel_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_omnichannel_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = omnichannelsettings.ListOmnichannelSettingsResponse.to_json(response) + response_payload = ( + omnichannelsettings.ListOmnichannelSettingsResponse.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.accounts_v1.OmnichannelSettingsServiceClient.list_omnichannel_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "ListOmnichannelSettings", "metadata": http_response["headers"], @@ -763,9 +939,14 @@ def __call__(self, ) return resp - class _RequestInventoryVerification(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification, OmnichannelSettingsServiceRestStub): + class _RequestInventoryVerification( + _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification, + OmnichannelSettingsServiceRestStub, + ): def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.RequestInventoryVerification") + return hash( + "OmnichannelSettingsServiceRestTransport.RequestInventoryVerification" + ) @staticmethod def _get_response( @@ -775,75 +956,91 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: omnichannelsettings.RequestInventoryVerificationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.RequestInventoryVerificationResponse: + def __call__( + self, + request: omnichannelsettings.RequestInventoryVerificationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.RequestInventoryVerificationResponse: r"""Call the request inventory - verification method over HTTP. - - Args: - request (~.omnichannelsettings.RequestInventoryVerificationRequest): - The request object. Request message for the - RequestInventoryVerification 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: - ~.omnichannelsettings.RequestInventoryVerificationResponse: - Response message for the - RequestInventoryVerification method. + verification method over HTTP. + + Args: + request (~.omnichannelsettings.RequestInventoryVerificationRequest): + The request object. Request message for the + RequestInventoryVerification 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: + ~.omnichannelsettings.RequestInventoryVerificationResponse: + Response message for the + RequestInventoryVerification method. """ - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_http_options() + http_options = ( + _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_http_options() + ) - request, metadata = self._interceptor.pre_request_inventory_verification(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_request_inventory_verification( + request, metadata + ) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_transcoded_request( + http_options, request + ) - body = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_request_body_json(transcoded_request) + body = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.RequestInventoryVerification", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "RequestInventoryVerification", "httpRequest": http_request, @@ -852,7 +1049,15 @@ def __call__(self, ) # Send the request - response = OmnichannelSettingsServiceRestTransport._RequestInventoryVerification._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OmnichannelSettingsServiceRestTransport._RequestInventoryVerification._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. @@ -867,20 +1072,29 @@ def __call__(self, resp = self._interceptor.post_request_inventory_verification(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_request_inventory_verification_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_request_inventory_verification_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = omnichannelsettings.RequestInventoryVerificationResponse.to_json(response) + response_payload = omnichannelsettings.RequestInventoryVerificationResponse.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.accounts_v1.OmnichannelSettingsServiceClient.request_inventory_verification", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "RequestInventoryVerification", "metadata": http_response["headers"], @@ -889,9 +1103,14 @@ def __call__(self, ) return resp - class _UpdateOmnichannelSetting(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting, OmnichannelSettingsServiceRestStub): + class _UpdateOmnichannelSetting( + _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting, + OmnichannelSettingsServiceRestStub, + ): def __hash__(self): - return hash("OmnichannelSettingsServiceRestTransport.UpdateOmnichannelSetting") + return hash( + "OmnichannelSettingsServiceRestTransport.UpdateOmnichannelSetting" + ) @staticmethod def _get_response( @@ -901,75 +1120,91 @@ def _get_response( session, timeout, transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(session, method)( "{host}{uri}".format(host=host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) return response - def __call__(self, - request: omnichannelsettings.UpdateOmnichannelSettingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> omnichannelsettings.OmnichannelSetting: + def __call__( + self, + request: omnichannelsettings.UpdateOmnichannelSettingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> omnichannelsettings.OmnichannelSetting: r"""Call the update omnichannel - setting method over HTTP. - - Args: - request (~.omnichannelsettings.UpdateOmnichannelSettingRequest): - The request object. Request message for the - UpdateOmnichannelSetting 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: - ~.omnichannelsettings.OmnichannelSetting: - Collection of information related to - the omnichannel settings of a merchant. + setting method over HTTP. + + Args: + request (~.omnichannelsettings.UpdateOmnichannelSettingRequest): + The request object. Request message for the + UpdateOmnichannelSetting 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: + ~.omnichannelsettings.OmnichannelSetting: + Collection of information related to + the omnichannel settings of a merchant. """ - http_options = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_http_options() + http_options = ( + _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_http_options() + ) - request, metadata = self._interceptor.pre_update_omnichannel_setting(request, metadata) - transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_update_omnichannel_setting( + request, metadata + ) + transcoded_request = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_transcoded_request( + http_options, request + ) - body = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_request_body_json(transcoded_request) + body = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OmnichannelSettingsServiceClient.UpdateOmnichannelSetting", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "UpdateOmnichannelSetting", "httpRequest": http_request, @@ -978,7 +1213,15 @@ def __call__(self, ) # Send the request - response = OmnichannelSettingsServiceRestTransport._UpdateOmnichannelSetting._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OmnichannelSettingsServiceRestTransport._UpdateOmnichannelSetting._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. @@ -993,20 +1236,26 @@ def __call__(self, resp = self._interceptor.post_update_omnichannel_setting(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_omnichannel_setting_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_omnichannel_setting_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = omnichannelsettings.OmnichannelSetting.to_json(response) + response_payload = omnichannelsettings.OmnichannelSetting.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.accounts_v1.OmnichannelSettingsServiceClient.update_omnichannel_setting", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OmnichannelSettingsService", "rpcName": "UpdateOmnichannelSetting", "metadata": http_response["headers"], @@ -1016,44 +1265,59 @@ def __call__(self, return resp @property - def create_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.CreateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: + def create_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.CreateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting, + ]: # 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._CreateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + return self._CreateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore @property - def get_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.GetOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: + def get_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.GetOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting, + ]: # 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._GetOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + return self._GetOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore @property - def list_omnichannel_settings(self) -> Callable[ - [omnichannelsettings.ListOmnichannelSettingsRequest], - omnichannelsettings.ListOmnichannelSettingsResponse]: + def list_omnichannel_settings( + self, + ) -> Callable[ + [omnichannelsettings.ListOmnichannelSettingsRequest], + omnichannelsettings.ListOmnichannelSettingsResponse, + ]: # 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._ListOmnichannelSettings(self._session, self._host, self._interceptor) # type: ignore + return self._ListOmnichannelSettings(self._session, self._host, self._interceptor) # type: ignore @property - def request_inventory_verification(self) -> Callable[ - [omnichannelsettings.RequestInventoryVerificationRequest], - omnichannelsettings.RequestInventoryVerificationResponse]: + def request_inventory_verification( + self, + ) -> Callable[ + [omnichannelsettings.RequestInventoryVerificationRequest], + omnichannelsettings.RequestInventoryVerificationResponse, + ]: # 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._RequestInventoryVerification(self._session, self._host, self._interceptor) # type: ignore + return self._RequestInventoryVerification(self._session, self._host, self._interceptor) # type: ignore @property - def update_omnichannel_setting(self) -> Callable[ - [omnichannelsettings.UpdateOmnichannelSettingRequest], - omnichannelsettings.OmnichannelSetting]: + def update_omnichannel_setting( + self, + ) -> Callable[ + [omnichannelsettings.UpdateOmnichannelSettingRequest], + omnichannelsettings.OmnichannelSetting, + ]: # 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._UpdateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateOmnichannelSetting(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -1063,6 +1327,4 @@ def close(self): self._session.close() -__all__=( - 'OmnichannelSettingsServiceRestTransport', -) +__all__ = ("OmnichannelSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py similarity index 57% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py index 5a6bf3c35dbe..3a1a9ce8320b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/omnichannel_settings_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 OmnichannelSettingsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import omnichannelsettings +from .base import DEFAULT_CLIENT_INFO, OmnichannelSettingsServiceTransport + class _BaseOmnichannelSettingsServiceRestTransport(OmnichannelSettingsServiceTransport): """Base REST backend transport for OmnichannelSettingsService. @@ -40,14 +38,16 @@ class _BaseOmnichannelSettingsServiceRestTransport(OmnichannelSettingsServiceTra 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,27 +84,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseCreateOmnichannelSetting: 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': '/accounts/v1/{parent=accounts/*}/omnichannelSettings', - 'body': 'omnichannel_setting', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/omnichannelSettings", + "body": "omnichannel_setting", + }, ] return http_options @@ -117,17 +123,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._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( + _BaseOmnichannelSettingsServiceRestTransport._BaseCreateOmnichannelSetting._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -136,19 +148,23 @@ class _BaseGetOmnichannelSetting: 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': '/accounts/v1/{name=accounts/*/omnichannelSettings/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/omnichannelSettings/*}", + }, ] return http_options @@ -160,11 +176,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(_BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._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( + _BaseOmnichannelSettingsServiceRestTransport._BaseGetOmnichannelSetting._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -173,19 +195,23 @@ class _BaseListOmnichannelSettings: 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': '/accounts/v1/{parent=accounts/*}/omnichannelSettings', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/omnichannelSettings", + }, ] return http_options @@ -197,11 +223,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(_BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._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( + _BaseOmnichannelSettingsServiceRestTransport._BaseListOmnichannelSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -210,26 +242,32 @@ class _BaseRequestInventoryVerification: 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': '/accounts/v1/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification", + "body": "*", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = omnichannelsettings.RequestInventoryVerificationRequest.pb(request) + pb_request = omnichannelsettings.RequestInventoryVerificationRequest.pb( + request + ) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -238,17 +276,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(_BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._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( + _BaseOmnichannelSettingsServiceRestTransport._BaseRequestInventoryVerification._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -257,20 +301,26 @@ class _BaseUpdateOmnichannelSetting: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask": {}, + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}', - 'body': 'omnichannel_setting', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}", + "body": "omnichannel_setting", + }, ] return http_options @@ -285,22 +335,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._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( + _BaseOmnichannelSettingsServiceRestTransport._BaseUpdateOmnichannelSetting._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseOmnichannelSettingsServiceRestTransport', -) +__all__ = ("_BaseOmnichannelSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py index 856118f59e37..ed8b4e63ce12 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import OnlineReturnPolicyServiceClient from .async_client import OnlineReturnPolicyServiceAsyncClient +from .client import OnlineReturnPolicyServiceClient __all__ = ( - 'OnlineReturnPolicyServiceClient', - 'OnlineReturnPolicyServiceAsyncClient', + "OnlineReturnPolicyServiceClient", + "OnlineReturnPolicyServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py index 36f356f18deb..221e159190d8 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/async_client.py @@ -13,51 +13,67 @@ # 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_accounts_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_accounts_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_accounts_v1.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1.services.online_return_policy_service import ( + pagers, +) +from google.shopping.merchant_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy -from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport + from .client import OnlineReturnPolicyServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, OnlineReturnPolicyServiceTransport +from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport 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 OnlineReturnPolicyServiceAsyncClient: """The service facilitates the management of a business's remorse return policy configuration, encompassing return policies for both ads and free listings programs. This API defines the following resource model: - -------------------------------------------------------- - `OnlineReturnPolicy `__ + - `OnlineReturnPolicy `__ """ _client: OnlineReturnPolicyServiceClient @@ -66,21 +82,47 @@ class OnlineReturnPolicyServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.online_return_policy_path) - parse_online_return_policy_path = staticmethod(OnlineReturnPolicyServiceClient.parse_online_return_policy_path) - common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_organization_path) - common_project_path = staticmethod(OnlineReturnPolicyServiceClient.common_project_path) - parse_common_project_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_project_path) - common_location_path = staticmethod(OnlineReturnPolicyServiceClient.common_location_path) - parse_common_location_path = staticmethod(OnlineReturnPolicyServiceClient.parse_common_location_path) + online_return_policy_path = staticmethod( + OnlineReturnPolicyServiceClient.online_return_policy_path + ) + parse_online_return_policy_path = staticmethod( + OnlineReturnPolicyServiceClient.parse_online_return_policy_path + ) + common_billing_account_path = staticmethod( + OnlineReturnPolicyServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + OnlineReturnPolicyServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + OnlineReturnPolicyServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + OnlineReturnPolicyServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + OnlineReturnPolicyServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + OnlineReturnPolicyServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + OnlineReturnPolicyServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + OnlineReturnPolicyServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + OnlineReturnPolicyServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + OnlineReturnPolicyServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -116,7 +158,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: @@ -179,12 +223,20 @@ def universe_domain(self) -> str: get_transport_class = OnlineReturnPolicyServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = "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, + OnlineReturnPolicyServiceTransport, + Callable[..., OnlineReturnPolicyServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the online return policy service async client. Args: @@ -239,31 +291,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.accounts_v1.OnlineReturnPolicyServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", - "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.accounts.v1.OnlineReturnPolicyService", "credentialsType": None, - } + }, ) - async def get_online_return_policy(self, - request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> online_return_policy.OnlineReturnPolicy: + async def get_online_return_policy( + self, + request: Optional[ + Union[online_return_policy.GetOnlineReturnPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: r"""Gets an existing return policy for a given business. .. code-block:: python @@ -323,10 +385,14 @@ async def sample_get_online_return_policy(): # - 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. @@ -340,14 +406,14 @@ async def sample_get_online_return_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_online_return_policy] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_online_return_policy + ] # 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. @@ -364,14 +430,17 @@ async def sample_get_online_return_policy(): # Done; return the response. return response - async def list_online_return_policies(self, - request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesAsyncPager: + async def list_online_return_policies( + self, + request: Optional[ + Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesAsyncPager: r"""Lists all existing return policies for a given business. @@ -434,14 +503,20 @@ async def sample_list_online_return_policies(): # - 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. - if not isinstance(request, online_return_policy.ListOnlineReturnPoliciesRequest): + if not isinstance( + request, online_return_policy.ListOnlineReturnPoliciesRequest + ): request = online_return_policy.ListOnlineReturnPoliciesRequest(request) # If we have keyword arguments corresponding to fields on the @@ -451,14 +526,14 @@ async def sample_list_online_return_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_online_return_policies] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_online_return_policies + ] # 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. @@ -486,15 +561,20 @@ async def sample_list_online_return_policies(): # Done; return the response. return response - async def create_online_return_policy(self, - request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_online_return_policy.OnlineReturnPolicy: + async def create_online_return_policy( + self, + request: Optional[ + Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + online_return_policy: Optional[ + gsma_online_return_policy.OnlineReturnPolicy + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: r"""Creates a new return policy for a given business. .. code-block:: python @@ -566,14 +646,20 @@ async def sample_create_online_return_policy(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, online_return_policy] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + if not isinstance( + request, gsma_online_return_policy.CreateOnlineReturnPolicyRequest + ): request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) # If we have keyword arguments corresponding to fields on the @@ -585,14 +671,14 @@ async def sample_create_online_return_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_online_return_policy] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_online_return_policy + ] # 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. @@ -609,14 +695,17 @@ async def sample_create_online_return_policy(): # Done; return the response. return response - async def delete_online_return_policy(self, - request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, - *, - name: 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_online_return_policy( + self, + request: Optional[ + Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict] + ] = None, + *, + name: 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 an existing return policy. .. code-block:: python @@ -666,14 +755,20 @@ async def sample_delete_online_return_policy(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, online_return_policy.DeleteOnlineReturnPolicyRequest): + if not isinstance( + request, online_return_policy.DeleteOnlineReturnPolicyRequest + ): request = online_return_policy.DeleteOnlineReturnPolicyRequest(request) # If we have keyword arguments corresponding to fields on the @@ -683,14 +778,14 @@ async def sample_delete_online_return_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_online_return_policy] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_online_return_policy + ] # 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. @@ -710,12 +805,13 @@ async def __aenter__(self) -> "OnlineReturnPolicyServiceAsyncClient": 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__ = ( - "OnlineReturnPolicyServiceAsyncClient", -) +__all__ = ("OnlineReturnPolicyServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py index 6b9305c24342..ac0292263796 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_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_accounts_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_accounts_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_accounts_v1.services.online_return_policy_service import pagers +from google.shopping.merchant_accounts_v1.services.online_return_policy_service import ( + pagers, +) +from google.shopping.merchant_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy -from .transports.base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, OnlineReturnPolicyServiceTransport from .transports.grpc import OnlineReturnPolicyServiceGrpcTransport from .transports.grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport from .transports.rest import OnlineReturnPolicyServiceRestTransport @@ -64,14 +82,18 @@ class OnlineReturnPolicyServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] _transport_registry["grpc"] = OnlineReturnPolicyServiceGrpcTransport _transport_registry["grpc_asyncio"] = OnlineReturnPolicyServiceGrpcAsyncIOTransport _transport_registry["rest"] = OnlineReturnPolicyServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[OnlineReturnPolicyServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[OnlineReturnPolicyServiceTransport]: """Returns an appropriate transport class. Args: @@ -96,9 +118,8 @@ class OnlineReturnPolicyServiceClient(metaclass=OnlineReturnPolicyServiceClientM ads and free listings programs. This API defines the following resource model: - -------------------------------------------------------- - `OnlineReturnPolicy `__ + - `OnlineReturnPolicy `__ """ @staticmethod @@ -171,8 +192,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: OnlineReturnPolicyServiceClient: 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) @@ -189,73 +209,106 @@ def transport(self) -> OnlineReturnPolicyServiceTransport: return self._transport @staticmethod - def online_return_policy_path(account: str,return_policy: str,) -> str: + def online_return_policy_path( + account: str, + return_policy: str, + ) -> str: """Returns a fully-qualified online_return_policy string.""" - return "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) + return "accounts/{account}/onlineReturnPolicies/{return_policy}".format( + account=account, + return_policy=return_policy, + ) @staticmethod - def parse_online_return_policy_path(path: str) -> Dict[str,str]: + def parse_online_return_policy_path(path: str) -> Dict[str, str]: """Parses a online_return_policy path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/onlineReturnPolicies/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/onlineReturnPolicies/(?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: @@ -287,16 +340,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 @@ -309,7 +368,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 @@ -330,13 +391,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 @@ -359,7 +426,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: @@ -375,17 +444,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 = OnlineReturnPolicyServiceClient._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 = OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + OnlineReturnPolicyServiceClient._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: @@ -421,15 +500,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 @@ -462,12 +544,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, OnlineReturnPolicyServiceTransport, Callable[..., OnlineReturnPolicyServiceTransport]]] = 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, + OnlineReturnPolicyServiceTransport, + Callable[..., OnlineReturnPolicyServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the online return policy service client. Args: @@ -522,14 +612,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 = OnlineReturnPolicyServiceClient._read_environment_variables() - self._client_cert_source = OnlineReturnPolicyServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = OnlineReturnPolicyServiceClient._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, + ) = OnlineReturnPolicyServiceClient._read_environment_variables() + self._client_cert_source = ( + OnlineReturnPolicyServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = OnlineReturnPolicyServiceClient._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 @@ -540,7 +642,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 @@ -549,8 +653,10 @@ def __init__(self, *, if transport_provided: # transport is a OnlineReturnPolicyServiceTransport 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 " @@ -559,20 +665,30 @@ def __init__(self, *, self._transport = cast(OnlineReturnPolicyServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - OnlineReturnPolicyServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or OnlineReturnPolicyServiceClient._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[OnlineReturnPolicyServiceTransport], Callable[..., OnlineReturnPolicyServiceTransport]] = ( + transport_init: Union[ + Type[OnlineReturnPolicyServiceTransport], + Callable[..., OnlineReturnPolicyServiceTransport], + ] = ( OnlineReturnPolicyServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., OnlineReturnPolicyServiceTransport], transport) @@ -591,28 +707,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.accounts_v1.OnlineReturnPolicyServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", - "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.accounts.v1.OnlineReturnPolicyService", "credentialsType": None, - } + }, ) - def get_online_return_policy(self, - request: Optional[Union[online_return_policy.GetOnlineReturnPolicyRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> online_return_policy.OnlineReturnPolicy: + def get_online_return_policy( + self, + request: Optional[ + Union[online_return_policy.GetOnlineReturnPolicyRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: r"""Gets an existing return policy for a given business. .. code-block:: python @@ -672,10 +799,14 @@ def sample_get_online_return_policy(): # - 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. @@ -693,9 +824,7 @@ def sample_get_online_return_policy(): # 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. @@ -712,14 +841,17 @@ def sample_get_online_return_policy(): # Done; return the response. return response - def list_online_return_policies(self, - request: Optional[Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesPager: + def list_online_return_policies( + self, + request: Optional[ + Union[online_return_policy.ListOnlineReturnPoliciesRequest, 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.ListOnlineReturnPoliciesPager: r"""Lists all existing return policies for a given business. @@ -782,14 +914,20 @@ def sample_list_online_return_policies(): # - 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. - if not isinstance(request, online_return_policy.ListOnlineReturnPoliciesRequest): + if not isinstance( + request, online_return_policy.ListOnlineReturnPoliciesRequest + ): request = online_return_policy.ListOnlineReturnPoliciesRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -798,14 +936,14 @@ def sample_list_online_return_policies(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_online_return_policies] + rpc = self._transport._wrapped_methods[ + self._transport.list_online_return_policies + ] # 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. @@ -833,15 +971,20 @@ def sample_list_online_return_policies(): # Done; return the response. return response - def create_online_return_policy(self, - request: Optional[Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict]] = None, - *, - parent: Optional[str] = None, - online_return_policy: Optional[gsma_online_return_policy.OnlineReturnPolicy] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_online_return_policy.OnlineReturnPolicy: + def create_online_return_policy( + self, + request: Optional[ + Union[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + online_return_policy: Optional[ + gsma_online_return_policy.OnlineReturnPolicy + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: r"""Creates a new return policy for a given business. .. code-block:: python @@ -913,14 +1056,20 @@ def sample_create_online_return_policy(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, online_return_policy] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be 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, gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + if not isinstance( + request, gsma_online_return_policy.CreateOnlineReturnPolicyRequest + ): request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -931,14 +1080,14 @@ def sample_create_online_return_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_online_return_policy] + rpc = self._transport._wrapped_methods[ + self._transport.create_online_return_policy + ] # 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. @@ -955,14 +1104,17 @@ def sample_create_online_return_policy(): # Done; return the response. return response - def delete_online_return_policy(self, - request: Optional[Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict]] = None, - *, - name: 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_online_return_policy( + self, + request: Optional[ + Union[online_return_policy.DeleteOnlineReturnPolicyRequest, dict] + ] = None, + *, + name: 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 an existing return policy. .. code-block:: python @@ -1012,14 +1164,20 @@ def sample_delete_online_return_policy(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, online_return_policy.DeleteOnlineReturnPolicyRequest): + if not isinstance( + request, online_return_policy.DeleteOnlineReturnPolicyRequest + ): request = online_return_policy.DeleteOnlineReturnPolicyRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1028,14 +1186,14 @@ def sample_delete_online_return_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_online_return_policy] + rpc = self._transport._wrapped_methods[ + self._transport.delete_online_return_policy + ] # 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. @@ -1063,16 +1221,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__ = ( - "OnlineReturnPolicyServiceClient", -) +__all__ = ("OnlineReturnPolicyServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py similarity index 77% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py index 8bd1d763b1bd..2c4c89c70090 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_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 ListOnlineReturnPoliciesPager: 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[..., online_return_policy.ListOnlineReturnPoliciesResponse], - request: online_return_policy.ListOnlineReturnPoliciesRequest, - response: online_return_policy.ListOnlineReturnPoliciesResponse, - *, - 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[..., online_return_policy.ListOnlineReturnPoliciesResponse], + request: online_return_policy.ListOnlineReturnPoliciesRequest, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + *, + 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[online_return_policy.ListOnlineReturnPoliciesRespons 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[online_return_policy.OnlineReturnPolicy]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[online_return_policy.OnlineReturnPolicy]: yield from page.online_return_policies 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 ListOnlineReturnPoliciesAsyncPager: @@ -112,14 +134,19 @@ class ListOnlineReturnPoliciesAsyncPager: 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[online_return_policy.ListOnlineReturnPoliciesResponse]], - request: online_return_policy.ListOnlineReturnPoliciesRequest, - response: online_return_policy.ListOnlineReturnPoliciesResponse, - *, - 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[online_return_policy.ListOnlineReturnPoliciesResponse] + ], + request: online_return_policy.ListOnlineReturnPoliciesRequest, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + *, + 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[online_return_policy.ListOnlineReturnPoliciesResponse]: + async def pages( + self, + ) -> AsyncIterator[online_return_policy.ListOnlineReturnPoliciesResponse]: 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[online_return_policy.OnlineReturnPolicy]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py index 406ed1cc95a3..321a182c11ae 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import OnlineReturnPolicyServiceTransport from .grpc import OnlineReturnPolicyServiceGrpcTransport from .grpc_asyncio import OnlineReturnPolicyServiceGrpcAsyncIOTransport -from .rest import OnlineReturnPolicyServiceRestTransport -from .rest import OnlineReturnPolicyServiceRestInterceptor - +from .rest import ( + OnlineReturnPolicyServiceRestInterceptor, + OnlineReturnPolicyServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] -_transport_registry['grpc'] = OnlineReturnPolicyServiceGrpcTransport -_transport_registry['grpc_asyncio'] = OnlineReturnPolicyServiceGrpcAsyncIOTransport -_transport_registry['rest'] = OnlineReturnPolicyServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[OnlineReturnPolicyServiceTransport]] +_transport_registry["grpc"] = OnlineReturnPolicyServiceGrpcTransport +_transport_registry["grpc_asyncio"] = OnlineReturnPolicyServiceGrpcAsyncIOTransport +_transport_registry["rest"] = OnlineReturnPolicyServiceRestTransport __all__ = ( - 'OnlineReturnPolicyServiceTransport', - 'OnlineReturnPolicyServiceGrpcTransport', - 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', - 'OnlineReturnPolicyServiceRestTransport', - 'OnlineReturnPolicyServiceRestInterceptor', + "OnlineReturnPolicyServiceTransport", + "OnlineReturnPolicyServiceGrpcTransport", + "OnlineReturnPolicyServiceGrpcAsyncIOTransport", + "OnlineReturnPolicyServiceRestTransport", + "OnlineReturnPolicyServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py similarity index 64% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py index a6176e61390f..91602e787a98 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/base.py @@ -16,22 +16,25 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version +from google.shopping.merchant_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -40,24 +43,23 @@ class OnlineReturnPolicyServiceTransport(abc.ABC): """Abstract transport class for OnlineReturnPolicyService.""" - 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: @@ -93,30 +95,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 @@ -146,51 +156,60 @@ 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 get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - Union[ - online_return_policy.OnlineReturnPolicy, - Awaitable[online_return_policy.OnlineReturnPolicy] - ]]: + def get_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + Union[ + online_return_policy.OnlineReturnPolicy, + Awaitable[online_return_policy.OnlineReturnPolicy], + ], + ]: raise NotImplementedError() @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - Union[ - online_return_policy.ListOnlineReturnPoliciesResponse, - Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse] - ]]: + def list_online_return_policies( + self, + ) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + Union[ + online_return_policy.ListOnlineReturnPoliciesResponse, + Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse], + ], + ]: raise NotImplementedError() @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - Union[ - gsma_online_return_policy.OnlineReturnPolicy, - Awaitable[gsma_online_return_policy.OnlineReturnPolicy] - ]]: + def create_online_return_policy( + self, + ) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + Union[ + gsma_online_return_policy.OnlineReturnPolicy, + Awaitable[gsma_online_return_policy.OnlineReturnPolicy], + ], + ]: raise NotImplementedError() @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property @@ -198,6 +217,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'OnlineReturnPolicyServiceTransport', -) +__all__ = ("OnlineReturnPolicyServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py index aa34b6df0792..6b2b261803c8 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc.py @@ -16,27 +16,29 @@ 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_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy -from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, OnlineReturnPolicyServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,7 +48,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -67,7 +71,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.accounts.v1.OnlineReturnPolicyService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,7 +82,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -93,7 +101,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.accounts.v1.OnlineReturnPolicyService", "rpcName": client_call_details.method, "response": grpc_response, @@ -111,9 +119,8 @@ class OnlineReturnPolicyServiceGrpcTransport(OnlineReturnPolicyServiceTransport) ads and free listings programs. This API defines the following resource model: - -------------------------------------------------------- - `OnlineReturnPolicy `__ + - `OnlineReturnPolicy `__ This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -122,23 +129,26 @@ class OnlineReturnPolicyServiceGrpcTransport(OnlineReturnPolicyServiceTransport) 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: @@ -260,19 +270,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. @@ -307,19 +321,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 get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - online_return_policy.OnlineReturnPolicy]: + def get_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + online_return_policy.OnlineReturnPolicy, + ]: r"""Return a callable for the get online return policy method over gRPC. Gets an existing return policy for a given business. @@ -334,18 +350,21 @@ def get_online_return_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_online_return_policy' not in self._stubs: - self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/GetOnlineReturnPolicy', + if "get_online_return_policy" not in self._stubs: + self._stubs["get_online_return_policy"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/GetOnlineReturnPolicy", request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, ) - return self._stubs['get_online_return_policy'] + return self._stubs["get_online_return_policy"] @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - online_return_policy.ListOnlineReturnPoliciesResponse]: + def list_online_return_policies( + self, + ) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + online_return_policy.ListOnlineReturnPoliciesResponse, + ]: r"""Return a callable for the list online return policies method over gRPC. Lists all existing return policies for a given @@ -361,18 +380,23 @@ def list_online_return_policies(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_online_return_policies' not in self._stubs: - self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/ListOnlineReturnPolicies', + if "list_online_return_policies" not in self._stubs: + self._stubs[ + "list_online_return_policies" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/ListOnlineReturnPolicies", request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, ) - return self._stubs['list_online_return_policies'] + return self._stubs["list_online_return_policies"] @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - gsma_online_return_policy.OnlineReturnPolicy]: + def create_online_return_policy( + self, + ) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy, + ]: r"""Return a callable for the create online return policy method over gRPC. Creates a new return policy for a given business. @@ -387,18 +411,22 @@ def create_online_return_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_online_return_policy' not in self._stubs: - self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/CreateOnlineReturnPolicy', + if "create_online_return_policy" not in self._stubs: + self._stubs[ + "create_online_return_policy" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/CreateOnlineReturnPolicy", request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, ) - return self._stubs['create_online_return_policy'] + return self._stubs["create_online_return_policy"] @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - empty_pb2.Empty]: + def delete_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete online return policy method over gRPC. Deletes an existing return policy. @@ -413,13 +441,15 @@ def delete_online_return_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_online_return_policy' not in self._stubs: - self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', + if "delete_online_return_policy" not in self._stubs: + self._stubs[ + "delete_online_return_policy" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/DeleteOnlineReturnPolicy", request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_online_return_policy'] + return self._stubs["delete_online_return_policy"] def close(self): self._logged_channel.close() @@ -429,6 +459,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'OnlineReturnPolicyServiceGrpcTransport', -) +__all__ = ("OnlineReturnPolicyServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py index eb982dc7694b..6358df4562f2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/grpc_asyncio.py @@ -15,32 +15,34 @@ # 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_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy -from .base import OnlineReturnPolicyServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, OnlineReturnPolicyServiceTransport from .grpc import OnlineReturnPolicyServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -48,9 +50,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -71,7 +77,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.accounts.v1.OnlineReturnPolicyService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -82,7 +88,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -97,7 +107,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.accounts.v1.OnlineReturnPolicyService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -115,9 +125,8 @@ class OnlineReturnPolicyServiceGrpcAsyncIOTransport(OnlineReturnPolicyServiceTra ads and free listings programs. This API defines the following resource model: - -------------------------------------------------------- - `OnlineReturnPolicy `__ + - `OnlineReturnPolicy `__ This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation @@ -131,13 +140,15 @@ class OnlineReturnPolicyServiceGrpcAsyncIOTransport(OnlineReturnPolicyServiceTra _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. @@ -167,24 +178,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: @@ -308,7 +321,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) @@ -323,9 +338,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - Awaitable[online_return_policy.OnlineReturnPolicy]]: + def get_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + Awaitable[online_return_policy.OnlineReturnPolicy], + ]: r"""Return a callable for the get online return policy method over gRPC. Gets an existing return policy for a given business. @@ -340,18 +358,21 @@ def get_online_return_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_online_return_policy' not in self._stubs: - self._stubs['get_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/GetOnlineReturnPolicy', + if "get_online_return_policy" not in self._stubs: + self._stubs["get_online_return_policy"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/GetOnlineReturnPolicy", request_serializer=online_return_policy.GetOnlineReturnPolicyRequest.serialize, response_deserializer=online_return_policy.OnlineReturnPolicy.deserialize, ) - return self._stubs['get_online_return_policy'] + return self._stubs["get_online_return_policy"] @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse]]: + def list_online_return_policies( + self, + ) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + Awaitable[online_return_policy.ListOnlineReturnPoliciesResponse], + ]: r"""Return a callable for the list online return policies method over gRPC. Lists all existing return policies for a given @@ -367,18 +388,23 @@ def list_online_return_policies(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_online_return_policies' not in self._stubs: - self._stubs['list_online_return_policies'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/ListOnlineReturnPolicies', + if "list_online_return_policies" not in self._stubs: + self._stubs[ + "list_online_return_policies" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/ListOnlineReturnPolicies", request_serializer=online_return_policy.ListOnlineReturnPoliciesRequest.serialize, response_deserializer=online_return_policy.ListOnlineReturnPoliciesResponse.deserialize, ) - return self._stubs['list_online_return_policies'] + return self._stubs["list_online_return_policies"] @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - Awaitable[gsma_online_return_policy.OnlineReturnPolicy]]: + def create_online_return_policy( + self, + ) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + Awaitable[gsma_online_return_policy.OnlineReturnPolicy], + ]: r"""Return a callable for the create online return policy method over gRPC. Creates a new return policy for a given business. @@ -393,18 +419,23 @@ def create_online_return_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_online_return_policy' not in self._stubs: - self._stubs['create_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/CreateOnlineReturnPolicy', + if "create_online_return_policy" not in self._stubs: + self._stubs[ + "create_online_return_policy" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/CreateOnlineReturnPolicy", request_serializer=gsma_online_return_policy.CreateOnlineReturnPolicyRequest.serialize, response_deserializer=gsma_online_return_policy.OnlineReturnPolicy.deserialize, ) - return self._stubs['create_online_return_policy'] + return self._stubs["create_online_return_policy"] @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - Awaitable[empty_pb2.Empty]]: + def delete_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], + Awaitable[empty_pb2.Empty], + ]: r"""Return a callable for the delete online return policy method over gRPC. Deletes an existing return policy. @@ -419,16 +450,18 @@ def delete_online_return_policy(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_online_return_policy' not in self._stubs: - self._stubs['delete_online_return_policy'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/DeleteOnlineReturnPolicy', + if "delete_online_return_policy" not in self._stubs: + self._stubs[ + "delete_online_return_policy" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.OnlineReturnPolicyService/DeleteOnlineReturnPolicy", request_serializer=online_return_policy.DeleteOnlineReturnPolicyRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_online_return_policy'] + return self._stubs["delete_online_return_policy"] 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.get_online_return_policy: self._wrap_method( self.get_online_return_policy, @@ -465,6 +498,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'OnlineReturnPolicyServiceGrpcAsyncIOTransport', -) +__all__ = ("OnlineReturnPolicyServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py similarity index 61% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py index c1f3e011bc04..9aa2baa0d80c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest.py @@ -13,33 +13,29 @@ # 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_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy - -from .rest_base import _BaseOnlineReturnPolicyServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseOnlineReturnPolicyServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -48,6 +44,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -112,7 +109,15 @@ def post_list_online_return_policies(self, response): """ - def pre_create_online_return_policy(self, request: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.CreateOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_online_return_policy( + self, + request: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_online_return_policy Override in a subclass to manipulate the request or metadata @@ -120,7 +125,9 @@ def pre_create_online_return_policy(self, request: gsma_online_return_policy.Cre """ return request, metadata - def post_create_online_return_policy(self, response: gsma_online_return_policy.OnlineReturnPolicy) -> gsma_online_return_policy.OnlineReturnPolicy: + def post_create_online_return_policy( + self, response: gsma_online_return_policy.OnlineReturnPolicy + ) -> gsma_online_return_policy.OnlineReturnPolicy: """Post-rpc interceptor for create_online_return_policy DEPRECATED. Please use the `post_create_online_return_policy_with_metadata` @@ -133,7 +140,14 @@ def post_create_online_return_policy(self, response: gsma_online_return_policy.O """ return response - def post_create_online_return_policy_with_metadata(self, response: gsma_online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_online_return_policy_with_metadata( + self, + response: gsma_online_return_policy.OnlineReturnPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gsma_online_return_policy.OnlineReturnPolicy, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for create_online_return_policy Override in a subclass to read or manipulate the response or metadata after it @@ -148,7 +162,14 @@ def post_create_online_return_policy_with_metadata(self, response: gsma_online_r """ return response, metadata - def pre_delete_online_return_policy(self, request: online_return_policy.DeleteOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.DeleteOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_online_return_policy( + self, + request: online_return_policy.DeleteOnlineReturnPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + online_return_policy.DeleteOnlineReturnPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for delete_online_return_policy Override in a subclass to manipulate the request or metadata @@ -156,7 +177,14 @@ def pre_delete_online_return_policy(self, request: online_return_policy.DeleteOn """ return request, metadata - def pre_get_online_return_policy(self, request: online_return_policy.GetOnlineReturnPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.GetOnlineReturnPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_online_return_policy( + self, + request: online_return_policy.GetOnlineReturnPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + online_return_policy.GetOnlineReturnPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_online_return_policy Override in a subclass to manipulate the request or metadata @@ -164,7 +192,9 @@ def pre_get_online_return_policy(self, request: online_return_policy.GetOnlineRe """ return request, metadata - def post_get_online_return_policy(self, response: online_return_policy.OnlineReturnPolicy) -> online_return_policy.OnlineReturnPolicy: + def post_get_online_return_policy( + self, response: online_return_policy.OnlineReturnPolicy + ) -> online_return_policy.OnlineReturnPolicy: """Post-rpc interceptor for get_online_return_policy DEPRECATED. Please use the `post_get_online_return_policy_with_metadata` @@ -177,7 +207,13 @@ def post_get_online_return_policy(self, response: online_return_policy.OnlineRet """ return response - def post_get_online_return_policy_with_metadata(self, response: online_return_policy.OnlineReturnPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_online_return_policy_with_metadata( + self, + response: online_return_policy.OnlineReturnPolicy, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + online_return_policy.OnlineReturnPolicy, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_online_return_policy Override in a subclass to read or manipulate the response or metadata after it @@ -192,7 +228,14 @@ def post_get_online_return_policy_with_metadata(self, response: online_return_po """ return response, metadata - def pre_list_online_return_policies(self, request: online_return_policy.ListOnlineReturnPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_online_return_policies( + self, + request: online_return_policy.ListOnlineReturnPoliciesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + online_return_policy.ListOnlineReturnPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_online_return_policies Override in a subclass to manipulate the request or metadata @@ -200,7 +243,9 @@ def pre_list_online_return_policies(self, request: online_return_policy.ListOnli """ return request, metadata - def post_list_online_return_policies(self, response: online_return_policy.ListOnlineReturnPoliciesResponse) -> online_return_policy.ListOnlineReturnPoliciesResponse: + def post_list_online_return_policies( + self, response: online_return_policy.ListOnlineReturnPoliciesResponse + ) -> online_return_policy.ListOnlineReturnPoliciesResponse: """Post-rpc interceptor for list_online_return_policies DEPRECATED. Please use the `post_list_online_return_policies_with_metadata` @@ -213,7 +258,14 @@ def post_list_online_return_policies(self, response: online_return_policy.ListOn """ return response - def post_list_online_return_policies_with_metadata(self, response: online_return_policy.ListOnlineReturnPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[online_return_policy.ListOnlineReturnPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_online_return_policies_with_metadata( + self, + response: online_return_policy.ListOnlineReturnPoliciesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + online_return_policy.ListOnlineReturnPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for list_online_return_policies Override in a subclass to read or manipulate the response or metadata after it @@ -236,7 +288,9 @@ class OnlineReturnPolicyServiceRestStub: _interceptor: OnlineReturnPolicyServiceRestInterceptor -class OnlineReturnPolicyServiceRestTransport(_BaseOnlineReturnPolicyServiceRestTransport): +class OnlineReturnPolicyServiceRestTransport( + _BaseOnlineReturnPolicyServiceRestTransport +): """REST backend synchronous transport for OnlineReturnPolicyService. The service facilitates the management of a business's remorse @@ -255,20 +309,21 @@ class OnlineReturnPolicyServiceRestTransport(_BaseOnlineReturnPolicyServiceRestT 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[OnlineReturnPolicyServiceRestInterceptor] = 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[OnlineReturnPolicyServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -311,18 +366,24 @@ 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 OnlineReturnPolicyServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + class _CreateOnlineReturnPolicy( + _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy, + OnlineReturnPolicyServiceRestStub, + ): def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.CreateOnlineReturnPolicy") + return hash( + "OnlineReturnPolicyServiceRestTransport.CreateOnlineReturnPolicy" + ) @staticmethod def _get_response( @@ -332,77 +393,93 @@ 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: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_online_return_policy.OnlineReturnPolicy: + def __call__( + self, + request: gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_online_return_policy.OnlineReturnPolicy: r"""Call the create online return - policy method over HTTP. - - Args: - request (~.gsma_online_return_policy.CreateOnlineReturnPolicyRequest): - The request object. Request message for the ``CreateOnlineReturnPolicy`` - 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: - ~.gsma_online_return_policy.OnlineReturnPolicy: - `Online return - policy `__ - object. This is currently used to represent return - policies for ads and free listings programs. + policy method over HTTP. + + Args: + request (~.gsma_online_return_policy.CreateOnlineReturnPolicyRequest): + The request object. Request message for the ``CreateOnlineReturnPolicy`` + 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: + ~.gsma_online_return_policy.OnlineReturnPolicy: + `Online return + policy `__ + object. This is currently used to represent return + policies for ads and free listings programs. """ - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_http_options() + http_options = ( + _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_http_options() + ) - request, metadata = self._interceptor.pre_create_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_create_online_return_policy( + request, metadata + ) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_transcoded_request( + http_options, request + ) - body = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_request_body_json(transcoded_request) + body = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.CreateOnlineReturnPolicy", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "CreateOnlineReturnPolicy", "httpRequest": http_request, @@ -411,7 +488,15 @@ def __call__(self, ) # Send the request - response = OnlineReturnPolicyServiceRestTransport._CreateOnlineReturnPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = OnlineReturnPolicyServiceRestTransport._CreateOnlineReturnPolicy._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. @@ -426,20 +511,26 @@ def __call__(self, resp = self._interceptor.post_create_online_return_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_online_return_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_online_return_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = gsma_online_return_policy.OnlineReturnPolicy.to_json(response) + response_payload = ( + gsma_online_return_policy.OnlineReturnPolicy.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.accounts_v1.OnlineReturnPolicyServiceClient.create_online_return_policy", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "CreateOnlineReturnPolicy", "metadata": http_response["headers"], @@ -448,9 +539,14 @@ def __call__(self, ) return resp - class _DeleteOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + class _DeleteOnlineReturnPolicy( + _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy, + OnlineReturnPolicyServiceRestStub, + ): def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.DeleteOnlineReturnPolicy") + return hash( + "OnlineReturnPolicyServiceRestTransport.DeleteOnlineReturnPolicy" + ) @staticmethod def _get_response( @@ -460,66 +556,80 @@ 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: online_return_policy.DeleteOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: online_return_policy.DeleteOnlineReturnPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete online return - policy method over HTTP. - - Args: - request (~.online_return_policy.DeleteOnlineReturnPolicyRequest): - The request object. Request message for the ``DeleteOnlineReturnPolicy`` - 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`. + policy method over HTTP. + + Args: + request (~.online_return_policy.DeleteOnlineReturnPolicyRequest): + The request object. Request message for the ``DeleteOnlineReturnPolicy`` + 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_http_options() + http_options = ( + _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_http_options() + ) - request, metadata = self._interceptor.pre_delete_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_delete_online_return_policy( + request, metadata + ) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.DeleteOnlineReturnPolicy", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "DeleteOnlineReturnPolicy", "httpRequest": http_request, @@ -528,14 +638,24 @@ def __call__(self, ) # Send the request - response = OnlineReturnPolicyServiceRestTransport._DeleteOnlineReturnPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OnlineReturnPolicyServiceRestTransport._DeleteOnlineReturnPolicy._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 _GetOnlineReturnPolicy(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy, OnlineReturnPolicyServiceRestStub): + class _GetOnlineReturnPolicy( + _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy, + OnlineReturnPolicyServiceRestStub, + ): def __hash__(self): return hash("OnlineReturnPolicyServiceRestTransport.GetOnlineReturnPolicy") @@ -547,26 +667,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: online_return_policy.GetOnlineReturnPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> online_return_policy.OnlineReturnPolicy: + def __call__( + self, + request: online_return_policy.GetOnlineReturnPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.OnlineReturnPolicy: r"""Call the get online return policy method over HTTP. Args: @@ -590,30 +712,42 @@ def __call__(self, """ - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_http_options() + http_options = ( + _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_http_options() + ) - request, metadata = self._interceptor.pre_get_online_return_policy(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_online_return_policy( + request, metadata + ) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.GetOnlineReturnPolicy", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "GetOnlineReturnPolicy", "httpRequest": http_request, @@ -622,7 +756,14 @@ def __call__(self, ) # Send the request - response = OnlineReturnPolicyServiceRestTransport._GetOnlineReturnPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OnlineReturnPolicyServiceRestTransport._GetOnlineReturnPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -637,20 +778,26 @@ def __call__(self, resp = self._interceptor.post_get_online_return_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_online_return_policy_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_online_return_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = online_return_policy.OnlineReturnPolicy.to_json(response) + response_payload = online_return_policy.OnlineReturnPolicy.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.accounts_v1.OnlineReturnPolicyServiceClient.get_online_return_policy", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "GetOnlineReturnPolicy", "metadata": http_response["headers"], @@ -659,9 +806,14 @@ def __call__(self, ) return resp - class _ListOnlineReturnPolicies(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies, OnlineReturnPolicyServiceRestStub): + class _ListOnlineReturnPolicies( + _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies, + OnlineReturnPolicyServiceRestStub, + ): def __hash__(self): - return hash("OnlineReturnPolicyServiceRestTransport.ListOnlineReturnPolicies") + return hash( + "OnlineReturnPolicyServiceRestTransport.ListOnlineReturnPolicies" + ) @staticmethod def _get_response( @@ -671,72 +823,86 @@ 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: online_return_policy.ListOnlineReturnPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> online_return_policy.ListOnlineReturnPoliciesResponse: + def __call__( + self, + request: online_return_policy.ListOnlineReturnPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> online_return_policy.ListOnlineReturnPoliciesResponse: r"""Call the list online return - policies method over HTTP. - - Args: - request (~.online_return_policy.ListOnlineReturnPoliciesRequest): - The request object. Request message for the ``ListOnlineReturnPolicies`` - 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: - ~.online_return_policy.ListOnlineReturnPoliciesResponse: - Response message for the ``ListOnlineReturnPolicies`` - method. + policies method over HTTP. + + Args: + request (~.online_return_policy.ListOnlineReturnPoliciesRequest): + The request object. Request message for the ``ListOnlineReturnPolicies`` + 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: + ~.online_return_policy.ListOnlineReturnPoliciesResponse: + Response message for the ``ListOnlineReturnPolicies`` + method. """ - http_options = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_http_options() + http_options = ( + _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_http_options() + ) - request, metadata = self._interceptor.pre_list_online_return_policies(request, metadata) - transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_list_online_return_policies( + request, metadata + ) + transcoded_request = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.OnlineReturnPolicyServiceClient.ListOnlineReturnPolicies", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "ListOnlineReturnPolicies", "httpRequest": http_request, @@ -745,7 +911,14 @@ def __call__(self, ) # Send the request - response = OnlineReturnPolicyServiceRestTransport._ListOnlineReturnPolicies._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = OnlineReturnPolicyServiceRestTransport._ListOnlineReturnPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -760,20 +933,28 @@ def __call__(self, resp = self._interceptor.post_list_online_return_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_online_return_policies_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_online_return_policies_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = online_return_policy.ListOnlineReturnPoliciesResponse.to_json(response) + response_payload = ( + online_return_policy.ListOnlineReturnPoliciesResponse.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.accounts_v1.OnlineReturnPolicyServiceClient.list_online_return_policies", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.OnlineReturnPolicyService", "rpcName": "ListOnlineReturnPolicies", "metadata": http_response["headers"], @@ -783,36 +964,47 @@ def __call__(self, return resp @property - def create_online_return_policy(self) -> Callable[ - [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], - gsma_online_return_policy.OnlineReturnPolicy]: + def create_online_return_policy( + self, + ) -> Callable[ + [gsma_online_return_policy.CreateOnlineReturnPolicyRequest], + gsma_online_return_policy.OnlineReturnPolicy, + ]: # 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._CreateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._CreateOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore @property - def delete_online_return_policy(self) -> Callable[ - [online_return_policy.DeleteOnlineReturnPolicyRequest], - empty_pb2.Empty]: + def delete_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.DeleteOnlineReturnPolicyRequest], 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._DeleteOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore @property - def get_online_return_policy(self) -> Callable[ - [online_return_policy.GetOnlineReturnPolicyRequest], - online_return_policy.OnlineReturnPolicy]: + def get_online_return_policy( + self, + ) -> Callable[ + [online_return_policy.GetOnlineReturnPolicyRequest], + online_return_policy.OnlineReturnPolicy, + ]: # 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._GetOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore + return self._GetOnlineReturnPolicy(self._session, self._host, self._interceptor) # type: ignore @property - def list_online_return_policies(self) -> Callable[ - [online_return_policy.ListOnlineReturnPoliciesRequest], - online_return_policy.ListOnlineReturnPoliciesResponse]: + def list_online_return_policies( + self, + ) -> Callable[ + [online_return_policy.ListOnlineReturnPoliciesRequest], + online_return_policy.ListOnlineReturnPoliciesResponse, + ]: # 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._ListOnlineReturnPolicies(self._session, self._host, self._interceptor) # type: ignore + return self._ListOnlineReturnPolicies(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -822,6 +1014,4 @@ def close(self): self._session.close() -__all__=( - 'OnlineReturnPolicyServiceRestTransport', -) +__all__ = ("OnlineReturnPolicyServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py index 38fdb9520846..1f0d28ff13a0 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/online_return_policy_service/transports/rest_base.py @@ -14,19 +14,19 @@ # limitations under the License. # import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import OnlineReturnPolicyServiceTransport, 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_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy + +from .base import DEFAULT_CLIENT_INFO, OnlineReturnPolicyServiceTransport class _BaseOnlineReturnPolicyServiceRestTransport(OnlineReturnPolicyServiceTransport): @@ -42,14 +42,16 @@ class _BaseOnlineReturnPolicyServiceRestTransport(OnlineReturnPolicyServiceTrans 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]): @@ -73,7 +75,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -84,33 +88,39 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseCreateOnlineReturnPolicy: 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': '/accounts/v1/{parent=accounts/*}/onlineReturnPolicies', - 'body': 'online_return_policy', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/onlineReturnPolicies", + "body": "online_return_policy", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb(request) + pb_request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb( + request + ) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -119,17 +129,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(_BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._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( + _BaseOnlineReturnPolicyServiceRestTransport._BaseCreateOnlineReturnPolicy._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -138,35 +154,47 @@ class _BaseDeleteOnlineReturnPolicy: 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': '/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = online_return_policy.DeleteOnlineReturnPolicyRequest.pb(request) + pb_request = online_return_policy.DeleteOnlineReturnPolicyRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._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( + _BaseOnlineReturnPolicyServiceRestTransport._BaseDeleteOnlineReturnPolicy._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -175,19 +203,23 @@ class _BaseGetOnlineReturnPolicy: 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': '/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}", + }, ] return http_options @@ -199,11 +231,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(_BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._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( + _BaseOnlineReturnPolicyServiceRestTransport._BaseGetOnlineReturnPolicy._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -212,40 +250,50 @@ class _BaseListOnlineReturnPolicies: 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': '/accounts/v1/{parent=accounts/*}/onlineReturnPolicies', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/onlineReturnPolicies", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = online_return_policy.ListOnlineReturnPoliciesRequest.pb(request) + pb_request = online_return_policy.ListOnlineReturnPoliciesRequest.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(_BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._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( + _BaseOnlineReturnPolicyServiceRestTransport._BaseListOnlineReturnPolicies._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseOnlineReturnPolicyServiceRestTransport', -) +__all__ = ("_BaseOnlineReturnPolicyServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py similarity index 91% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py index 400e3ec082c8..30323546c079 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import ProgramsServiceClient from .async_client import ProgramsServiceAsyncClient +from .client import ProgramsServiceClient __all__ = ( - 'ProgramsServiceClient', - 'ProgramsServiceAsyncClient', + "ProgramsServiceClient", + "ProgramsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py index a51835cd13d2..a3d5da7ee6a2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -36,18 +46,21 @@ from google.shopping.merchant_accounts_v1.services.programs_service import pagers from google.shopping.merchant_accounts_v1.types import programs -from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport + from .client import ProgramsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, ProgramsServiceTransport +from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport 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 ProgramsServiceAsyncClient: """Service for program management. @@ -73,16 +86,30 @@ class ProgramsServiceAsyncClient: program_path = staticmethod(ProgramsServiceClient.program_path) parse_program_path = staticmethod(ProgramsServiceClient.parse_program_path) - common_billing_account_path = staticmethod(ProgramsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProgramsServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + ProgramsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ProgramsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(ProgramsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ProgramsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ProgramsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ProgramsServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + ProgramsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + ProgramsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + ProgramsServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(ProgramsServiceClient.common_project_path) - parse_common_project_path = staticmethod(ProgramsServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + ProgramsServiceClient.parse_common_project_path + ) common_location_path = staticmethod(ProgramsServiceClient.common_location_path) - parse_common_location_path = staticmethod(ProgramsServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + ProgramsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -118,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: @@ -181,12 +210,18 @@ def universe_domain(self) -> str: get_transport_class = ProgramsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = "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, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the programs service async client. Args: @@ -241,31 +276,39 @@ 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.accounts_v1.ProgramsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", - "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.accounts.v1.ProgramsService", "credentialsType": None, - } + }, ) - async def get_program(self, - request: Optional[Union[programs.GetProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: + async def get_program( + self, + request: Optional[Union[programs.GetProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Retrieves the specified program for the account. .. code-block:: python @@ -338,10 +381,14 @@ async def sample_get_program(): # - 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. @@ -355,14 +402,14 @@ async def sample_get_program(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_program] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_program + ] # 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. @@ -379,14 +426,15 @@ async def sample_get_program(): # Done; return the response. return response - async def list_programs(self, - request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsAsyncPager: + async def list_programs( + self, + request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsAsyncPager: r"""Retrieves all programs for the account. .. code-block:: python @@ -448,10 +496,14 @@ async def sample_list_programs(): # - 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. @@ -465,14 +517,14 @@ async def sample_list_programs(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_programs] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_programs + ] # 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. @@ -500,14 +552,15 @@ async def sample_list_programs(): # Done; return the response. return response - async def enable_program(self, - request: Optional[Union[programs.EnableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: + async def enable_program( + self, + request: Optional[Union[programs.EnableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Enable participation in the specified program for the account. @@ -582,10 +635,14 @@ async def sample_enable_program(): # - 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. @@ -599,14 +656,14 @@ async def sample_enable_program(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.enable_program] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.enable_program + ] # 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. @@ -623,14 +680,15 @@ async def sample_enable_program(): # Done; return the response. return response - async def disable_program(self, - request: Optional[Union[programs.DisableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: + async def disable_program( + self, + request: Optional[Union[programs.DisableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Disable participation in the specified program for the account. @@ -705,10 +763,14 @@ async def sample_disable_program(): # - 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. @@ -722,14 +784,14 @@ async def sample_disable_program(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.disable_program] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.disable_program + ] # 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. @@ -752,12 +814,13 @@ async def __aenter__(self) -> "ProgramsServiceAsyncClient": 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__ = ( - "ProgramsServiceAsyncClient", -) +__all__ = ("ProgramsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/client.py index 0a008e79e355..e1a9316dca9f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,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 @@ -50,7 +63,8 @@ from google.shopping.merchant_accounts_v1.services.programs_service import pagers from google.shopping.merchant_accounts_v1.types import programs -from .transports.base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ProgramsServiceTransport from .transports.grpc import ProgramsServiceGrpcTransport from .transports.grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport from .transports.rest import ProgramsServiceRestTransport @@ -63,14 +77,18 @@ class ProgramsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ProgramsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ProgramsServiceTransport]] _transport_registry["grpc"] = ProgramsServiceGrpcTransport _transport_registry["grpc_asyncio"] = ProgramsServiceGrpcAsyncIOTransport _transport_registry["rest"] = ProgramsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ProgramsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ProgramsServiceTransport]: """Returns an appropriate transport class. Args: @@ -173,8 +191,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ProgramsServiceClient: 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) @@ -191,73 +208,103 @@ def transport(self) -> ProgramsServiceTransport: return self._transport @staticmethod - def program_path(account: str,program: str,) -> str: + def program_path( + account: str, + program: str, + ) -> str: """Returns a fully-qualified program string.""" - return "accounts/{account}/programs/{program}".format(account=account, program=program, ) + return "accounts/{account}/programs/{program}".format( + account=account, + program=program, + ) @staticmethod - def parse_program_path(path: str) -> Dict[str,str]: + def parse_program_path(path: str) -> Dict[str, str]: """Parses a program path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/programs/(?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: @@ -289,16 +336,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 @@ -311,7 +364,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 @@ -332,13 +387,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 @@ -361,7 +422,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: @@ -377,17 +440,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = ProgramsServiceClient._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 = ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ProgramsServiceClient._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: @@ -423,15 +494,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 @@ -464,12 +538,18 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport]]] = 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, ProgramsServiceTransport, Callable[..., ProgramsServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the programs service client. Args: @@ -524,14 +604,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 = ProgramsServiceClient._read_environment_variables() - self._client_cert_source = ProgramsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ProgramsServiceClient._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, + ) = ProgramsServiceClient._read_environment_variables() + self._client_cert_source = ProgramsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ProgramsServiceClient._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 @@ -542,7 +632,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 @@ -551,8 +643,10 @@ def __init__(self, *, if transport_provided: # transport is a ProgramsServiceTransport 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 " @@ -561,20 +655,29 @@ def __init__(self, *, self._transport = cast(ProgramsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - ProgramsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or ProgramsServiceClient._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[ProgramsServiceTransport], Callable[..., ProgramsServiceTransport]] = ( + transport_init: Union[ + Type[ProgramsServiceTransport], Callable[..., ProgramsServiceTransport] + ] = ( ProgramsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ProgramsServiceTransport], transport) @@ -593,28 +696,37 @@ 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.accounts_v1.ProgramsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", - "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.accounts.v1.ProgramsService", "credentialsType": None, - } + }, ) - def get_program(self, - request: Optional[Union[programs.GetProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: + def get_program( + self, + request: Optional[Union[programs.GetProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Retrieves the specified program for the account. .. code-block:: python @@ -687,10 +799,14 @@ def sample_get_program(): # - 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. @@ -708,9 +824,7 @@ def sample_get_program(): # 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. @@ -727,14 +841,15 @@ def sample_get_program(): # Done; return the response. return response - def list_programs(self, - request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsPager: + def list_programs( + self, + request: Optional[Union[programs.ListProgramsRequest, 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.ListProgramsPager: r"""Retrieves all programs for the account. .. code-block:: python @@ -796,10 +911,14 @@ def sample_list_programs(): # - 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. @@ -817,9 +936,7 @@ def sample_list_programs(): # 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. @@ -847,14 +964,15 @@ def sample_list_programs(): # Done; return the response. return response - def enable_program(self, - request: Optional[Union[programs.EnableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: + def enable_program( + self, + request: Optional[Union[programs.EnableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Enable participation in the specified program for the account. @@ -929,10 +1047,14 @@ def sample_enable_program(): # - 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. @@ -950,9 +1072,7 @@ def sample_enable_program(): # 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. @@ -969,14 +1089,15 @@ def sample_enable_program(): # Done; return the response. return response - def disable_program(self, - request: Optional[Union[programs.DisableProgramRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> programs.Program: + def disable_program( + self, + request: Optional[Union[programs.DisableProgramRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Disable participation in the specified program for the account. @@ -1051,10 +1172,14 @@ def sample_disable_program(): # - 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. @@ -1072,9 +1197,7 @@ def sample_disable_program(): # 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. @@ -1105,16 +1228,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__ = ( - "ProgramsServiceClient", -) +__all__ = ("ProgramsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py index 6fa0359f8ad0..0223651001d1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_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 ListProgramsPager: 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[..., programs.ListProgramsResponse], - request: programs.ListProgramsRequest, - response: programs.ListProgramsResponse, - *, - 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[..., programs.ListProgramsResponse], + request: programs.ListProgramsRequest, + response: programs.ListProgramsResponse, + *, + 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[programs.ListProgramsResponse]: 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[programs.Program]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[programs.Program]: yield from page.programs 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 ListProgramsAsyncPager: @@ -112,14 +134,17 @@ class ListProgramsAsyncPager: 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[programs.ListProgramsResponse]], - request: programs.ListProgramsRequest, - response: programs.ListProgramsResponse, - *, - 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[programs.ListProgramsResponse]], + request: programs.ListProgramsRequest, + response: programs.ListProgramsResponse, + *, + 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[programs.ListProgramsResponse]: 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[programs.Program]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py index dc803437b5a1..9a274b14f358 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/programs_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import ProgramsServiceTransport from .grpc import ProgramsServiceGrpcTransport from .grpc_asyncio import ProgramsServiceGrpcAsyncIOTransport -from .rest import ProgramsServiceRestTransport -from .rest import ProgramsServiceRestInterceptor - +from .rest import ProgramsServiceRestInterceptor, ProgramsServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[ProgramsServiceTransport]] -_transport_registry['grpc'] = ProgramsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ProgramsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ProgramsServiceRestTransport +_transport_registry["grpc"] = ProgramsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ProgramsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ProgramsServiceRestTransport __all__ = ( - 'ProgramsServiceTransport', - 'ProgramsServiceGrpcTransport', - 'ProgramsServiceGrpcAsyncIOTransport', - 'ProgramsServiceRestTransport', - 'ProgramsServiceRestInterceptor', + "ProgramsServiceTransport", + "ProgramsServiceGrpcTransport", + "ProgramsServiceGrpcAsyncIOTransport", + "ProgramsServiceRestTransport", + "ProgramsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py index 638318303da2..f18095b89cc5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import programs -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__ @@ -38,24 +39,23 @@ class ProgramsServiceTransport(abc.ABC): """Abstract transport class for ProgramsService.""" - 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: @@ -91,30 +91,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 @@ -144,51 +152,51 @@ 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 get_program(self) -> Callable[ - [programs.GetProgramRequest], - Union[ - programs.Program, - Awaitable[programs.Program] - ]]: + def get_program( + self, + ) -> Callable[ + [programs.GetProgramRequest], + Union[programs.Program, Awaitable[programs.Program]], + ]: raise NotImplementedError() @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - Union[ - programs.ListProgramsResponse, - Awaitable[programs.ListProgramsResponse] - ]]: + def list_programs( + self, + ) -> Callable[ + [programs.ListProgramsRequest], + Union[programs.ListProgramsResponse, Awaitable[programs.ListProgramsResponse]], + ]: raise NotImplementedError() @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - Union[ - programs.Program, - Awaitable[programs.Program] - ]]: + def enable_program( + self, + ) -> Callable[ + [programs.EnableProgramRequest], + Union[programs.Program, Awaitable[programs.Program]], + ]: raise NotImplementedError() @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - Union[ - programs.Program, - Awaitable[programs.Program] - ]]: + def disable_program( + self, + ) -> Callable[ + [programs.DisableProgramRequest], + Union[programs.Program, Awaitable[programs.Program]], + ]: raise NotImplementedError() @property @@ -196,6 +204,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'ProgramsServiceTransport', -) +__all__ = ("ProgramsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py index 0b38768d78c0..de80bd2dadef 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import programs -from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, ProgramsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -123,23 +129,26 @@ class ProgramsServiceGrpcTransport(ProgramsServiceTransport): 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: @@ -261,19 +270,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. @@ -308,19 +321,16 @@ 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 get_program(self) -> Callable[ - [programs.GetProgramRequest], - programs.Program]: + def get_program(self) -> Callable[[programs.GetProgramRequest], programs.Program]: r"""Return a callable for the get program method over gRPC. Retrieves the specified program for the account. @@ -335,18 +345,18 @@ def get_program(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_program' not in self._stubs: - self._stubs['get_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/GetProgram', + if "get_program" not in self._stubs: + self._stubs["get_program"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/GetProgram", request_serializer=programs.GetProgramRequest.serialize, response_deserializer=programs.Program.deserialize, ) - return self._stubs['get_program'] + return self._stubs["get_program"] @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - programs.ListProgramsResponse]: + def list_programs( + self, + ) -> Callable[[programs.ListProgramsRequest], programs.ListProgramsResponse]: r"""Return a callable for the list programs method over gRPC. Retrieves all programs for the account. @@ -361,18 +371,18 @@ def list_programs(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_programs' not in self._stubs: - self._stubs['list_programs'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/ListPrograms', + if "list_programs" not in self._stubs: + self._stubs["list_programs"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/ListPrograms", request_serializer=programs.ListProgramsRequest.serialize, response_deserializer=programs.ListProgramsResponse.deserialize, ) - return self._stubs['list_programs'] + return self._stubs["list_programs"] @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - programs.Program]: + def enable_program( + self, + ) -> Callable[[programs.EnableProgramRequest], programs.Program]: r"""Return a callable for the enable program method over gRPC. Enable participation in the specified program for the @@ -388,18 +398,18 @@ def enable_program(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'enable_program' not in self._stubs: - self._stubs['enable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/EnableProgram', + if "enable_program" not in self._stubs: + self._stubs["enable_program"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/EnableProgram", request_serializer=programs.EnableProgramRequest.serialize, response_deserializer=programs.Program.deserialize, ) - return self._stubs['enable_program'] + return self._stubs["enable_program"] @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - programs.Program]: + def disable_program( + self, + ) -> Callable[[programs.DisableProgramRequest], programs.Program]: r"""Return a callable for the disable program method over gRPC. Disable participation in the specified program for @@ -415,13 +425,13 @@ def disable_program(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'disable_program' not in self._stubs: - self._stubs['disable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/DisableProgram', + if "disable_program" not in self._stubs: + self._stubs["disable_program"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/DisableProgram", request_serializer=programs.DisableProgramRequest.serialize, response_deserializer=programs.Program.deserialize, ) - return self._stubs['disable_program'] + return self._stubs["disable_program"] def close(self): self._logged_channel.close() @@ -431,6 +441,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'ProgramsServiceGrpcTransport', -) +__all__ = ("ProgramsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py index 5d146558736a..420e732a91ac 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import programs -from .base import ProgramsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, ProgramsServiceTransport from .grpc import ProgramsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -132,13 +140,15 @@ class ProgramsServiceGrpcAsyncIOTransport(ProgramsServiceTransport): _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. @@ -168,24 +178,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: @@ -309,7 +321,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) @@ -324,9 +338,9 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_program(self) -> Callable[ - [programs.GetProgramRequest], - Awaitable[programs.Program]]: + def get_program( + self, + ) -> Callable[[programs.GetProgramRequest], Awaitable[programs.Program]]: r"""Return a callable for the get program method over gRPC. Retrieves the specified program for the account. @@ -341,18 +355,20 @@ def get_program(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_program' not in self._stubs: - self._stubs['get_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/GetProgram', + if "get_program" not in self._stubs: + self._stubs["get_program"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/GetProgram", request_serializer=programs.GetProgramRequest.serialize, response_deserializer=programs.Program.deserialize, ) - return self._stubs['get_program'] + return self._stubs["get_program"] @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - Awaitable[programs.ListProgramsResponse]]: + def list_programs( + self, + ) -> Callable[ + [programs.ListProgramsRequest], Awaitable[programs.ListProgramsResponse] + ]: r"""Return a callable for the list programs method over gRPC. Retrieves all programs for the account. @@ -367,18 +383,18 @@ def list_programs(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_programs' not in self._stubs: - self._stubs['list_programs'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/ListPrograms', + if "list_programs" not in self._stubs: + self._stubs["list_programs"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/ListPrograms", request_serializer=programs.ListProgramsRequest.serialize, response_deserializer=programs.ListProgramsResponse.deserialize, ) - return self._stubs['list_programs'] + return self._stubs["list_programs"] @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - Awaitable[programs.Program]]: + def enable_program( + self, + ) -> Callable[[programs.EnableProgramRequest], Awaitable[programs.Program]]: r"""Return a callable for the enable program method over gRPC. Enable participation in the specified program for the @@ -394,18 +410,18 @@ def enable_program(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'enable_program' not in self._stubs: - self._stubs['enable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/EnableProgram', + if "enable_program" not in self._stubs: + self._stubs["enable_program"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/EnableProgram", request_serializer=programs.EnableProgramRequest.serialize, response_deserializer=programs.Program.deserialize, ) - return self._stubs['enable_program'] + return self._stubs["enable_program"] @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - Awaitable[programs.Program]]: + def disable_program( + self, + ) -> Callable[[programs.DisableProgramRequest], Awaitable[programs.Program]]: r"""Return a callable for the disable program method over gRPC. Disable participation in the specified program for @@ -421,16 +437,16 @@ def disable_program(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'disable_program' not in self._stubs: - self._stubs['disable_program'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ProgramsService/DisableProgram', + if "disable_program" not in self._stubs: + self._stubs["disable_program"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ProgramsService/DisableProgram", request_serializer=programs.DisableProgramRequest.serialize, response_deserializer=programs.Program.deserialize, ) - return self._stubs['disable_program'] + return self._stubs["disable_program"] 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.get_program: self._wrap_method( self.get_program, @@ -467,6 +483,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'ProgramsServiceGrpcAsyncIOTransport', -) +__all__ = ("ProgramsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py similarity index 74% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py index a56450e66673..1ee18be7bbbf 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import programs - -from .rest_base import _BaseProgramsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseProgramsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -114,7 +109,12 @@ def post_list_programs(self, response): """ - def pre_disable_program(self, request: programs.DisableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_disable_program( + self, + request: programs.DisableProgramRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.DisableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for disable_program Override in a subclass to manipulate the request or metadata @@ -135,7 +135,11 @@ def post_disable_program(self, response: programs.Program) -> programs.Program: """ return response - def post_disable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_disable_program_with_metadata( + self, + response: programs.Program, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for disable_program Override in a subclass to read or manipulate the response or metadata after it @@ -150,7 +154,11 @@ def post_disable_program_with_metadata(self, response: programs.Program, metadat """ return response, metadata - def pre_enable_program(self, request: programs.EnableProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_enable_program( + self, + request: programs.EnableProgramRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.EnableProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for enable_program Override in a subclass to manipulate the request or metadata @@ -171,7 +179,11 @@ def post_enable_program(self, response: programs.Program) -> programs.Program: """ return response - def post_enable_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_enable_program_with_metadata( + self, + response: programs.Program, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for enable_program Override in a subclass to read or manipulate the response or metadata after it @@ -186,7 +198,11 @@ def post_enable_program_with_metadata(self, response: programs.Program, metadata """ return response, metadata - def pre_get_program(self, request: programs.GetProgramRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_program( + self, + request: programs.GetProgramRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.GetProgramRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_program Override in a subclass to manipulate the request or metadata @@ -207,7 +223,11 @@ def post_get_program(self, response: programs.Program) -> programs.Program: """ return response - def post_get_program_with_metadata(self, response: programs.Program, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_program_with_metadata( + self, + response: programs.Program, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.Program, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_program Override in a subclass to read or manipulate the response or metadata after it @@ -222,7 +242,11 @@ def post_get_program_with_metadata(self, response: programs.Program, metadata: S """ return response, metadata - def pre_list_programs(self, request: programs.ListProgramsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_programs( + self, + request: programs.ListProgramsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.ListProgramsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_programs Override in a subclass to manipulate the request or metadata @@ -230,7 +254,9 @@ def pre_list_programs(self, request: programs.ListProgramsRequest, metadata: Seq """ return request, metadata - def post_list_programs(self, response: programs.ListProgramsResponse) -> programs.ListProgramsResponse: + def post_list_programs( + self, response: programs.ListProgramsResponse + ) -> programs.ListProgramsResponse: """Post-rpc interceptor for list_programs DEPRECATED. Please use the `post_list_programs_with_metadata` @@ -243,7 +269,11 @@ def post_list_programs(self, response: programs.ListProgramsResponse) -> program """ return response - def post_list_programs_with_metadata(self, response: programs.ListProgramsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[programs.ListProgramsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_programs_with_metadata( + self, + response: programs.ListProgramsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[programs.ListProgramsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_programs Override in a subclass to read or manipulate the response or metadata after it @@ -288,20 +318,21 @@ class ProgramsServiceRestTransport(_BaseProgramsServiceRestTransport): 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[ProgramsServiceRestInterceptor] = 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[ProgramsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -344,16 +375,19 @@ 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 ProgramsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _DisableProgram(_BaseProgramsServiceRestTransport._BaseDisableProgram, ProgramsServiceRestStub): + class _DisableProgram( + _BaseProgramsServiceRestTransport._BaseDisableProgram, ProgramsServiceRestStub + ): def __hash__(self): return hash("ProgramsServiceRestTransport.DisableProgram") @@ -365,27 +399,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: programs.DisableProgramRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.Program: + def __call__( + self, + request: programs.DisableProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Call the disable program method over HTTP. Args: @@ -421,32 +457,44 @@ def __call__(self, """ - http_options = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_http_options() + http_options = ( + _BaseProgramsServiceRestTransport._BaseDisableProgram._get_http_options() + ) request, metadata = self._interceptor.pre_disable_program(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_transcoded_request(http_options, request) + transcoded_request = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_transcoded_request( + http_options, request + ) - body = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_request_body_json(transcoded_request) + body = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseProgramsServiceRestTransport._BaseDisableProgram._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.DisableProgram", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "DisableProgram", "httpRequest": http_request, @@ -455,7 +503,15 @@ def __call__(self, ) # Send the request - response = ProgramsServiceRestTransport._DisableProgram._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ProgramsServiceRestTransport._DisableProgram._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. @@ -470,20 +526,24 @@ def __call__(self, resp = self._interceptor.post_disable_program(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_disable_program_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_disable_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = programs.Program.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.accounts_v1.ProgramsServiceClient.disable_program", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "DisableProgram", "metadata": http_response["headers"], @@ -492,7 +552,9 @@ def __call__(self, ) return resp - class _EnableProgram(_BaseProgramsServiceRestTransport._BaseEnableProgram, ProgramsServiceRestStub): + class _EnableProgram( + _BaseProgramsServiceRestTransport._BaseEnableProgram, ProgramsServiceRestStub + ): def __hash__(self): return hash("ProgramsServiceRestTransport.EnableProgram") @@ -504,27 +566,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: programs.EnableProgramRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.Program: + def __call__( + self, + request: programs.EnableProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Call the enable program method over HTTP. Args: @@ -560,32 +624,44 @@ def __call__(self, """ - http_options = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_http_options() + http_options = ( + _BaseProgramsServiceRestTransport._BaseEnableProgram._get_http_options() + ) request, metadata = self._interceptor.pre_enable_program(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_transcoded_request(http_options, request) + transcoded_request = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_transcoded_request( + http_options, request + ) - body = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_request_body_json(transcoded_request) + body = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseProgramsServiceRestTransport._BaseEnableProgram._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.EnableProgram", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "EnableProgram", "httpRequest": http_request, @@ -594,7 +670,15 @@ def __call__(self, ) # Send the request - response = ProgramsServiceRestTransport._EnableProgram._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ProgramsServiceRestTransport._EnableProgram._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -609,20 +693,24 @@ def __call__(self, resp = self._interceptor.post_enable_program(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_enable_program_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_enable_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = programs.Program.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.accounts_v1.ProgramsServiceClient.enable_program", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "EnableProgram", "metadata": http_response["headers"], @@ -631,7 +719,9 @@ def __call__(self, ) return resp - class _GetProgram(_BaseProgramsServiceRestTransport._BaseGetProgram, ProgramsServiceRestStub): + class _GetProgram( + _BaseProgramsServiceRestTransport._BaseGetProgram, ProgramsServiceRestStub + ): def __hash__(self): return hash("ProgramsServiceRestTransport.GetProgram") @@ -643,26 +733,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: programs.GetProgramRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.Program: + def __call__( + self, + request: programs.GetProgramRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.Program: r"""Call the get program method over HTTP. Args: @@ -698,30 +790,40 @@ def __call__(self, """ - http_options = _BaseProgramsServiceRestTransport._BaseGetProgram._get_http_options() + http_options = ( + _BaseProgramsServiceRestTransport._BaseGetProgram._get_http_options() + ) request, metadata = self._interceptor.pre_get_program(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseGetProgram._get_transcoded_request(http_options, request) + transcoded_request = _BaseProgramsServiceRestTransport._BaseGetProgram._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseGetProgram._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseProgramsServiceRestTransport._BaseGetProgram._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.GetProgram", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "GetProgram", "httpRequest": http_request, @@ -730,7 +832,14 @@ def __call__(self, ) # Send the request - response = ProgramsServiceRestTransport._GetProgram._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ProgramsServiceRestTransport._GetProgram._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -745,20 +854,24 @@ def __call__(self, resp = self._interceptor.post_get_program(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_program_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_program_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = programs.Program.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.accounts_v1.ProgramsServiceClient.get_program", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "GetProgram", "metadata": http_response["headers"], @@ -767,7 +880,9 @@ def __call__(self, ) return resp - class _ListPrograms(_BaseProgramsServiceRestTransport._BaseListPrograms, ProgramsServiceRestStub): + class _ListPrograms( + _BaseProgramsServiceRestTransport._BaseListPrograms, ProgramsServiceRestStub + ): def __hash__(self): return hash("ProgramsServiceRestTransport.ListPrograms") @@ -779,26 +894,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: programs.ListProgramsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> programs.ListProgramsResponse: + def __call__( + self, + request: programs.ListProgramsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> programs.ListProgramsResponse: r"""Call the list programs method over HTTP. Args: @@ -820,30 +937,40 @@ def __call__(self, """ - http_options = _BaseProgramsServiceRestTransport._BaseListPrograms._get_http_options() + http_options = ( + _BaseProgramsServiceRestTransport._BaseListPrograms._get_http_options() + ) request, metadata = self._interceptor.pre_list_programs(request, metadata) - transcoded_request = _BaseProgramsServiceRestTransport._BaseListPrograms._get_transcoded_request(http_options, request) + transcoded_request = _BaseProgramsServiceRestTransport._BaseListPrograms._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseProgramsServiceRestTransport._BaseListPrograms._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseProgramsServiceRestTransport._BaseListPrograms._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ProgramsServiceClient.ListPrograms", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "ListPrograms", "httpRequest": http_request, @@ -852,7 +979,14 @@ def __call__(self, ) # Send the request - response = ProgramsServiceRestTransport._ListPrograms._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ProgramsServiceRestTransport._ListPrograms._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -867,20 +1001,24 @@ def __call__(self, resp = self._interceptor.post_list_programs(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_programs_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_programs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = programs.ListProgramsResponse.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.accounts_v1.ProgramsServiceClient.list_programs", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ProgramsService", "rpcName": "ListPrograms", "metadata": http_response["headers"], @@ -890,36 +1028,34 @@ def __call__(self, return resp @property - def disable_program(self) -> Callable[ - [programs.DisableProgramRequest], - programs.Program]: + def disable_program( + self, + ) -> Callable[[programs.DisableProgramRequest], programs.Program]: # 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._DisableProgram(self._session, self._host, self._interceptor) # type: ignore + return self._DisableProgram(self._session, self._host, self._interceptor) # type: ignore @property - def enable_program(self) -> Callable[ - [programs.EnableProgramRequest], - programs.Program]: + def enable_program( + self, + ) -> Callable[[programs.EnableProgramRequest], programs.Program]: # 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._EnableProgram(self._session, self._host, self._interceptor) # type: ignore + return self._EnableProgram(self._session, self._host, self._interceptor) # type: ignore @property - def get_program(self) -> Callable[ - [programs.GetProgramRequest], - programs.Program]: + def get_program(self) -> Callable[[programs.GetProgramRequest], programs.Program]: # 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._GetProgram(self._session, self._host, self._interceptor) # type: ignore + return self._GetProgram(self._session, self._host, self._interceptor) # type: ignore @property - def list_programs(self) -> Callable[ - [programs.ListProgramsRequest], - programs.ListProgramsResponse]: + def list_programs( + self, + ) -> Callable[[programs.ListProgramsRequest], programs.ListProgramsResponse]: # 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._ListPrograms(self._session, self._host, self._interceptor) # type: ignore + return self._ListPrograms(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -929,6 +1065,4 @@ def close(self): self._session.close() -__all__=( - 'ProgramsServiceRestTransport', -) +__all__ = ("ProgramsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py index 841b18e2ca4f..3613b45cf6c7 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/programs_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 ProgramsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import programs +from .base import DEFAULT_CLIENT_INFO, ProgramsServiceTransport + class _BaseProgramsServiceRestTransport(ProgramsServiceTransport): """Base REST backend transport for ProgramsService. @@ -40,14 +38,16 @@ class _BaseProgramsServiceRestTransport(ProgramsServiceTransport): 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,27 +84,31 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) class _BaseDisableProgram: 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': '/accounts/v1/{name=accounts/*/programs/*}:disable', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/programs/*}:disable", + "body": "*", + }, ] return http_options @@ -117,17 +123,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseProgramsServiceRestTransport._BaseDisableProgram._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( + _BaseProgramsServiceRestTransport._BaseDisableProgram._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -136,20 +148,24 @@ class _BaseEnableProgram: 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': '/accounts/v1/{name=accounts/*/programs/*}:enable', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=accounts/*/programs/*}:enable", + "body": "*", + }, ] return http_options @@ -164,17 +180,23 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseProgramsServiceRestTransport._BaseEnableProgram._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( + _BaseProgramsServiceRestTransport._BaseEnableProgram._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -183,19 +205,23 @@ class _BaseGetProgram: 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': '/accounts/v1/{name=accounts/*/programs/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/programs/*}", + }, ] return http_options @@ -207,11 +233,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(_BaseProgramsServiceRestTransport._BaseGetProgram._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( + _BaseProgramsServiceRestTransport._BaseGetProgram._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -220,19 +252,23 @@ class _BaseListPrograms: 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': '/accounts/v1/{parent=accounts/*}/programs', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/programs", + }, ] return http_options @@ -244,16 +280,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(_BaseProgramsServiceRestTransport._BaseListPrograms._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( + _BaseProgramsServiceRestTransport._BaseListPrograms._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseProgramsServiceRestTransport', -) +__all__ = ("_BaseProgramsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py similarity index 92% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py index 4809e9fed9f9..f77ca5b08255 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import RegionsServiceClient from .async_client import RegionsServiceAsyncClient +from .client import RegionsServiceClient __all__ = ( - 'RegionsServiceClient', - 'RegionsServiceAsyncClient', + "RegionsServiceClient", + "RegionsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py index 0a23741838d8..d1996276c7e3 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -36,20 +46,24 @@ from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.regions_service import pagers from google.shopping.merchant_accounts_v1.types import regions -from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport + from .client import RegionsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, RegionsServiceTransport +from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport 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 RegionsServiceAsyncClient: """Manages regions configuration. @@ -71,16 +85,30 @@ class RegionsServiceAsyncClient: parse_account_path = staticmethod(RegionsServiceClient.parse_account_path) region_path = staticmethod(RegionsServiceClient.region_path) parse_region_path = staticmethod(RegionsServiceClient.parse_region_path) - common_billing_account_path = staticmethod(RegionsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegionsServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + RegionsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RegionsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(RegionsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RegionsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RegionsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RegionsServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + RegionsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + RegionsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RegionsServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(RegionsServiceClient.common_project_path) - parse_common_project_path = staticmethod(RegionsServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + RegionsServiceClient.parse_common_project_path + ) common_location_path = staticmethod(RegionsServiceClient.common_location_path) - parse_common_location_path = staticmethod(RegionsServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + RegionsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -116,7 +144,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: @@ -179,12 +209,16 @@ def universe_domain(self) -> str: get_transport_class = RegionsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = "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, RegionsServiceTransport, Callable[..., RegionsServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the regions service async client. Args: @@ -239,31 +273,39 @@ 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.accounts_v1.RegionsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", - "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.accounts.v1.RegionsService", "credentialsType": None, - } + }, ) - async def get_region(self, - request: Optional[Union[regions.GetRegionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: + async def get_region( + self, + request: Optional[Union[regions.GetRegionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Retrieves a region defined in your Merchant Center account. @@ -326,10 +368,14 @@ async def sample_get_region(): # - 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. @@ -343,14 +389,14 @@ async def sample_get_region(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_region] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_region + ] # 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. @@ -367,16 +413,17 @@ async def sample_get_region(): # Done; return the response. return response - async def create_region(self, - request: Optional[Union[regions.CreateRegionRequest, dict]] = None, - *, - parent: Optional[str] = None, - region: Optional[regions.Region] = None, - region_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: + async def create_region( + self, + request: Optional[Union[regions.CreateRegionRequest, dict]] = None, + *, + parent: Optional[str] = None, + region: Optional[regions.Region] = None, + region_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Creates a region definition in your Merchant Center account. Executing this method requires admin access. @@ -453,10 +500,14 @@ async def sample_create_region(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, region, region_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -474,14 +525,14 @@ async def sample_create_region(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_region] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_region + ] # 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. @@ -498,15 +549,16 @@ async def sample_create_region(): # Done; return the response. return response - async def update_region(self, - request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, - *, - region: Optional[regions.Region] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: + async def update_region( + self, + request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, + *, + region: Optional[regions.Region] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Updates a region definition in your Merchant Center account. Executing this method requires admin access. @@ -574,10 +626,14 @@ async def sample_update_region(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [region, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -593,14 +649,16 @@ async def sample_update_region(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_region] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_region + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("region.name", request.region.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("region.name", request.region.name),) + ), ) # Validate the universe domain. @@ -617,14 +675,15 @@ async def sample_update_region(): # Done; return the response. return response - async def delete_region(self, - request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, - *, - name: 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_region( + self, + request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, + *, + name: 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 a region definition from your Merchant Center account. Executing this method requires admin access. @@ -673,10 +732,14 @@ async def sample_delete_region(): # - 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. @@ -690,14 +753,14 @@ async def sample_delete_region(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_region] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_region + ] # 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. @@ -711,14 +774,15 @@ async def sample_delete_region(): metadata=metadata, ) - async def list_regions(self, - request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsAsyncPager: + async def list_regions( + self, + request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsAsyncPager: r"""Lists the regions in your Merchant Center account. .. code-block:: python @@ -778,10 +842,14 @@ async def sample_list_regions(): # - 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. @@ -795,14 +863,14 @@ async def sample_list_regions(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_regions] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_regions + ] # 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. @@ -836,12 +904,13 @@ async def __aenter__(self) -> "RegionsServiceAsyncClient": 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__ = ( - "RegionsServiceAsyncClient", -) +__all__ = ("RegionsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/client.py index 97e99287902d..62ea7b923ca9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,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 @@ -50,9 +63,11 @@ from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.regions_service import pagers from google.shopping.merchant_accounts_v1.types import regions -from .transports.base import RegionsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, RegionsServiceTransport from .transports.grpc import RegionsServiceGrpcTransport from .transports.grpc_asyncio import RegionsServiceGrpcAsyncIOTransport from .transports.rest import RegionsServiceRestTransport @@ -65,14 +80,18 @@ class RegionsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RegionsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[RegionsServiceTransport]] _transport_registry["grpc"] = RegionsServiceGrpcTransport _transport_registry["grpc_asyncio"] = RegionsServiceGrpcAsyncIOTransport _transport_registry["rest"] = RegionsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RegionsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionsServiceTransport]: """Returns an appropriate transport class. Args: @@ -169,8 +188,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: RegionsServiceClient: 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) @@ -187,84 +205,118 @@ def transport(self) -> RegionsServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def region_path(account: str,region: str,) -> str: + def region_path( + account: str, + region: str, + ) -> str: """Returns a fully-qualified region string.""" - return "accounts/{account}/regions/{region}".format(account=account, region=region, ) + return "accounts/{account}/regions/{region}".format( + account=account, + region=region, + ) @staticmethod - def parse_region_path(path: str) -> Dict[str,str]: + def parse_region_path(path: str) -> Dict[str, str]: """Parses a region path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/regions/(?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: @@ -296,16 +348,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 @@ -318,7 +376,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 @@ -339,13 +399,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 @@ -368,7 +434,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: @@ -384,17 +452,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = RegionsServiceClient._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 = RegionsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = RegionsServiceClient._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: @@ -430,15 +506,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 @@ -471,12 +550,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegionsServiceTransport, Callable[..., RegionsServiceTransport]]] = 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, RegionsServiceTransport, Callable[..., RegionsServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the regions service client. Args: @@ -531,14 +614,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 = RegionsServiceClient._read_environment_variables() - self._client_cert_source = RegionsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = RegionsServiceClient._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, + ) = RegionsServiceClient._read_environment_variables() + self._client_cert_source = RegionsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RegionsServiceClient._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 @@ -549,7 +642,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 @@ -558,8 +653,10 @@ def __init__(self, *, if transport_provided: # transport is a RegionsServiceTransport 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 " @@ -568,20 +665,29 @@ def __init__(self, *, self._transport = cast(RegionsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - RegionsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or RegionsServiceClient._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[RegionsServiceTransport], Callable[..., RegionsServiceTransport]] = ( + transport_init: Union[ + Type[RegionsServiceTransport], Callable[..., RegionsServiceTransport] + ] = ( RegionsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., RegionsServiceTransport], transport) @@ -600,28 +706,37 @@ 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.accounts_v1.RegionsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", - "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.accounts.v1.RegionsService", "credentialsType": None, - } + }, ) - def get_region(self, - request: Optional[Union[regions.GetRegionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: + def get_region( + self, + request: Optional[Union[regions.GetRegionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Retrieves a region defined in your Merchant Center account. @@ -684,10 +799,14 @@ def sample_get_region(): # - 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. @@ -705,9 +824,7 @@ def sample_get_region(): # 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. @@ -724,16 +841,17 @@ def sample_get_region(): # Done; return the response. return response - def create_region(self, - request: Optional[Union[regions.CreateRegionRequest, dict]] = None, - *, - parent: Optional[str] = None, - region: Optional[regions.Region] = None, - region_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: + def create_region( + self, + request: Optional[Union[regions.CreateRegionRequest, dict]] = None, + *, + parent: Optional[str] = None, + region: Optional[regions.Region] = None, + region_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Creates a region definition in your Merchant Center account. Executing this method requires admin access. @@ -810,10 +928,14 @@ def sample_create_region(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, region, region_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -835,9 +957,7 @@ def sample_create_region(): # 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. @@ -854,15 +974,16 @@ def sample_create_region(): # Done; return the response. return response - def update_region(self, - request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, - *, - region: Optional[regions.Region] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> regions.Region: + def update_region( + self, + request: Optional[Union[regions.UpdateRegionRequest, dict]] = None, + *, + region: Optional[regions.Region] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Updates a region definition in your Merchant Center account. Executing this method requires admin access. @@ -930,10 +1051,14 @@ def sample_update_region(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [region, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -953,9 +1078,9 @@ def sample_update_region(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("region.name", request.region.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("region.name", request.region.name),) + ), ) # Validate the universe domain. @@ -972,14 +1097,15 @@ def sample_update_region(): # Done; return the response. return response - def delete_region(self, - request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, - *, - name: 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_region( + self, + request: Optional[Union[regions.DeleteRegionRequest, dict]] = None, + *, + name: 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 a region definition from your Merchant Center account. Executing this method requires admin access. @@ -1028,10 +1154,14 @@ def sample_delete_region(): # - 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. @@ -1049,9 +1179,7 @@ def sample_delete_region(): # 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. @@ -1065,14 +1193,15 @@ def sample_delete_region(): metadata=metadata, ) - def list_regions(self, - request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsPager: + def list_regions( + self, + request: Optional[Union[regions.ListRegionsRequest, 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.ListRegionsPager: r"""Lists the regions in your Merchant Center account. .. code-block:: python @@ -1132,10 +1261,14 @@ def sample_list_regions(): # - 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. @@ -1153,9 +1286,7 @@ def sample_list_regions(): # 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. @@ -1197,16 +1328,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__ = ( - "RegionsServiceClient", -) +__all__ = ("RegionsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py index 6a25efa04dd8..089f669d7e61 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_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 ListRegionsPager: 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[..., regions.ListRegionsResponse], - request: regions.ListRegionsRequest, - response: regions.ListRegionsResponse, - *, - 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[..., regions.ListRegionsResponse], + request: regions.ListRegionsRequest, + response: regions.ListRegionsResponse, + *, + 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[regions.ListRegionsResponse]: 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[regions.Region]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[regions.Region]: yield from page.regions 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 ListRegionsAsyncPager: @@ -112,14 +134,17 @@ class ListRegionsAsyncPager: 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[regions.ListRegionsResponse]], - request: regions.ListRegionsRequest, - response: regions.ListRegionsResponse, - *, - 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[regions.ListRegionsResponse]], + request: regions.ListRegionsRequest, + response: regions.ListRegionsResponse, + *, + 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[regions.ListRegionsResponse]: 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[regions.Region]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py index e958dfda0512..19385c56bb74 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/regions_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import RegionsServiceTransport from .grpc import RegionsServiceGrpcTransport from .grpc_asyncio import RegionsServiceGrpcAsyncIOTransport -from .rest import RegionsServiceRestTransport -from .rest import RegionsServiceRestInterceptor - +from .rest import RegionsServiceRestInterceptor, RegionsServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[RegionsServiceTransport]] -_transport_registry['grpc'] = RegionsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RegionsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RegionsServiceRestTransport +_transport_registry["grpc"] = RegionsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = RegionsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = RegionsServiceRestTransport __all__ = ( - 'RegionsServiceTransport', - 'RegionsServiceGrpcTransport', - 'RegionsServiceGrpcAsyncIOTransport', - 'RegionsServiceRestTransport', - 'RegionsServiceRestInterceptor', + "RegionsServiceTransport", + "RegionsServiceGrpcTransport", + "RegionsServiceGrpcAsyncIOTransport", + "RegionsServiceRestTransport", + "RegionsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py index a1f149140f44..60cdd11d57a1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/base.py @@ -16,21 +16,22 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import regions -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 RegionsServiceTransport(abc.ABC): """Abstract transport class for RegionsService.""" - 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 @@ -150,60 +158,57 @@ 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 get_region(self) -> Callable[ - [regions.GetRegionRequest], - Union[ - regions.Region, - Awaitable[regions.Region] - ]]: + def get_region( + self, + ) -> Callable[ + [regions.GetRegionRequest], Union[regions.Region, Awaitable[regions.Region]] + ]: raise NotImplementedError() @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - Union[ - regions.Region, - Awaitable[regions.Region] - ]]: + def create_region( + self, + ) -> Callable[ + [regions.CreateRegionRequest], Union[regions.Region, Awaitable[regions.Region]] + ]: raise NotImplementedError() @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - Union[ - regions.Region, - Awaitable[regions.Region] - ]]: + def update_region( + self, + ) -> Callable[ + [regions.UpdateRegionRequest], Union[regions.Region, Awaitable[regions.Region]] + ]: raise NotImplementedError() @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_region( + self, + ) -> Callable[ + [regions.DeleteRegionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: raise NotImplementedError() @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - Union[ - regions.ListRegionsResponse, - Awaitable[regions.ListRegionsResponse] - ]]: + def list_regions( + self, + ) -> Callable[ + [regions.ListRegionsRequest], + Union[regions.ListRegionsResponse, Awaitable[regions.ListRegionsResponse]], + ]: raise NotImplementedError() @property @@ -211,6 +216,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'RegionsServiceTransport', -) +__all__ = ("RegionsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py index 3c9745b0a812..5ea440aa1c7d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_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_accounts_v1.types import regions -from .base import RegionsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, RegionsServiceTransport 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.accounts.v1.RegionsService", "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.accounts.v1.RegionsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -118,23 +124,26 @@ class RegionsServiceGrpcTransport(RegionsServiceTransport): 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: @@ -256,19 +265,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. @@ -303,19 +316,16 @@ 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 get_region(self) -> Callable[ - [regions.GetRegionRequest], - regions.Region]: + def get_region(self) -> Callable[[regions.GetRegionRequest], regions.Region]: r"""Return a callable for the get region method over gRPC. Retrieves a region defined in your Merchant Center @@ -331,18 +341,16 @@ def get_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_region' not in self._stubs: - self._stubs['get_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/GetRegion', + if "get_region" not in self._stubs: + self._stubs["get_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/GetRegion", request_serializer=regions.GetRegionRequest.serialize, response_deserializer=regions.Region.deserialize, ) - return self._stubs['get_region'] + return self._stubs["get_region"] @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - regions.Region]: + def create_region(self) -> Callable[[regions.CreateRegionRequest], regions.Region]: r"""Return a callable for the create region method over gRPC. Creates a region definition in your Merchant Center @@ -358,18 +366,16 @@ def create_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_region' not in self._stubs: - self._stubs['create_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/CreateRegion', + if "create_region" not in self._stubs: + self._stubs["create_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/CreateRegion", request_serializer=regions.CreateRegionRequest.serialize, response_deserializer=regions.Region.deserialize, ) - return self._stubs['create_region'] + return self._stubs["create_region"] @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - regions.Region]: + def update_region(self) -> Callable[[regions.UpdateRegionRequest], regions.Region]: r"""Return a callable for the update region method over gRPC. Updates a region definition in your Merchant Center @@ -385,18 +391,16 @@ def update_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_region' not in self._stubs: - self._stubs['update_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/UpdateRegion', + if "update_region" not in self._stubs: + self._stubs["update_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/UpdateRegion", request_serializer=regions.UpdateRegionRequest.serialize, response_deserializer=regions.Region.deserialize, ) - return self._stubs['update_region'] + return self._stubs["update_region"] @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - empty_pb2.Empty]: + def delete_region(self) -> Callable[[regions.DeleteRegionRequest], empty_pb2.Empty]: r"""Return a callable for the delete region method over gRPC. Deletes a region definition from your Merchant Center @@ -412,18 +416,18 @@ def delete_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_region' not in self._stubs: - self._stubs['delete_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/DeleteRegion', + if "delete_region" not in self._stubs: + self._stubs["delete_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/DeleteRegion", request_serializer=regions.DeleteRegionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_region'] + return self._stubs["delete_region"] @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - regions.ListRegionsResponse]: + def list_regions( + self, + ) -> Callable[[regions.ListRegionsRequest], regions.ListRegionsResponse]: r"""Return a callable for the list regions method over gRPC. Lists the regions in your Merchant Center account. @@ -438,13 +442,13 @@ def list_regions(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_regions' not in self._stubs: - self._stubs['list_regions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/ListRegions', + if "list_regions" not in self._stubs: + self._stubs["list_regions"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/ListRegions", request_serializer=regions.ListRegionsRequest.serialize, response_deserializer=regions.ListRegionsResponse.deserialize, ) - return self._stubs['list_regions'] + return self._stubs["list_regions"] def close(self): self._logged_channel.close() @@ -454,6 +458,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'RegionsServiceGrpcTransport', -) +__all__ = ("RegionsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py index 0c9b25f62067..e46a15718721 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_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_accounts_v1.types import regions -from .base import RegionsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, RegionsServiceTransport from .grpc import RegionsServiceGrpcTransport 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.accounts.v1.RegionsService", "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.accounts.v1.RegionsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -127,13 +135,15 @@ class RegionsServiceGrpcAsyncIOTransport(RegionsServiceTransport): _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. @@ -163,24 +173,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = '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: @@ -304,7 +316,9 @@ def __init__(self, *, self._interceptor = _LoggingClientAIOInterceptor() self._grpc_channel._unary_unary_interceptors.append(self._interceptor) self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @@ -319,9 +333,9 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_region(self) -> Callable[ - [regions.GetRegionRequest], - Awaitable[regions.Region]]: + def get_region( + self, + ) -> Callable[[regions.GetRegionRequest], Awaitable[regions.Region]]: r"""Return a callable for the get region method over gRPC. Retrieves a region defined in your Merchant Center @@ -337,18 +351,18 @@ def get_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_region' not in self._stubs: - self._stubs['get_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/GetRegion', + if "get_region" not in self._stubs: + self._stubs["get_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/GetRegion", request_serializer=regions.GetRegionRequest.serialize, response_deserializer=regions.Region.deserialize, ) - return self._stubs['get_region'] + return self._stubs["get_region"] @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - Awaitable[regions.Region]]: + def create_region( + self, + ) -> Callable[[regions.CreateRegionRequest], Awaitable[regions.Region]]: r"""Return a callable for the create region method over gRPC. Creates a region definition in your Merchant Center @@ -364,18 +378,18 @@ def create_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_region' not in self._stubs: - self._stubs['create_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/CreateRegion', + if "create_region" not in self._stubs: + self._stubs["create_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/CreateRegion", request_serializer=regions.CreateRegionRequest.serialize, response_deserializer=regions.Region.deserialize, ) - return self._stubs['create_region'] + return self._stubs["create_region"] @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - Awaitable[regions.Region]]: + def update_region( + self, + ) -> Callable[[regions.UpdateRegionRequest], Awaitable[regions.Region]]: r"""Return a callable for the update region method over gRPC. Updates a region definition in your Merchant Center @@ -391,18 +405,18 @@ def update_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_region' not in self._stubs: - self._stubs['update_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/UpdateRegion', + if "update_region" not in self._stubs: + self._stubs["update_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/UpdateRegion", request_serializer=regions.UpdateRegionRequest.serialize, response_deserializer=regions.Region.deserialize, ) - return self._stubs['update_region'] + return self._stubs["update_region"] @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - Awaitable[empty_pb2.Empty]]: + def delete_region( + self, + ) -> Callable[[regions.DeleteRegionRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete region method over gRPC. Deletes a region definition from your Merchant Center @@ -418,18 +432,18 @@ def delete_region(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_region' not in self._stubs: - self._stubs['delete_region'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/DeleteRegion', + if "delete_region" not in self._stubs: + self._stubs["delete_region"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/DeleteRegion", request_serializer=regions.DeleteRegionRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_region'] + return self._stubs["delete_region"] @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - Awaitable[regions.ListRegionsResponse]]: + def list_regions( + self, + ) -> Callable[[regions.ListRegionsRequest], Awaitable[regions.ListRegionsResponse]]: r"""Return a callable for the list regions method over gRPC. Lists the regions in your Merchant Center account. @@ -444,16 +458,16 @@ def list_regions(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_regions' not in self._stubs: - self._stubs['list_regions'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.RegionsService/ListRegions', + if "list_regions" not in self._stubs: + self._stubs["list_regions"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.RegionsService/ListRegions", request_serializer=regions.ListRegionsRequest.serialize, response_deserializer=regions.ListRegionsResponse.deserialize, ) - return self._stubs['list_regions'] + return self._stubs["list_regions"] 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.get_region: self._wrap_method( self.get_region, @@ -495,6 +509,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'RegionsServiceGrpcAsyncIOTransport', -) +__all__ = ("RegionsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py index d0e734288934..b287bd0d2afd 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_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_accounts_v1.types import regions - -from .rest_base import _BaseRegionsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseRegionsServiceRestTransport 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 @@ -119,7 +114,12 @@ def post_update_region(self, response): """ - def pre_create_region(self, request: regions.CreateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_region( + self, + request: regions.CreateRegionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.CreateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_region Override in a subclass to manipulate the request or metadata @@ -140,7 +140,11 @@ def post_create_region(self, response: regions.Region) -> regions.Region: """ return response - def post_create_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_region_with_metadata( + self, + response: regions.Region, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_region Override in a subclass to read or manipulate the response or metadata after it @@ -155,7 +159,11 @@ def post_create_region_with_metadata(self, response: regions.Region, metadata: S """ return response, metadata - def pre_delete_region(self, request: regions.DeleteRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_region( + self, + request: regions.DeleteRegionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.DeleteRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_region Override in a subclass to manipulate the request or metadata @@ -163,7 +171,11 @@ def pre_delete_region(self, request: regions.DeleteRegionRequest, metadata: Sequ """ return request, metadata - def pre_get_region(self, request: regions.GetRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_region( + self, + request: regions.GetRegionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.GetRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_region Override in a subclass to manipulate the request or metadata @@ -184,7 +196,11 @@ def post_get_region(self, response: regions.Region) -> regions.Region: """ return response - def post_get_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_region_with_metadata( + self, + response: regions.Region, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_region Override in a subclass to read or manipulate the response or metadata after it @@ -199,7 +215,11 @@ def post_get_region_with_metadata(self, response: regions.Region, metadata: Sequ """ return response, metadata - def pre_list_regions(self, request: regions.ListRegionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_regions( + self, + request: regions.ListRegionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.ListRegionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_regions Override in a subclass to manipulate the request or metadata @@ -207,7 +227,9 @@ def pre_list_regions(self, request: regions.ListRegionsRequest, metadata: Sequen """ return request, metadata - def post_list_regions(self, response: regions.ListRegionsResponse) -> regions.ListRegionsResponse: + def post_list_regions( + self, response: regions.ListRegionsResponse + ) -> regions.ListRegionsResponse: """Post-rpc interceptor for list_regions DEPRECATED. Please use the `post_list_regions_with_metadata` @@ -220,7 +242,11 @@ def post_list_regions(self, response: regions.ListRegionsResponse) -> regions.Li """ return response - def post_list_regions_with_metadata(self, response: regions.ListRegionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.ListRegionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_regions_with_metadata( + self, + response: regions.ListRegionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.ListRegionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_regions Override in a subclass to read or manipulate the response or metadata after it @@ -235,7 +261,11 @@ def post_list_regions_with_metadata(self, response: regions.ListRegionsResponse, """ return response, metadata - def pre_update_region(self, request: regions.UpdateRegionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_region( + self, + request: regions.UpdateRegionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.UpdateRegionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_region Override in a subclass to manipulate the request or metadata @@ -256,7 +286,11 @@ def post_update_region(self, response: regions.Region) -> regions.Region: """ return response - def post_update_region_with_metadata(self, response: regions.Region, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_region_with_metadata( + self, + response: regions.Region, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[regions.Region, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_region Override in a subclass to read or manipulate the response or metadata after it @@ -295,20 +329,21 @@ class RegionsServiceRestTransport(_BaseRegionsServiceRestTransport): 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[RegionsServiceRestInterceptor] = 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[RegionsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -351,16 +386,19 @@ 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 RegionsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateRegion(_BaseRegionsServiceRestTransport._BaseCreateRegion, RegionsServiceRestStub): + class _CreateRegion( + _BaseRegionsServiceRestTransport._BaseCreateRegion, RegionsServiceRestStub + ): def __hash__(self): return hash("RegionsServiceRestTransport.CreateRegion") @@ -372,27 +410,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: regions.CreateRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.Region: + def __call__( + self, + request: regions.CreateRegionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Call the create region method over HTTP. Args: @@ -419,32 +459,44 @@ def __call__(self, """ - http_options = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_http_options() + http_options = ( + _BaseRegionsServiceRestTransport._BaseCreateRegion._get_http_options() + ) request, metadata = self._interceptor.pre_create_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_transcoded_request(http_options, request) + transcoded_request = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_transcoded_request( + http_options, request + ) - body = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_request_body_json(transcoded_request) + body = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionsServiceRestTransport._BaseCreateRegion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.CreateRegion", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "CreateRegion", "httpRequest": http_request, @@ -453,7 +505,15 @@ def __call__(self, ) # Send the request - response = RegionsServiceRestTransport._CreateRegion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = RegionsServiceRestTransport._CreateRegion._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. @@ -468,20 +528,24 @@ def __call__(self, resp = self._interceptor.post_create_region(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_region_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_region_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = regions.Region.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.accounts_v1.RegionsServiceClient.create_region", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "CreateRegion", "metadata": http_response["headers"], @@ -490,7 +554,9 @@ def __call__(self, ) return resp - class _DeleteRegion(_BaseRegionsServiceRestTransport._BaseDeleteRegion, RegionsServiceRestStub): + class _DeleteRegion( + _BaseRegionsServiceRestTransport._BaseDeleteRegion, RegionsServiceRestStub + ): def __hash__(self): return hash("RegionsServiceRestTransport.DeleteRegion") @@ -502,26 +568,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: regions.DeleteRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: regions.DeleteRegionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete region method over HTTP. Args: @@ -536,30 +604,40 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_http_options() + http_options = ( + _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_http_options() + ) request, metadata = self._interceptor.pre_delete_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_transcoded_request(http_options, request) + transcoded_request = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.DeleteRegion", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "DeleteRegion", "httpRequest": http_request, @@ -568,14 +646,23 @@ def __call__(self, ) # Send the request - response = RegionsServiceRestTransport._DeleteRegion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = RegionsServiceRestTransport._DeleteRegion._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 _GetRegion(_BaseRegionsServiceRestTransport._BaseGetRegion, RegionsServiceRestStub): + class _GetRegion( + _BaseRegionsServiceRestTransport._BaseGetRegion, RegionsServiceRestStub + ): def __hash__(self): return hash("RegionsServiceRestTransport.GetRegion") @@ -587,26 +674,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: regions.GetRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.Region: + def __call__( + self, + request: regions.GetRegionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Call the get region method over HTTP. Args: @@ -633,30 +722,44 @@ def __call__(self, """ - http_options = _BaseRegionsServiceRestTransport._BaseGetRegion._get_http_options() + http_options = ( + _BaseRegionsServiceRestTransport._BaseGetRegion._get_http_options() + ) request, metadata = self._interceptor.pre_get_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseGetRegion._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseRegionsServiceRestTransport._BaseGetRegion._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseGetRegion._get_query_params_json(transcoded_request) + query_params = ( + _BaseRegionsServiceRestTransport._BaseGetRegion._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.shopping.merchant.accounts_v1.RegionsServiceClient.GetRegion", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "GetRegion", "httpRequest": http_request, @@ -665,7 +768,14 @@ def __call__(self, ) # Send the request - response = RegionsServiceRestTransport._GetRegion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = RegionsServiceRestTransport._GetRegion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -680,20 +790,24 @@ def __call__(self, resp = self._interceptor.post_get_region(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_region_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_region_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = regions.Region.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.accounts_v1.RegionsServiceClient.get_region", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "GetRegion", "metadata": http_response["headers"], @@ -702,7 +816,9 @@ def __call__(self, ) return resp - class _ListRegions(_BaseRegionsServiceRestTransport._BaseListRegions, RegionsServiceRestStub): + class _ListRegions( + _BaseRegionsServiceRestTransport._BaseListRegions, RegionsServiceRestStub + ): def __hash__(self): return hash("RegionsServiceRestTransport.ListRegions") @@ -714,26 +830,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: regions.ListRegionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.ListRegionsResponse: + def __call__( + self, + request: regions.ListRegionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.ListRegionsResponse: r"""Call the list regions method over HTTP. Args: @@ -752,30 +870,40 @@ def __call__(self, Response message for the ``ListRegions`` method. """ - http_options = _BaseRegionsServiceRestTransport._BaseListRegions._get_http_options() + http_options = ( + _BaseRegionsServiceRestTransport._BaseListRegions._get_http_options() + ) request, metadata = self._interceptor.pre_list_regions(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseListRegions._get_transcoded_request(http_options, request) + transcoded_request = _BaseRegionsServiceRestTransport._BaseListRegions._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseListRegions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionsServiceRestTransport._BaseListRegions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.ListRegions", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "ListRegions", "httpRequest": http_request, @@ -784,7 +912,14 @@ def __call__(self, ) # Send the request - response = RegionsServiceRestTransport._ListRegions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = RegionsServiceRestTransport._ListRegions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -799,20 +934,24 @@ def __call__(self, resp = self._interceptor.post_list_regions(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_regions_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_regions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = regions.ListRegionsResponse.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.accounts_v1.RegionsServiceClient.list_regions", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "ListRegions", "metadata": http_response["headers"], @@ -821,7 +960,9 @@ def __call__(self, ) return resp - class _UpdateRegion(_BaseRegionsServiceRestTransport._BaseUpdateRegion, RegionsServiceRestStub): + class _UpdateRegion( + _BaseRegionsServiceRestTransport._BaseUpdateRegion, RegionsServiceRestStub + ): def __hash__(self): return hash("RegionsServiceRestTransport.UpdateRegion") @@ -833,27 +974,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: regions.UpdateRegionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> regions.Region: + def __call__( + self, + request: regions.UpdateRegionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> regions.Region: r"""Call the update region method over HTTP. Args: @@ -880,32 +1023,44 @@ def __call__(self, """ - http_options = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_http_options() + http_options = ( + _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_http_options() + ) request, metadata = self._interceptor.pre_update_region(request, metadata) - transcoded_request = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_transcoded_request(http_options, request) + transcoded_request = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_transcoded_request( + http_options, request + ) - body = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_request_body_json(transcoded_request) + body = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.RegionsServiceClient.UpdateRegion", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "UpdateRegion", "httpRequest": http_request, @@ -914,7 +1069,15 @@ def __call__(self, ) # Send the request - response = RegionsServiceRestTransport._UpdateRegion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = RegionsServiceRestTransport._UpdateRegion._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. @@ -929,20 +1092,24 @@ def __call__(self, resp = self._interceptor.post_update_region(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_region_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_region_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = regions.Region.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.accounts_v1.RegionsServiceClient.update_region", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.RegionsService", "rpcName": "UpdateRegion", "metadata": http_response["headers"], @@ -952,44 +1119,36 @@ def __call__(self, return resp @property - def create_region(self) -> Callable[ - [regions.CreateRegionRequest], - regions.Region]: + def create_region(self) -> Callable[[regions.CreateRegionRequest], regions.Region]: # 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._CreateRegion(self._session, self._host, self._interceptor) # type: ignore + return self._CreateRegion(self._session, self._host, self._interceptor) # type: ignore @property - def delete_region(self) -> Callable[ - [regions.DeleteRegionRequest], - empty_pb2.Empty]: + def delete_region(self) -> Callable[[regions.DeleteRegionRequest], 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._DeleteRegion(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteRegion(self._session, self._host, self._interceptor) # type: ignore @property - def get_region(self) -> Callable[ - [regions.GetRegionRequest], - regions.Region]: + def get_region(self) -> Callable[[regions.GetRegionRequest], regions.Region]: # 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._GetRegion(self._session, self._host, self._interceptor) # type: ignore + return self._GetRegion(self._session, self._host, self._interceptor) # type: ignore @property - def list_regions(self) -> Callable[ - [regions.ListRegionsRequest], - regions.ListRegionsResponse]: + def list_regions( + self, + ) -> Callable[[regions.ListRegionsRequest], regions.ListRegionsResponse]: # 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._ListRegions(self._session, self._host, self._interceptor) # type: ignore + return self._ListRegions(self._session, self._host, self._interceptor) # type: ignore @property - def update_region(self) -> Callable[ - [regions.UpdateRegionRequest], - regions.Region]: + def update_region(self) -> Callable[[regions.UpdateRegionRequest], regions.Region]: # 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._UpdateRegion(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateRegion(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -999,6 +1158,4 @@ def close(self): self._session.close() -__all__=( - 'RegionsServiceRestTransport', -) +__all__ = ("RegionsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py index 1ce66206aae9..b208bf6d4d9d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/regions_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/regions_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 RegionsServiceTransport, 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_accounts_v1.types import regions +from .base import DEFAULT_CLIENT_INFO, RegionsServiceTransport + class _BaseRegionsServiceRestTransport(RegionsServiceTransport): """Base REST backend transport for RegionsService. @@ -41,14 +39,16 @@ class _BaseRegionsServiceRestTransport(RegionsServiceTransport): 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,27 +85,33 @@ 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 _BaseCreateRegion: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "regionId" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "regionId": "", + } @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': '/accounts/v1/{parent=accounts/*}/regions', - 'body': 'region', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/regions", + "body": "region", + }, ] return http_options @@ -118,17 +126,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(_BaseRegionsServiceRestTransport._BaseCreateRegion._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( + _BaseRegionsServiceRestTransport._BaseCreateRegion._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -137,19 +151,23 @@ class _BaseDeleteRegion: 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': '/accounts/v1/{name=accounts/*/regions/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/accounts/v1/{name=accounts/*/regions/*}", + }, ] return http_options @@ -161,11 +179,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(_BaseRegionsServiceRestTransport._BaseDeleteRegion._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( + _BaseRegionsServiceRestTransport._BaseDeleteRegion._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -174,19 +198,23 @@ class _BaseGetRegion: 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': '/accounts/v1/{name=accounts/*/regions/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/regions/*}", + }, ] return http_options @@ -198,11 +226,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(_BaseRegionsServiceRestTransport._BaseGetRegion._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( + _BaseRegionsServiceRestTransport._BaseGetRegion._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -211,19 +245,23 @@ class _BaseListRegions: 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': '/accounts/v1/{parent=accounts/*}/regions', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/regions", + }, ] return http_options @@ -235,11 +273,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(_BaseRegionsServiceRestTransport._BaseListRegions._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( + _BaseRegionsServiceRestTransport._BaseListRegions._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -248,20 +292,24 @@ class _BaseUpdateRegion: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{region.name=accounts/*/regions/*}', - 'body': 'region', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{region.name=accounts/*/regions/*}", + "body": "region", + }, ] return http_options @@ -276,22 +324,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseRegionsServiceRestTransport._BaseUpdateRegion._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( + _BaseRegionsServiceRestTransport._BaseUpdateRegion._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseRegionsServiceRestTransport', -) +__all__ = ("_BaseRegionsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py index 023e41c50a7f..e67dc8f31ef3 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import ShippingSettingsServiceClient from .async_client import ShippingSettingsServiceAsyncClient +from .client import ShippingSettingsServiceClient __all__ = ( - 'ShippingSettingsServiceClient', - 'ShippingSettingsServiceAsyncClient', + "ShippingSettingsServiceClient", + "ShippingSettingsServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py index 0325c9e594f1..86d7af2b9dfa 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,18 +45,21 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.shopping.merchant_accounts_v1.types import shippingsettings -from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport + from .client import ShippingSettingsServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, ShippingSettingsServiceTransport +from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport 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 ShippingSettingsServiceAsyncClient: """Service to get method call shipping setting information per Merchant API method. @@ -58,23 +71,47 @@ class ShippingSettingsServiceAsyncClient: # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_ENDPOINT_TEMPLATE = ( + ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = ShippingSettingsServiceClient._DEFAULT_UNIVERSE account_path = staticmethod(ShippingSettingsServiceClient.account_path) parse_account_path = staticmethod(ShippingSettingsServiceClient.parse_account_path) - shipping_settings_path = staticmethod(ShippingSettingsServiceClient.shipping_settings_path) - parse_shipping_settings_path = staticmethod(ShippingSettingsServiceClient.parse_shipping_settings_path) - common_billing_account_path = staticmethod(ShippingSettingsServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ShippingSettingsServiceClient.parse_common_billing_account_path) + shipping_settings_path = staticmethod( + ShippingSettingsServiceClient.shipping_settings_path + ) + parse_shipping_settings_path = staticmethod( + ShippingSettingsServiceClient.parse_shipping_settings_path + ) + common_billing_account_path = staticmethod( + ShippingSettingsServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ShippingSettingsServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(ShippingSettingsServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ShippingSettingsServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ShippingSettingsServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ShippingSettingsServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ShippingSettingsServiceClient.common_project_path) - parse_common_project_path = staticmethod(ShippingSettingsServiceClient.parse_common_project_path) - common_location_path = staticmethod(ShippingSettingsServiceClient.common_location_path) - parse_common_location_path = staticmethod(ShippingSettingsServiceClient.parse_common_location_path) + parse_common_folder_path = staticmethod( + ShippingSettingsServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + ShippingSettingsServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + ShippingSettingsServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + ShippingSettingsServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + ShippingSettingsServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + ShippingSettingsServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + ShippingSettingsServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -110,7 +147,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 +212,20 @@ def universe_domain(self) -> str: get_transport_class = ShippingSettingsServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = "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, + ShippingSettingsServiceTransport, + Callable[..., ShippingSettingsServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the shipping settings service async client. Args: @@ -233,31 +280,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.accounts_v1.ShippingSettingsServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", - "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.accounts.v1.ShippingSettingsService", "credentialsType": None, - } + }, ) - async def get_shipping_settings(self, - request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: + async def get_shipping_settings( + self, + request: Optional[ + Union[shippingsettings.GetShippingSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: r"""Retrieve shipping setting information. .. code-block:: python @@ -317,10 +374,14 @@ async def sample_get_shipping_settings(): # - 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. @@ -334,14 +395,14 @@ async def sample_get_shipping_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_shipping_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_shipping_settings + ] # 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. @@ -358,13 +419,16 @@ async def sample_get_shipping_settings(): # Done; return the response. return response - async def insert_shipping_settings(self, - request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: + async def insert_shipping_settings( + self, + request: Optional[ + Union[shippingsettings.InsertShippingSettingsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: r"""Replace the shipping setting of a business with the request shipping setting. Executing this method requires admin access. @@ -428,14 +492,14 @@ async def sample_insert_shipping_settings(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.insert_shipping_settings] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.insert_shipping_settings + ] # 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. @@ -458,12 +522,13 @@ async def __aenter__(self) -> "ShippingSettingsServiceAsyncClient": 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__ = ( - "ShippingSettingsServiceAsyncClient", -) +__all__ = ("ShippingSettingsServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py index c83008848825..40d0b34414a3 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,7 +62,8 @@ _LOGGER = std_logging.getLogger(__name__) from google.shopping.merchant_accounts_v1.types import shippingsettings -from .transports.base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, ShippingSettingsServiceTransport from .transports.grpc import ShippingSettingsServiceGrpcTransport from .transports.grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport from .transports.rest import ShippingSettingsServiceRestTransport @@ -62,14 +76,18 @@ class ShippingSettingsServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ShippingSettingsServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ShippingSettingsServiceTransport]] _transport_registry["grpc"] = ShippingSettingsServiceGrpcTransport _transport_registry["grpc_asyncio"] = ShippingSettingsServiceGrpcAsyncIOTransport _transport_registry["rest"] = ShippingSettingsServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ShippingSettingsServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ShippingSettingsServiceTransport]: """Returns an appropriate transport class. Args: @@ -163,8 +181,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: ShippingSettingsServiceClient: 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,84 +198,116 @@ def transport(self) -> ShippingSettingsServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def shipping_settings_path(account: str,) -> str: + def shipping_settings_path( + account: str, + ) -> str: """Returns a fully-qualified shipping_settings string.""" - return "accounts/{account}/shippingSettings".format(account=account, ) + return "accounts/{account}/shippingSettings".format( + account=account, + ) @staticmethod - def parse_shipping_settings_path(path: str) -> Dict[str,str]: + def parse_shipping_settings_path(path: str) -> Dict[str, str]: """Parses a shipping_settings path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/shippingSettings$", 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: @@ -290,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 @@ -312,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 @@ -333,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 @@ -362,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: @@ -378,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 = ShippingSettingsServiceClient._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 = ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + ShippingSettingsServiceClient._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: @@ -424,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 @@ -465,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, ShippingSettingsServiceTransport, Callable[..., ShippingSettingsServiceTransport]]] = 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, + ShippingSettingsServiceTransport, + Callable[..., ShippingSettingsServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the shipping settings service client. Args: @@ -525,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 = ShippingSettingsServiceClient._read_environment_variables() - self._client_cert_source = ShippingSettingsServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ShippingSettingsServiceClient._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, + ) = ShippingSettingsServiceClient._read_environment_variables() + self._client_cert_source = ( + ShippingSettingsServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ShippingSettingsServiceClient._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 @@ -543,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 @@ -552,8 +652,10 @@ def __init__(self, *, if transport_provided: # transport is a ShippingSettingsServiceTransport 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 " @@ -562,20 +664,30 @@ def __init__(self, *, self._transport = cast(ShippingSettingsServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - ShippingSettingsServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or ShippingSettingsServiceClient._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[ShippingSettingsServiceTransport], Callable[..., ShippingSettingsServiceTransport]] = ( + transport_init: Union[ + Type[ShippingSettingsServiceTransport], + Callable[..., ShippingSettingsServiceTransport], + ] = ( ShippingSettingsServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., ShippingSettingsServiceTransport], transport) @@ -594,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.accounts_v1.ShippingSettingsServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", - "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.accounts.v1.ShippingSettingsService", "credentialsType": None, - } + }, ) - def get_shipping_settings(self, - request: Optional[Union[shippingsettings.GetShippingSettingsRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: + def get_shipping_settings( + self, + request: Optional[ + Union[shippingsettings.GetShippingSettingsRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: r"""Retrieve shipping setting information. .. code-block:: python @@ -675,10 +798,14 @@ def sample_get_shipping_settings(): # - 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. @@ -696,9 +823,7 @@ def sample_get_shipping_settings(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -715,13 +840,16 @@ def sample_get_shipping_settings(): # Done; return the response. return response - def insert_shipping_settings(self, - request: Optional[Union[shippingsettings.InsertShippingSettingsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> shippingsettings.ShippingSettings: + def insert_shipping_settings( + self, + request: Optional[ + Union[shippingsettings.InsertShippingSettingsRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: r"""Replace the shipping setting of a business with the request shipping setting. Executing this method requires admin access. @@ -790,9 +918,7 @@ def sample_insert_shipping_settings(): # 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,16 +949,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__ = ( - "ShippingSettingsServiceClient", -) +__all__ = ("ShippingSettingsServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py index cbb84e1b0a91..60da5c508a9e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import ShippingSettingsServiceTransport from .grpc import ShippingSettingsServiceGrpcTransport from .grpc_asyncio import ShippingSettingsServiceGrpcAsyncIOTransport -from .rest import ShippingSettingsServiceRestTransport -from .rest import ShippingSettingsServiceRestInterceptor - +from .rest import ( + ShippingSettingsServiceRestInterceptor, + ShippingSettingsServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ShippingSettingsServiceTransport]] -_transport_registry['grpc'] = ShippingSettingsServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ShippingSettingsServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ShippingSettingsServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[ShippingSettingsServiceTransport]] +_transport_registry["grpc"] = ShippingSettingsServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ShippingSettingsServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ShippingSettingsServiceRestTransport __all__ = ( - 'ShippingSettingsServiceTransport', - 'ShippingSettingsServiceGrpcTransport', - 'ShippingSettingsServiceGrpcAsyncIOTransport', - 'ShippingSettingsServiceRestTransport', - 'ShippingSettingsServiceRestInterceptor', + "ShippingSettingsServiceTransport", + "ShippingSettingsServiceGrpcTransport", + "ShippingSettingsServiceGrpcAsyncIOTransport", + "ShippingSettingsServiceRestTransport", + "ShippingSettingsServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py index 960e9328bda1..10b6bf9d4bfa 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import shippingsettings -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__ @@ -38,24 +39,23 @@ class ShippingSettingsServiceTransport(abc.ABC): """Abstract transport class for ShippingSettingsService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,39 @@ 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 get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - Union[ - shippingsettings.ShippingSettings, - Awaitable[shippingsettings.ShippingSettings] - ]]: + def get_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + Union[ + shippingsettings.ShippingSettings, + Awaitable[shippingsettings.ShippingSettings], + ], + ]: raise NotImplementedError() @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - Union[ - shippingsettings.ShippingSettings, - Awaitable[shippingsettings.ShippingSettings] - ]]: + def insert_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + Union[ + shippingsettings.ShippingSettings, + Awaitable[shippingsettings.ShippingSettings], + ], + ]: raise NotImplementedError() @property @@ -168,6 +182,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'ShippingSettingsServiceTransport', -) +__all__ = ("ShippingSettingsServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py similarity index 84% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py index 477d03cf4f7f..f0bd0d1704a0 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import shippingsettings -from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, ShippingSettingsServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": client_call_details.method, "response": grpc_response, @@ -114,23 +120,26 @@ class ShippingSettingsServiceGrpcTransport(ShippingSettingsServiceTransport): 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,20 @@ 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 get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - shippingsettings.ShippingSettings]: + def get_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], shippingsettings.ShippingSettings + ]: r"""Return a callable for the get shipping settings method over gRPC. Retrieve shipping setting information. @@ -326,18 +340,21 @@ def get_shipping_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_shipping_settings' not in self._stubs: - self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ShippingSettingsService/GetShippingSettings', + if "get_shipping_settings" not in self._stubs: + self._stubs["get_shipping_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ShippingSettingsService/GetShippingSettings", request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, response_deserializer=shippingsettings.ShippingSettings.deserialize, ) - return self._stubs['get_shipping_settings'] + return self._stubs["get_shipping_settings"] @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - shippingsettings.ShippingSettings]: + def insert_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + shippingsettings.ShippingSettings, + ]: r"""Return a callable for the insert shipping settings method over gRPC. Replace the shipping setting of a business with the @@ -354,13 +371,13 @@ def insert_shipping_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'insert_shipping_settings' not in self._stubs: - self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ShippingSettingsService/InsertShippingSettings', + if "insert_shipping_settings" not in self._stubs: + self._stubs["insert_shipping_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ShippingSettingsService/InsertShippingSettings", request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, response_deserializer=shippingsettings.ShippingSettings.deserialize, ) - return self._stubs['insert_shipping_settings'] + return self._stubs["insert_shipping_settings"] def close(self): self._logged_channel.close() @@ -370,6 +387,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'ShippingSettingsServiceGrpcTransport', -) +__all__ = ("ShippingSettingsServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py index 275ed2b5daa2..4f135bc588eb 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import shippingsettings -from .base import ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, ShippingSettingsServiceTransport from .grpc import ShippingSettingsServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -123,13 +131,15 @@ class ShippingSettingsServiceGrpcAsyncIOTransport(ShippingSettingsServiceTranspo _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 get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - Awaitable[shippingsettings.ShippingSettings]]: + def get_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], + Awaitable[shippingsettings.ShippingSettings], + ]: r"""Return a callable for the get shipping settings method over gRPC. Retrieve shipping setting information. @@ -332,18 +349,21 @@ def get_shipping_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_shipping_settings' not in self._stubs: - self._stubs['get_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ShippingSettingsService/GetShippingSettings', + if "get_shipping_settings" not in self._stubs: + self._stubs["get_shipping_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ShippingSettingsService/GetShippingSettings", request_serializer=shippingsettings.GetShippingSettingsRequest.serialize, response_deserializer=shippingsettings.ShippingSettings.deserialize, ) - return self._stubs['get_shipping_settings'] + return self._stubs["get_shipping_settings"] @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - Awaitable[shippingsettings.ShippingSettings]]: + def insert_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + Awaitable[shippingsettings.ShippingSettings], + ]: r"""Return a callable for the insert shipping settings method over gRPC. Replace the shipping setting of a business with the @@ -360,16 +380,16 @@ def insert_shipping_settings(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'insert_shipping_settings' not in self._stubs: - self._stubs['insert_shipping_settings'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.ShippingSettingsService/InsertShippingSettings', + if "insert_shipping_settings" not in self._stubs: + self._stubs["insert_shipping_settings"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.ShippingSettingsService/InsertShippingSettings", request_serializer=shippingsettings.InsertShippingSettingsRequest.serialize, response_deserializer=shippingsettings.ShippingSettings.deserialize, ) - return self._stubs['insert_shipping_settings'] + return self._stubs["insert_shipping_settings"] 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.get_shipping_settings: self._wrap_method( self.get_shipping_settings, @@ -396,6 +416,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'ShippingSettingsServiceGrpcAsyncIOTransport', -) +__all__ = ("ShippingSettingsServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py index cbade75bcb65..69e9e370bb95 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import shippingsettings - -from .rest_base import _BaseShippingSettingsServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseShippingSettingsServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,15 @@ def post_insert_shipping_settings(self, response): """ - def pre_get_shipping_settings(self, request: shippingsettings.GetShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.GetShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_shipping_settings( + self, + request: shippingsettings.GetShippingSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + shippingsettings.GetShippingSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_shipping_settings Override in a subclass to manipulate the request or metadata @@ -106,7 +109,9 @@ def pre_get_shipping_settings(self, request: shippingsettings.GetShippingSetting """ return request, metadata - def post_get_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: + def post_get_shipping_settings( + self, response: shippingsettings.ShippingSettings + ) -> shippingsettings.ShippingSettings: """Post-rpc interceptor for get_shipping_settings DEPRECATED. Please use the `post_get_shipping_settings_with_metadata` @@ -119,7 +124,13 @@ def post_get_shipping_settings(self, response: shippingsettings.ShippingSettings """ return response - def post_get_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_shipping_settings_with_metadata( + self, + response: shippingsettings.ShippingSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for get_shipping_settings Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +145,14 @@ def post_get_shipping_settings_with_metadata(self, response: shippingsettings.Sh """ return response, metadata - def pre_insert_shipping_settings(self, request: shippingsettings.InsertShippingSettingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.InsertShippingSettingsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_insert_shipping_settings( + self, + request: shippingsettings.InsertShippingSettingsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + shippingsettings.InsertShippingSettingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for insert_shipping_settings Override in a subclass to manipulate the request or metadata @@ -142,7 +160,9 @@ def pre_insert_shipping_settings(self, request: shippingsettings.InsertShippingS """ return request, metadata - def post_insert_shipping_settings(self, response: shippingsettings.ShippingSettings) -> shippingsettings.ShippingSettings: + def post_insert_shipping_settings( + self, response: shippingsettings.ShippingSettings + ) -> shippingsettings.ShippingSettings: """Post-rpc interceptor for insert_shipping_settings DEPRECATED. Please use the `post_insert_shipping_settings_with_metadata` @@ -155,7 +175,13 @@ def post_insert_shipping_settings(self, response: shippingsettings.ShippingSetti """ return response - def post_insert_shipping_settings_with_metadata(self, response: shippingsettings.ShippingSettings, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_insert_shipping_settings_with_metadata( + self, + response: shippingsettings.ShippingSettings, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + shippingsettings.ShippingSettings, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Post-rpc interceptor for insert_shipping_settings Override in a subclass to read or manipulate the response or metadata after it @@ -191,20 +217,21 @@ class ShippingSettingsServiceRestTransport(_BaseShippingSettingsServiceRestTrans 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[ShippingSettingsServiceRestInterceptor] = 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[ShippingSettingsServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -247,16 +274,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 ShippingSettingsServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _GetShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings, ShippingSettingsServiceRestStub): + class _GetShippingSettings( + _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings, + ShippingSettingsServiceRestStub, + ): def __hash__(self): return hash("ShippingSettingsServiceRestTransport.GetShippingSettings") @@ -268,26 +299,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: shippingsettings.GetShippingSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> shippingsettings.ShippingSettings: + def __call__( + self, + request: shippingsettings.GetShippingSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: r"""Call the get shipping settings method over HTTP. Args: @@ -311,30 +344,42 @@ def __call__(self, """ - http_options = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_http_options() + http_options = ( + _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_get_shipping_settings(request, metadata) - transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_shipping_settings( + request, metadata + ) + transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ShippingSettingsServiceClient.GetShippingSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": "GetShippingSettings", "httpRequest": http_request, @@ -343,7 +388,16 @@ def __call__(self, ) # Send the request - response = ShippingSettingsServiceRestTransport._GetShippingSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + ShippingSettingsServiceRestTransport._GetShippingSettings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -358,20 +412,26 @@ def __call__(self, resp = self._interceptor.post_get_shipping_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_shipping_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_shipping_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = shippingsettings.ShippingSettings.to_json(response) + response_payload = shippingsettings.ShippingSettings.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.accounts_v1.ShippingSettingsServiceClient.get_shipping_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": "GetShippingSettings", "metadata": http_response["headers"], @@ -380,7 +440,10 @@ def __call__(self, ) return resp - class _InsertShippingSettings(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings, ShippingSettingsServiceRestStub): + class _InsertShippingSettings( + _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings, + ShippingSettingsServiceRestStub, + ): def __hash__(self): return hash("ShippingSettingsServiceRestTransport.InsertShippingSettings") @@ -392,27 +455,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: shippingsettings.InsertShippingSettingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> shippingsettings.ShippingSettings: + def __call__( + self, + request: shippingsettings.InsertShippingSettingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> shippingsettings.ShippingSettings: r"""Call the insert shipping settings method over HTTP. Args: @@ -437,32 +502,46 @@ def __call__(self, """ - http_options = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_http_options() + http_options = ( + _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_http_options() + ) - request, metadata = self._interceptor.pre_insert_shipping_settings(request, metadata) - transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_insert_shipping_settings( + request, metadata + ) + transcoded_request = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_transcoded_request( + http_options, request + ) - body = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_request_body_json(transcoded_request) + body = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.ShippingSettingsServiceClient.InsertShippingSettings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": "InsertShippingSettings", "httpRequest": http_request, @@ -471,7 +550,15 @@ def __call__(self, ) # Send the request - response = ShippingSettingsServiceRestTransport._InsertShippingSettings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = ShippingSettingsServiceRestTransport._InsertShippingSettings._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. @@ -486,20 +573,26 @@ def __call__(self, resp = self._interceptor.post_insert_shipping_settings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_shipping_settings_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_insert_shipping_settings_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = shippingsettings.ShippingSettings.to_json(response) + response_payload = shippingsettings.ShippingSettings.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.accounts_v1.ShippingSettingsServiceClient.insert_shipping_settings", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.ShippingSettingsService", "rpcName": "InsertShippingSettings", "metadata": http_response["headers"], @@ -509,20 +602,25 @@ def __call__(self, return resp @property - def get_shipping_settings(self) -> Callable[ - [shippingsettings.GetShippingSettingsRequest], - shippingsettings.ShippingSettings]: + def get_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.GetShippingSettingsRequest], shippingsettings.ShippingSettings + ]: # 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._GetShippingSettings(self._session, self._host, self._interceptor) # type: ignore + return self._GetShippingSettings(self._session, self._host, self._interceptor) # type: ignore @property - def insert_shipping_settings(self) -> Callable[ - [shippingsettings.InsertShippingSettingsRequest], - shippingsettings.ShippingSettings]: + def insert_shipping_settings( + self, + ) -> Callable[ + [shippingsettings.InsertShippingSettingsRequest], + shippingsettings.ShippingSettings, + ]: # 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._InsertShippingSettings(self._session, self._host, self._interceptor) # type: ignore + return self._InsertShippingSettings(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -532,6 +630,4 @@ def close(self): self._session.close() -__all__=( - 'ShippingSettingsServiceRestTransport', -) +__all__ = ("ShippingSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py index 8d95b4704766..c826885b3b5f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/shipping_settings_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 ShippingSettingsServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import shippingsettings +from .base import DEFAULT_CLIENT_INFO, ShippingSettingsServiceTransport + class _BaseShippingSettingsServiceRestTransport(ShippingSettingsServiceTransport): """Base REST backend transport for ShippingSettingsService. @@ -40,14 +38,16 @@ class _BaseShippingSettingsServiceRestTransport(ShippingSettingsServiceTransport 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,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 _BaseGetShippingSettings: 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': '/accounts/v1/{name=accounts/*/shippingSettings}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/shippingSettings}", + }, ] return http_options @@ -113,11 +119,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(_BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._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( + _BaseShippingSettingsServiceRestTransport._BaseGetShippingSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,20 +138,24 @@ class _BaseInsertShippingSettings: 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': '/accounts/v1/{parent=accounts/*}/shippingSettings:insert', - 'body': 'shipping_setting', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/shippingSettings:insert", + "body": "shipping_setting", + }, ] return http_options @@ -154,22 +170,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._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( + _BaseShippingSettingsServiceRestTransport._BaseInsertShippingSettings._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseShippingSettingsServiceRestTransport', -) +__all__ = ("_BaseShippingSettingsServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py similarity index 87% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py index c0461009811b..408a77f80f91 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import TermsOfServiceAgreementStateServiceClient from .async_client import TermsOfServiceAgreementStateServiceAsyncClient +from .client import TermsOfServiceAgreementStateServiceClient __all__ = ( - 'TermsOfServiceAgreementStateServiceClient', - 'TermsOfServiceAgreementStateServiceAsyncClient', + "TermsOfServiceAgreementStateServiceClient", + "TermsOfServiceAgreementStateServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py similarity index 75% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py index 75f8a39efc66..c68831aafb40 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/async_client.py @@ -13,41 +13,61 @@ # 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_accounts_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_accounts_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_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind -from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from google.shopping.merchant_accounts_v1.types import ( + termsofserviceagreementstate, + termsofservicekind, +) + from .client import TermsOfServiceAgreementStateServiceClient +from .transports.base import ( + DEFAULT_CLIENT_INFO, + TermsOfServiceAgreementStateServiceTransport, +) +from .transports.grpc_asyncio import ( + TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, +) 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 TermsOfServiceAgreementStateServiceAsyncClient: """Service to support ``TermsOfServiceAgreementState`` API.""" @@ -56,26 +76,60 @@ class TermsOfServiceAgreementStateServiceAsyncClient: # Copy defaults from the synchronous client for use here. # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. DEFAULT_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE + DEFAULT_MTLS_ENDPOINT = ( + TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + ) + _DEFAULT_ENDPOINT_TEMPLATE = ( + TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE + ) _DEFAULT_UNIVERSE = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.account_path) - parse_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_account_path) - terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_path) - parse_terms_of_service_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path) - terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path) - parse_terms_of_service_agreement_state_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path) - common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_organization_path) - common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_project_path) - parse_common_project_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_project_path) - common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.common_location_path) - parse_common_location_path = staticmethod(TermsOfServiceAgreementStateServiceClient.parse_common_location_path) + parse_account_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_account_path + ) + terms_of_service_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.terms_of_service_path + ) + parse_terms_of_service_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path + ) + terms_of_service_agreement_state_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path + ) + parse_terms_of_service_agreement_state_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path + ) + common_billing_account_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + TermsOfServiceAgreementStateServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -111,7 +165,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: @@ -174,12 +230,20 @@ def universe_domain(self) -> str: get_transport_class = TermsOfServiceAgreementStateServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = "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, + TermsOfServiceAgreementStateServiceTransport, + Callable[..., TermsOfServiceAgreementStateServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the terms of service agreement state service async client. Args: @@ -234,31 +298,44 @@ 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.accounts_v1.TermsOfServiceAgreementStateServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", - "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.accounts.v1.TermsOfServiceAgreementStateService", "credentialsType": None, - } + }, ) - async def get_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + async def get_terms_of_service_agreement_state( + self, + request: Optional[ + Union[ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Returns the state of a terms of service agreement. .. code-block:: python @@ -343,15 +420,25 @@ async def sample_get_terms_of_service_agreement_state(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(request) + if not isinstance( + request, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest + ): + request = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -360,14 +447,14 @@ async def sample_get_terms_of_service_agreement_state(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_terms_of_service_agreement_state] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_terms_of_service_agreement_state + ] # 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. @@ -384,14 +471,20 @@ async def sample_get_terms_of_service_agreement_state(): # Done; return the response. return response - async def retrieve_for_application_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + async def retrieve_for_application_terms_of_service_agreement_state( + self, + request: Optional[ + Union[ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + 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]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Retrieves the state of the agreement for the application terms of service. Application terms of service covers permissions related @@ -479,15 +572,24 @@ async def sample_retrieve_for_application_terms_of_service_agreement_state(): # - 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. - if not isinstance(request, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(request) + if not isinstance( + request, + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + ): + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -496,14 +598,14 @@ async def sample_retrieve_for_application_terms_of_service_agreement_state(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.retrieve_for_application_terms_of_service_agreement_state] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_for_application_terms_of_service_agreement_state + ] # 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. @@ -526,12 +628,13 @@ async def __aenter__(self) -> "TermsOfServiceAgreementStateServiceAsyncClient": 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__ = ( - "TermsOfServiceAgreementStateServiceAsyncClient", -) +__all__ = ("TermsOfServiceAgreementStateServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py similarity index 74% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py index 99e175d5b10a..8b5d8de619fb 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,17 +54,26 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind -from .transports.base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_accounts_v1.types import ( + termsofserviceagreementstate, + termsofservicekind, +) + +from .transports.base import ( + DEFAULT_CLIENT_INFO, + TermsOfServiceAgreementStateServiceTransport, +) from .transports.grpc import TermsOfServiceAgreementStateServiceGrpcTransport -from .transports.grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +from .transports.grpc_asyncio import ( + TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, +) from .transports.rest import TermsOfServiceAgreementStateServiceRestTransport @@ -63,14 +84,20 @@ class TermsOfServiceAgreementStateServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] _transport_registry["grpc"] = TermsOfServiceAgreementStateServiceGrpcTransport - _transport_registry["grpc_asyncio"] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport + _transport_registry[ + "grpc_asyncio" + ] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport _transport_registry["rest"] = TermsOfServiceAgreementStateServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TermsOfServiceAgreementStateServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[TermsOfServiceAgreementStateServiceTransport]: """Returns an appropriate transport class. Args: @@ -89,7 +116,9 @@ def get_transport_class(cls, return next(iter(cls._transport_registry.values())) -class TermsOfServiceAgreementStateServiceClient(metaclass=TermsOfServiceAgreementStateServiceClientMeta): +class TermsOfServiceAgreementStateServiceClient( + metaclass=TermsOfServiceAgreementStateServiceClientMeta +): """Service to support ``TermsOfServiceAgreementState`` API.""" @staticmethod @@ -162,8 +191,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: TermsOfServiceAgreementStateServiceClient: 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) @@ -180,95 +208,136 @@ def transport(self) -> TermsOfServiceAgreementStateServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def terms_of_service_path(version: str,) -> str: + def terms_of_service_path( + version: str, + ) -> str: """Returns a fully-qualified terms_of_service string.""" - return "termsOfService/{version}".format(version=version, ) + return "termsOfService/{version}".format( + version=version, + ) @staticmethod - def parse_terms_of_service_path(path: str) -> Dict[str,str]: + def parse_terms_of_service_path(path: str) -> Dict[str, str]: """Parses a terms_of_service path into its component segments.""" m = re.match(r"^termsOfService/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def terms_of_service_agreement_state_path(account: str,identifier: str,) -> str: + def terms_of_service_agreement_state_path( + account: str, + identifier: str, + ) -> str: """Returns a fully-qualified terms_of_service_agreement_state string.""" - return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format( + account=account, + identifier=identifier, + ) @staticmethod - def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str,str]: + def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str, str]: """Parses a terms_of_service_agreement_state path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?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: @@ -300,16 +369,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 @@ -322,7 +397,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 @@ -343,13 +420,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 @@ -372,7 +455,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: @@ -388,17 +473,29 @@ 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): - _default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ( + TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + ) if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ( + TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + ) else: - api_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = TermsOfServiceAgreementStateServiceClient._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: @@ -434,15 +531,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 @@ -475,12 +575,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TermsOfServiceAgreementStateServiceTransport, Callable[..., TermsOfServiceAgreementStateServiceTransport]]] = 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, + TermsOfServiceAgreementStateServiceTransport, + Callable[..., TermsOfServiceAgreementStateServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the terms of service agreement state service client. Args: @@ -535,14 +643,28 @@ 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 = TermsOfServiceAgreementStateServiceClient._read_environment_variables() - self._client_cert_source = TermsOfServiceAgreementStateServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = TermsOfServiceAgreementStateServiceClient._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, + ) = TermsOfServiceAgreementStateServiceClient._read_environment_variables() + self._client_cert_source = ( + TermsOfServiceAgreementStateServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = ( + TermsOfServiceAgreementStateServiceClient._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 @@ -553,42 +675,63 @@ 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 # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, TermsOfServiceAgreementStateServiceTransport) + transport_provided = isinstance( + transport, TermsOfServiceAgreementStateServiceTransport + ) if transport_provided: # transport is a TermsOfServiceAgreementStateServiceTransport instance. if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if self._client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " "directly." ) - self._transport = cast(TermsOfServiceAgreementStateServiceTransport, transport) + self._transport = cast( + TermsOfServiceAgreementStateServiceTransport, transport + ) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or TermsOfServiceAgreementStateServiceClient._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[TermsOfServiceAgreementStateServiceTransport], Callable[..., TermsOfServiceAgreementStateServiceTransport]] = ( + transport_init: Union[ + Type[TermsOfServiceAgreementStateServiceTransport], + Callable[..., TermsOfServiceAgreementStateServiceTransport], + ] = ( TermsOfServiceAgreementStateServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None - else cast(Callable[..., TermsOfServiceAgreementStateServiceTransport], transport) + else cast( + Callable[..., TermsOfServiceAgreementStateServiceTransport], + transport, + ) ) # initialize with the provided callable or the passed in class self._transport = transport_init( @@ -604,28 +747,42 @@ 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.accounts_v1.TermsOfServiceAgreementStateServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", - "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.accounts.v1.TermsOfServiceAgreementStateService", "credentialsType": None, - } + }, ) - def get_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + def get_terms_of_service_agreement_state( + self, + request: Optional[ + Union[ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Returns the state of a terms of service agreement. .. code-block:: python @@ -710,15 +867,25 @@ def sample_get_terms_of_service_agreement_state(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [name] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. - if not isinstance(request, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(request) + if not isinstance( + request, termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest + ): + request = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -726,14 +893,14 @@ def sample_get_terms_of_service_agreement_state(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_terms_of_service_agreement_state] + rpc = self._transport._wrapped_methods[ + self._transport.get_terms_of_service_agreement_state + ] # 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. @@ -750,14 +917,20 @@ def sample_get_terms_of_service_agreement_state(): # Done; return the response. return response - def retrieve_for_application_terms_of_service_agreement_state(self, - request: Optional[Union[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, 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]]] = (), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + def retrieve_for_application_terms_of_service_agreement_state( + self, + request: Optional[ + Union[ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + 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]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Retrieves the state of the agreement for the application terms of service. Application terms of service covers permissions related @@ -845,15 +1018,24 @@ def sample_retrieve_for_application_terms_of_service_agreement_state(): # - 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. - if not isinstance(request, termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(request) + if not isinstance( + request, + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + ): + request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: @@ -861,14 +1043,14 @@ def sample_retrieve_for_application_terms_of_service_agreement_state(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.retrieve_for_application_terms_of_service_agreement_state] + rpc = self._transport._wrapped_methods[ + self._transport.retrieve_for_application_terms_of_service_agreement_state + ] # 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. @@ -899,16 +1081,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__ = ( - "TermsOfServiceAgreementStateServiceClient", -) +__all__ = ("TermsOfServiceAgreementStateServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py similarity index 55% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py index 3e5e8db05323..d8cbfa9c52df 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/__init__.py @@ -19,20 +19,25 @@ from .base import TermsOfServiceAgreementStateServiceTransport from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport from .grpc_asyncio import TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport -from .rest import TermsOfServiceAgreementStateServiceRestTransport -from .rest import TermsOfServiceAgreementStateServiceRestInterceptor - +from .rest import ( + TermsOfServiceAgreementStateServiceRestInterceptor, + TermsOfServiceAgreementStateServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] -_transport_registry['grpc'] = TermsOfServiceAgreementStateServiceGrpcTransport -_transport_registry['grpc_asyncio'] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport -_transport_registry['rest'] = TermsOfServiceAgreementStateServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[TermsOfServiceAgreementStateServiceTransport]] +_transport_registry["grpc"] = TermsOfServiceAgreementStateServiceGrpcTransport +_transport_registry[ + "grpc_asyncio" +] = TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport +_transport_registry["rest"] = TermsOfServiceAgreementStateServiceRestTransport __all__ = ( - 'TermsOfServiceAgreementStateServiceTransport', - 'TermsOfServiceAgreementStateServiceGrpcTransport', - 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', - 'TermsOfServiceAgreementStateServiceRestTransport', - 'TermsOfServiceAgreementStateServiceRestInterceptor', + "TermsOfServiceAgreementStateServiceTransport", + "TermsOfServiceAgreementStateServiceGrpcTransport", + "TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport", + "TermsOfServiceAgreementStateServiceRestTransport", + "TermsOfServiceAgreementStateServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py index f66f5f861dee..a611b0e742d7 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -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__ @@ -38,24 +39,23 @@ class TermsOfServiceAgreementStateServiceTransport(abc.ABC): """Abstract transport class for TermsOfServiceAgreementStateService.""" - 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: @@ -91,30 +91,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 @@ -134,33 +142,41 @@ 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 get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - Union[ - termsofserviceagreementstate.TermsOfServiceAgreementState, - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] - ]]: + def get_terms_of_service_agreement_state( + self, + ) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + Union[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState], + ], + ]: raise NotImplementedError() @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - Union[ - termsofserviceagreementstate.TermsOfServiceAgreementState, - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState] - ]]: + def retrieve_for_application_terms_of_service_agreement_state( + self, + ) -> Callable[ + [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest + ], + Union[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState], + ], + ]: raise NotImplementedError() @property @@ -168,6 +184,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'TermsOfServiceAgreementStateServiceTransport', -) +__all__ = ("TermsOfServiceAgreementStateServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py index 618bffa5e5a4..ece8165034be 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, TermsOfServiceAgreementStateServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": client_call_details.method, "response": grpc_response, @@ -101,7 +107,9 @@ def intercept_unary_unary(self, continuation, client_call_details, request): return response -class TermsOfServiceAgreementStateServiceGrpcTransport(TermsOfServiceAgreementStateServiceTransport): +class TermsOfServiceAgreementStateServiceGrpcTransport( + TermsOfServiceAgreementStateServiceTransport +): """gRPC backend transport for TermsOfServiceAgreementStateService. Service to support ``TermsOfServiceAgreementState`` API. @@ -113,23 +121,26 @@ class TermsOfServiceAgreementStateServiceGrpcTransport(TermsOfServiceAgreementSt 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: @@ -251,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. @@ -298,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 get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: + def get_terms_of_service_agreement_state( + self, + ) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState, + ]: r"""Return a callable for the get terms of service agreement state method over gRPC. @@ -326,18 +343,25 @@ def get_terms_of_service_agreement_state(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_terms_of_service_agreement_state' not in self._stubs: - self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', + if "get_terms_of_service_agreement_state" not in self._stubs: + self._stubs[ + "get_terms_of_service_agreement_state" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, ) - return self._stubs['get_terms_of_service_agreement_state'] + return self._stubs["get_terms_of_service_agreement_state"] @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: + def retrieve_for_application_terms_of_service_agreement_state( + self, + ) -> Callable[ + [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest + ], + termsofserviceagreementstate.TermsOfServiceAgreementState, + ]: r"""Return a callable for the retrieve for application terms of service agreement state method over gRPC. @@ -357,13 +381,18 @@ def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: - self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', + if ( + "retrieve_for_application_terms_of_service_agreement_state" + not in self._stubs + ): + self._stubs[ + "retrieve_for_application_terms_of_service_agreement_state" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, ) - return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] + return self._stubs["retrieve_for_application_terms_of_service_agreement_state"] def close(self): self._logged_channel.close() @@ -373,6 +402,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'TermsOfServiceAgreementStateServiceGrpcTransport', -) +__all__ = ("TermsOfServiceAgreementStateServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py similarity index 81% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py index dc0729d255d6..20e1db867f2f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from .base import TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, TermsOfServiceAgreementStateServiceTransport from .grpc import TermsOfServiceAgreementStateServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -105,7 +113,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request return response -class TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport(TermsOfServiceAgreementStateServiceTransport): +class TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( + TermsOfServiceAgreementStateServiceTransport +): """gRPC AsyncIO backend transport for TermsOfServiceAgreementStateService. Service to support ``TermsOfServiceAgreementState`` API. @@ -122,13 +132,15 @@ class TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport(TermsOfServiceAgre _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. @@ -158,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: @@ -299,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) @@ -314,9 +330,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: + def get_terms_of_service_agreement_state( + self, + ) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState], + ]: r"""Return a callable for the get terms of service agreement state method over gRPC. @@ -332,18 +351,25 @@ def get_terms_of_service_agreement_state(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_terms_of_service_agreement_state' not in self._stubs: - self._stubs['get_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState', + if "get_terms_of_service_agreement_state" not in self._stubs: + self._stubs[ + "get_terms_of_service_agreement_state" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/GetTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, ) - return self._stubs['get_terms_of_service_agreement_state'] + return self._stubs["get_terms_of_service_agreement_state"] @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState]]: + def retrieve_for_application_terms_of_service_agreement_state( + self, + ) -> Callable[ + [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest + ], + Awaitable[termsofserviceagreementstate.TermsOfServiceAgreementState], + ]: r"""Return a callable for the retrieve for application terms of service agreement state method over gRPC. @@ -363,16 +389,21 @@ def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'retrieve_for_application_terms_of_service_agreement_state' not in self._stubs: - self._stubs['retrieve_for_application_terms_of_service_agreement_state'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState', + if ( + "retrieve_for_application_terms_of_service_agreement_state" + not in self._stubs + ): + self._stubs[ + "retrieve_for_application_terms_of_service_agreement_state" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService/RetrieveForApplicationTermsOfServiceAgreementState", request_serializer=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.serialize, response_deserializer=termsofserviceagreementstate.TermsOfServiceAgreementState.deserialize, ) - return self._stubs['retrieve_for_application_terms_of_service_agreement_state'] + return self._stubs["retrieve_for_application_terms_of_service_agreement_state"] 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.get_terms_of_service_agreement_state: self._wrap_method( self.get_terms_of_service_agreement_state, @@ -399,6 +430,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport', -) +__all__ = ("TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py similarity index 55% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py index e73fb463590d..9f5d8ca77e8a 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import termsofserviceagreementstate - -from .rest_base import _BaseTermsOfServiceAgreementStateServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTermsOfServiceAgreementStateServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -98,7 +93,15 @@ def post_retrieve_for_application_terms_of_service_agreement_state(self, respons """ - def pre_get_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_get_terms_of_service_agreement_state( + self, + request: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for get_terms_of_service_agreement_state Override in a subclass to manipulate the request or metadata @@ -106,7 +109,9 @@ def pre_get_terms_of_service_agreement_state(self, request: termsofserviceagreem """ return request, metadata - def post_get_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + def post_get_terms_of_service_agreement_state( + self, response: termsofserviceagreementstate.TermsOfServiceAgreementState + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: """Post-rpc interceptor for get_terms_of_service_agreement_state DEPRECATED. Please use the `post_get_terms_of_service_agreement_state_with_metadata` @@ -119,7 +124,14 @@ def post_get_terms_of_service_agreement_state(self, response: termsofserviceagre """ return response - def post_get_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_terms_of_service_agreement_state_with_metadata( + self, + response: termsofserviceagreementstate.TermsOfServiceAgreementState, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for get_terms_of_service_agreement_state Override in a subclass to read or manipulate the response or metadata after it @@ -134,7 +146,14 @@ def post_get_terms_of_service_agreement_state_with_metadata(self, response: term """ return response, metadata - def pre_retrieve_for_application_terms_of_service_agreement_state(self, request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_retrieve_for_application_terms_of_service_agreement_state( + self, + request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state Override in a subclass to manipulate the request or metadata @@ -142,7 +161,9 @@ def pre_retrieve_for_application_terms_of_service_agreement_state(self, request: """ return request, metadata - def post_retrieve_for_application_terms_of_service_agreement_state(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + def post_retrieve_for_application_terms_of_service_agreement_state( + self, response: termsofserviceagreementstate.TermsOfServiceAgreementState + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state DEPRECATED. Please use the `post_retrieve_for_application_terms_of_service_agreement_state_with_metadata` @@ -155,7 +176,14 @@ def post_retrieve_for_application_terms_of_service_agreement_state(self, respons """ return response - def post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(self, response: termsofserviceagreementstate.TermsOfServiceAgreementState, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofserviceagreementstate.TermsOfServiceAgreementState, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_retrieve_for_application_terms_of_service_agreement_state_with_metadata( + self, + response: termsofserviceagreementstate.TermsOfServiceAgreementState, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofserviceagreementstate.TermsOfServiceAgreementState, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for retrieve_for_application_terms_of_service_agreement_state Override in a subclass to read or manipulate the response or metadata after it @@ -178,7 +206,9 @@ class TermsOfServiceAgreementStateServiceRestStub: _interceptor: TermsOfServiceAgreementStateServiceRestInterceptor -class TermsOfServiceAgreementStateServiceRestTransport(_BaseTermsOfServiceAgreementStateServiceRestTransport): +class TermsOfServiceAgreementStateServiceRestTransport( + _BaseTermsOfServiceAgreementStateServiceRestTransport +): """REST backend synchronous transport for TermsOfServiceAgreementStateService. Service to support ``TermsOfServiceAgreementState`` API. @@ -190,20 +220,23 @@ class TermsOfServiceAgreementStateServiceRestTransport(_BaseTermsOfServiceAgreem 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[TermsOfServiceAgreementStateServiceRestInterceptor] = 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[ + TermsOfServiceAgreementStateServiceRestInterceptor + ] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -246,18 +279,26 @@ 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 TermsOfServiceAgreementStateServiceRestInterceptor() + self._interceptor = ( + interceptor or TermsOfServiceAgreementStateServiceRestInterceptor() + ) self._prep_wrapped_messages(client_info) - class _GetTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): + class _GetTermsOfServiceAgreementState( + _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState, + TermsOfServiceAgreementStateServiceRestStub, + ): def __hash__(self): - return hash("TermsOfServiceAgreementStateServiceRestTransport.GetTermsOfServiceAgreementState") + return hash( + "TermsOfServiceAgreementStateServiceRestTransport.GetTermsOfServiceAgreementState" + ) @staticmethod def _get_response( @@ -267,97 +308,114 @@ 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: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + def __call__( + self, + request: termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Call the get terms of service - agreement state method over HTTP. - - Args: - request (~.termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): - The request object. Request message for the - ``GetTermsOfServiceAgreementState`` 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: - ~.termsofserviceagreementstate.TermsOfServiceAgreementState: - This resource represents the agreement state for a given - account and terms of service kind. The state is as - follows: - - - If the business has accepted a terms of service, - [``accepted``][google.shopping.merchant.accounts.v1.Accepted] - will be populated, otherwise it will be empty - - If the business must sign a terms of service, - [``required``][google.shopping.merchant.accounts.v1.Required] - will be populated, otherwise it will be empty. - - Note that both ``required`` and ``accepted`` can be - present. In this case the ``accepted`` terms of services - will have an expiration date set in the - [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] - field. The ``required`` terms of services need to be - accepted before ``valid_until`` in order for the account - to continue having a valid agreement. When accepting new - terms of services we expect third-party providers to - display the text associated with the given terms of - service agreement (the url to the file containing the - text is added in the Required message below as - [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). - The actual acceptance of the terms of service is done by - calling accept on the - [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] - resource. ``valid_until`` field. + agreement state method over HTTP. + + Args: + request (~.termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): + The request object. Request message for the + ``GetTermsOfServiceAgreementState`` 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: + ~.termsofserviceagreementstate.TermsOfServiceAgreementState: + This resource represents the agreement state for a given + account and terms of service kind. The state is as + follows: + + - If the business has accepted a terms of service, + [``accepted``][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty + - If the business must sign a terms of service, + [``required``][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both ``required`` and ``accepted`` can be + present. In this case the ``accepted`` terms of services + will have an expiration date set in the + [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The ``required`` terms of services need to be + accepted before ``valid_until`` in order for the account + to continue having a valid agreement. When accepting new + terms of services we expect third-party providers to + display the text associated with the given terms of + service agreement (the url to the file containing the + text is added in the Required message below as + [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done by + calling accept on the + [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. ``valid_until`` field. """ - http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_http_options() + http_options = ( + _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_http_options() + ) - request, metadata = self._interceptor.pre_get_terms_of_service_agreement_state(request, metadata) - transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_transcoded_request(http_options, request) + ( + request, + metadata, + ) = self._interceptor.pre_get_terms_of_service_agreement_state( + request, metadata + ) + transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceAgreementStateServiceClient.GetTermsOfServiceAgreementState", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": "GetTermsOfServiceAgreementState", "httpRequest": http_request, @@ -366,7 +424,14 @@ def __call__(self, ) # Send the request - response = TermsOfServiceAgreementStateServiceRestTransport._GetTermsOfServiceAgreementState._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = TermsOfServiceAgreementStateServiceRestTransport._GetTermsOfServiceAgreementState._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -381,20 +446,29 @@ def __call__(self, resp = self._interceptor.post_get_terms_of_service_agreement_state(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_terms_of_service_agreement_state_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_get_terms_of_service_agreement_state_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(response) + response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1.TermsOfServiceAgreementStateServiceClient.get_terms_of_service_agreement_state", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": "GetTermsOfServiceAgreementState", "metadata": http_response["headers"], @@ -403,9 +477,14 @@ def __call__(self, ) return resp - class _RetrieveForApplicationTermsOfServiceAgreementState(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState, TermsOfServiceAgreementStateServiceRestStub): + class _RetrieveForApplicationTermsOfServiceAgreementState( + _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState, + TermsOfServiceAgreementStateServiceRestStub, + ): def __hash__(self): - return hash("TermsOfServiceAgreementStateServiceRestTransport.RetrieveForApplicationTermsOfServiceAgreementState") + return hash( + "TermsOfServiceAgreementStateServiceRestTransport.RetrieveForApplicationTermsOfServiceAgreementState" + ) @staticmethod def _get_response( @@ -415,98 +494,115 @@ 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: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: + def __call__( + self, + request: termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofserviceagreementstate.TermsOfServiceAgreementState: r"""Call the retrieve for application - terms of service agreement state method over HTTP. - - Args: - request (~.termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): - The request object. Request message for the - ``RetrieveForApplicationTermsOfServiceAgreementState`` - 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: - ~.termsofserviceagreementstate.TermsOfServiceAgreementState: - This resource represents the agreement state for a given - account and terms of service kind. The state is as - follows: - - - If the business has accepted a terms of service, - [``accepted``][google.shopping.merchant.accounts.v1.Accepted] - will be populated, otherwise it will be empty - - If the business must sign a terms of service, - [``required``][google.shopping.merchant.accounts.v1.Required] - will be populated, otherwise it will be empty. - - Note that both ``required`` and ``accepted`` can be - present. In this case the ``accepted`` terms of services - will have an expiration date set in the - [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] - field. The ``required`` terms of services need to be - accepted before ``valid_until`` in order for the account - to continue having a valid agreement. When accepting new - terms of services we expect third-party providers to - display the text associated with the given terms of - service agreement (the url to the file containing the - text is added in the Required message below as - [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). - The actual acceptance of the terms of service is done by - calling accept on the - [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] - resource. ``valid_until`` field. + terms of service agreement state method over HTTP. + + Args: + request (~.termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): + The request object. Request message for the + ``RetrieveForApplicationTermsOfServiceAgreementState`` + 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: + ~.termsofserviceagreementstate.TermsOfServiceAgreementState: + This resource represents the agreement state for a given + account and terms of service kind. The state is as + follows: + + - If the business has accepted a terms of service, + [``accepted``][google.shopping.merchant.accounts.v1.Accepted] + will be populated, otherwise it will be empty + - If the business must sign a terms of service, + [``required``][google.shopping.merchant.accounts.v1.Required] + will be populated, otherwise it will be empty. + + Note that both ``required`` and ``accepted`` can be + present. In this case the ``accepted`` terms of services + will have an expiration date set in the + [``valid_until``][google.shopping.merchant.accounts.v1.Accepted.valid_until] + field. The ``required`` terms of services need to be + accepted before ``valid_until`` in order for the account + to continue having a valid agreement. When accepting new + terms of services we expect third-party providers to + display the text associated with the given terms of + service agreement (the url to the file containing the + text is added in the Required message below as + [``tos_file_uri``][google.shopping.merchant.accounts.v1.Required.tos_file_uri]). + The actual acceptance of the terms of service is done by + calling accept on the + [``TermsOfService``][google.shopping.merchant.accounts.v1.Accepted.terms_of_service] + resource. ``valid_until`` field. """ - http_options = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_http_options() + http_options = ( + _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_http_options() + ) - request, metadata = self._interceptor.pre_retrieve_for_application_terms_of_service_agreement_state(request, metadata) - transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_transcoded_request(http_options, request) + ( + request, + metadata, + ) = self._interceptor.pre_retrieve_for_application_terms_of_service_agreement_state( + request, metadata + ) + transcoded_request = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceAgreementStateServiceClient.RetrieveForApplicationTermsOfServiceAgreementState", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", "httpRequest": http_request, @@ -515,7 +611,14 @@ def __call__(self, ) # Send the request - response = TermsOfServiceAgreementStateServiceRestTransport._RetrieveForApplicationTermsOfServiceAgreementState._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = TermsOfServiceAgreementStateServiceRestTransport._RetrieveForApplicationTermsOfServiceAgreementState._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -528,22 +631,33 @@ def __call__(self, json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state(resp) + resp = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_retrieve_for_application_terms_of_service_agreement_state_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(response) + response_payload = termsofserviceagreementstate.TermsOfServiceAgreementState.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.accounts_v1.TermsOfServiceAgreementStateServiceClient.retrieve_for_application_terms_of_service_agreement_state", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceAgreementStateService", "rpcName": "RetrieveForApplicationTermsOfServiceAgreementState", "metadata": http_response["headers"], @@ -553,20 +667,28 @@ def __call__(self, return resp @property - def get_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: + def get_terms_of_service_agreement_state( + self, + ) -> Callable[ + [termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest], + termsofserviceagreementstate.TermsOfServiceAgreementState, + ]: # 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._GetTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore + return self._GetTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore @property - def retrieve_for_application_terms_of_service_agreement_state(self) -> Callable[ - [termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest], - termsofserviceagreementstate.TermsOfServiceAgreementState]: + def retrieve_for_application_terms_of_service_agreement_state( + self, + ) -> Callable[ + [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest + ], + termsofserviceagreementstate.TermsOfServiceAgreementState, + ]: # 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._RetrieveForApplicationTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore + return self._RetrieveForApplicationTermsOfServiceAgreementState(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -576,6 +698,4 @@ def close(self): self._session.close() -__all__=( - 'TermsOfServiceAgreementStateServiceRestTransport', -) +__all__ = ("TermsOfServiceAgreementStateServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py similarity index 60% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py index b891b391c48e..720e00603320 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_agreement_state_service/transports/rest_base.py @@ -14,20 +14,20 @@ # 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 TermsOfServiceAgreementStateServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate +from .base import DEFAULT_CLIENT_INFO, TermsOfServiceAgreementStateServiceTransport + -class _BaseTermsOfServiceAgreementStateServiceRestTransport(TermsOfServiceAgreementStateServiceTransport): +class _BaseTermsOfServiceAgreementStateServiceRestTransport( + TermsOfServiceAgreementStateServiceTransport +): """Base REST backend transport for TermsOfServiceAgreementStateService. Note: This class is not meant to be used directly. Use its sync and @@ -40,14 +40,16 @@ class _BaseTermsOfServiceAgreementStateServiceRestTransport(TermsOfServiceAgreem 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]): @@ -71,7 +73,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,42 +86,56 @@ 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 _BaseGetTermsOfServiceAgreementState: 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': '/accounts/v1/{name=accounts/*/termsOfServiceAgreementStates/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/termsOfServiceAgreementStates/*}", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.pb(request) + pb_request = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._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( + _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseGetTermsOfServiceAgreementState._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,40 +144,50 @@ class _BaseRetrieveForApplicationTermsOfServiceAgreementState: 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': '/accounts/v1/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication", + }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.pb(request) + pb_request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.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(_BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._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( + _BaseTermsOfServiceAgreementStateServiceRestTransport._BaseRetrieveForApplicationTermsOfServiceAgreementState._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseTermsOfServiceAgreementStateServiceRestTransport', -) +__all__ = ("_BaseTermsOfServiceAgreementStateServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py index 7bfe24f4bb51..73bf31b66afa 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import TermsOfServiceServiceClient from .async_client import TermsOfServiceServiceAsyncClient +from .client import TermsOfServiceServiceClient __all__ = ( - 'TermsOfServiceServiceClient', - 'TermsOfServiceServiceAsyncClient', + "TermsOfServiceServiceClient", + "TermsOfServiceServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py index db2dae66a680..69c66a8fb242 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/async_client.py @@ -13,42 +13,57 @@ # 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_accounts_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_accounts_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_accounts_v1.types import termsofservice -from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind -from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport +from google.shopping.merchant_accounts_v1.types import ( + termsofservice, + termsofserviceagreementstate, + termsofservicekind, +) + from .client import TermsOfServiceServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, TermsOfServiceServiceTransport +from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport 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 TermsOfServiceServiceAsyncClient: """Service to support ``TermsOfService`` API.""" @@ -63,20 +78,44 @@ class TermsOfServiceServiceAsyncClient: account_path = staticmethod(TermsOfServiceServiceClient.account_path) parse_account_path = staticmethod(TermsOfServiceServiceClient.parse_account_path) - terms_of_service_path = staticmethod(TermsOfServiceServiceClient.terms_of_service_path) - parse_terms_of_service_path = staticmethod(TermsOfServiceServiceClient.parse_terms_of_service_path) - terms_of_service_agreement_state_path = staticmethod(TermsOfServiceServiceClient.terms_of_service_agreement_state_path) - parse_terms_of_service_agreement_state_path = staticmethod(TermsOfServiceServiceClient.parse_terms_of_service_agreement_state_path) - common_billing_account_path = staticmethod(TermsOfServiceServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(TermsOfServiceServiceClient.parse_common_billing_account_path) + terms_of_service_path = staticmethod( + TermsOfServiceServiceClient.terms_of_service_path + ) + parse_terms_of_service_path = staticmethod( + TermsOfServiceServiceClient.parse_terms_of_service_path + ) + terms_of_service_agreement_state_path = staticmethod( + TermsOfServiceServiceClient.terms_of_service_agreement_state_path + ) + parse_terms_of_service_agreement_state_path = staticmethod( + TermsOfServiceServiceClient.parse_terms_of_service_agreement_state_path + ) + common_billing_account_path = staticmethod( + TermsOfServiceServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + TermsOfServiceServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(TermsOfServiceServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(TermsOfServiceServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(TermsOfServiceServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(TermsOfServiceServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + TermsOfServiceServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + TermsOfServiceServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + TermsOfServiceServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(TermsOfServiceServiceClient.common_project_path) - parse_common_project_path = staticmethod(TermsOfServiceServiceClient.parse_common_project_path) - common_location_path = staticmethod(TermsOfServiceServiceClient.common_location_path) - parse_common_location_path = staticmethod(TermsOfServiceServiceClient.parse_common_location_path) + parse_common_project_path = staticmethod( + TermsOfServiceServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + TermsOfServiceServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + TermsOfServiceServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -112,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: @@ -175,12 +216,20 @@ def universe_domain(self) -> str: get_transport_class = TermsOfServiceServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = "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, + TermsOfServiceServiceTransport, + Callable[..., TermsOfServiceServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the terms of service service async client. Args: @@ -235,31 +284,39 @@ 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.accounts_v1.TermsOfServiceServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", - "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.accounts.v1.TermsOfServiceService", "credentialsType": None, - } + }, ) - async def get_terms_of_service(self, - request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: + async def get_terms_of_service( + self, + request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: r"""Retrieves the ``TermsOfService`` associated with the provided version. @@ -327,10 +384,14 @@ async def sample_get_terms_of_service(): # - 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. @@ -344,14 +405,14 @@ async def sample_get_terms_of_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_terms_of_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_terms_of_service + ] # 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. @@ -368,13 +429,16 @@ async def sample_get_terms_of_service(): # Done; return the response. return response - async def retrieve_latest_terms_of_service(self, - request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: + async def retrieve_latest_terms_of_service( + self, + request: Optional[ + Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: r"""Retrieves the latest version of the ``TermsOfService`` for a given ``kind`` and ``region_code``. @@ -441,7 +505,9 @@ async def sample_retrieve_latest_terms_of_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.retrieve_latest_terms_of_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_latest_terms_of_service + ] # Validate the universe domain. self._client._validate_universe_domain() @@ -457,14 +523,17 @@ async def sample_retrieve_latest_terms_of_service(): # Done; return the response. return response - async def accept_terms_of_service(self, - request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.AcceptTermsOfServiceResponse: + async def accept_terms_of_service( + self, + request: Optional[ + Union[termsofservice.AcceptTermsOfServiceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.AcceptTermsOfServiceResponse: r"""Accepts a ``TermsOfService``. Executing this method requires admin access. @@ -522,10 +591,14 @@ async def sample_accept_terms_of_service(): # - 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. @@ -539,14 +612,14 @@ async def sample_accept_terms_of_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.accept_terms_of_service] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.accept_terms_of_service + ] # 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. @@ -569,12 +642,13 @@ async def __aenter__(self) -> "TermsOfServiceServiceAsyncClient": 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__ = ( - "TermsOfServiceServiceAsyncClient", -) +__all__ = ("TermsOfServiceServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py similarity index 78% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py index da21398ba440..45c461a049c5 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_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_accounts_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_accounts_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,20 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False _LOGGER = std_logging.getLogger(__name__) -from google.shopping.merchant_accounts_v1.types import termsofservice -from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind -from .transports.base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO +from google.shopping.merchant_accounts_v1.types import ( + termsofservice, + termsofserviceagreementstate, + termsofservicekind, +) + +from .transports.base import DEFAULT_CLIENT_INFO, TermsOfServiceServiceTransport from .transports.grpc import TermsOfServiceServiceGrpcTransport from .transports.grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport from .transports.rest import TermsOfServiceServiceRestTransport @@ -64,14 +80,18 @@ class TermsOfServiceServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[TermsOfServiceServiceTransport]] _transport_registry["grpc"] = TermsOfServiceServiceGrpcTransport _transport_registry["grpc_asyncio"] = TermsOfServiceServiceGrpcAsyncIOTransport _transport_registry["rest"] = TermsOfServiceServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[TermsOfServiceServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[TermsOfServiceServiceTransport]: """Returns an appropriate transport class. Args: @@ -163,8 +183,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: TermsOfServiceServiceClient: 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,95 +200,136 @@ def transport(self) -> TermsOfServiceServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def terms_of_service_path(version: str,) -> str: + def terms_of_service_path( + version: str, + ) -> str: """Returns a fully-qualified terms_of_service string.""" - return "termsOfService/{version}".format(version=version, ) + return "termsOfService/{version}".format( + version=version, + ) @staticmethod - def parse_terms_of_service_path(path: str) -> Dict[str,str]: + def parse_terms_of_service_path(path: str) -> Dict[str, str]: """Parses a terms_of_service path into its component segments.""" m = re.match(r"^termsOfService/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def terms_of_service_agreement_state_path(account: str,identifier: str,) -> str: + def terms_of_service_agreement_state_path( + account: str, + identifier: str, + ) -> str: """Returns a fully-qualified terms_of_service_agreement_state string.""" - return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) + return "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format( + account=account, + identifier=identifier, + ) @staticmethod - def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str,str]: + def parse_terms_of_service_agreement_state_path(path: str) -> Dict[str, str]: """Parses a terms_of_service_agreement_state path into its component segments.""" - m = re.match(r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?P.+?)$", path) + m = re.match( + r"^accounts/(?P.+?)/termsOfServiceAgreementStates/(?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: @@ -301,16 +361,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 @@ -323,7 +389,9 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT @@ -344,13 +412,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 @@ -373,7 +447,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: @@ -389,17 +465,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 = TermsOfServiceServiceClient._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 = TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = ( + TermsOfServiceServiceClient._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: @@ -435,15 +521,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 @@ -476,12 +565,20 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TermsOfServiceServiceTransport, Callable[..., TermsOfServiceServiceTransport]]] = 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, + TermsOfServiceServiceTransport, + Callable[..., TermsOfServiceServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the terms of service service client. Args: @@ -536,14 +633,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 = TermsOfServiceServiceClient._read_environment_variables() - self._client_cert_source = TermsOfServiceServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = TermsOfServiceServiceClient._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, + ) = TermsOfServiceServiceClient._read_environment_variables() + self._client_cert_source = TermsOfServiceServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = TermsOfServiceServiceClient._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 @@ -554,7 +661,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 @@ -563,8 +672,10 @@ def __init__(self, *, if transport_provided: # transport is a TermsOfServiceServiceTransport 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 " @@ -573,20 +684,30 @@ def __init__(self, *, self._transport = cast(TermsOfServiceServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - TermsOfServiceServiceClient._get_api_endpoint( + self._api_endpoint = ( + self._api_endpoint + or TermsOfServiceServiceClient._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[TermsOfServiceServiceTransport], Callable[..., TermsOfServiceServiceTransport]] = ( + transport_init: Union[ + Type[TermsOfServiceServiceTransport], + Callable[..., TermsOfServiceServiceTransport], + ] = ( TermsOfServiceServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., TermsOfServiceServiceTransport], transport) @@ -605,28 +726,37 @@ 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.accounts_v1.TermsOfServiceServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", - "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.accounts.v1.TermsOfServiceService", "credentialsType": None, - } + }, ) - def get_terms_of_service(self, - request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: + def get_terms_of_service( + self, + request: Optional[Union[termsofservice.GetTermsOfServiceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: r"""Retrieves the ``TermsOfService`` associated with the provided version. @@ -694,10 +824,14 @@ def sample_get_terms_of_service(): # - 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. @@ -715,9 +849,7 @@ def sample_get_terms_of_service(): # 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. @@ -734,13 +866,16 @@ def sample_get_terms_of_service(): # Done; return the response. return response - def retrieve_latest_terms_of_service(self, - request: Optional[Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.TermsOfService: + def retrieve_latest_terms_of_service( + self, + request: Optional[ + Union[termsofservice.RetrieveLatestTermsOfServiceRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: r"""Retrieves the latest version of the ``TermsOfService`` for a given ``kind`` and ``region_code``. @@ -807,7 +942,9 @@ def sample_retrieve_latest_terms_of_service(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.retrieve_latest_terms_of_service] + rpc = self._transport._wrapped_methods[ + self._transport.retrieve_latest_terms_of_service + ] # Validate the universe domain. self._validate_universe_domain() @@ -823,14 +960,17 @@ def sample_retrieve_latest_terms_of_service(): # Done; return the response. return response - def accept_terms_of_service(self, - request: Optional[Union[termsofservice.AcceptTermsOfServiceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> termsofservice.AcceptTermsOfServiceResponse: + def accept_terms_of_service( + self, + request: Optional[ + Union[termsofservice.AcceptTermsOfServiceRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.AcceptTermsOfServiceResponse: r"""Accepts a ``TermsOfService``. Executing this method requires admin access. @@ -888,10 +1028,14 @@ def sample_accept_terms_of_service(): # - 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. @@ -909,9 +1053,7 @@ def sample_accept_terms_of_service(): # 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. @@ -942,16 +1084,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__ = ( - "TermsOfServiceServiceClient", -) +__all__ = ("TermsOfServiceServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py similarity index 59% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py index 04c865765be1..79b659e0832c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/__init__.py @@ -19,20 +19,23 @@ from .base import TermsOfServiceServiceTransport from .grpc import TermsOfServiceServiceGrpcTransport from .grpc_asyncio import TermsOfServiceServiceGrpcAsyncIOTransport -from .rest import TermsOfServiceServiceRestTransport -from .rest import TermsOfServiceServiceRestInterceptor - +from .rest import ( + TermsOfServiceServiceRestInterceptor, + TermsOfServiceServiceRestTransport, +) # Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[TermsOfServiceServiceTransport]] -_transport_registry['grpc'] = TermsOfServiceServiceGrpcTransport -_transport_registry['grpc_asyncio'] = TermsOfServiceServiceGrpcAsyncIOTransport -_transport_registry['rest'] = TermsOfServiceServiceRestTransport +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[TermsOfServiceServiceTransport]] +_transport_registry["grpc"] = TermsOfServiceServiceGrpcTransport +_transport_registry["grpc_asyncio"] = TermsOfServiceServiceGrpcAsyncIOTransport +_transport_registry["rest"] = TermsOfServiceServiceRestTransport __all__ = ( - 'TermsOfServiceServiceTransport', - 'TermsOfServiceServiceGrpcTransport', - 'TermsOfServiceServiceGrpcAsyncIOTransport', - 'TermsOfServiceServiceRestTransport', - 'TermsOfServiceServiceRestInterceptor', + "TermsOfServiceServiceTransport", + "TermsOfServiceServiceGrpcTransport", + "TermsOfServiceServiceGrpcAsyncIOTransport", + "TermsOfServiceServiceRestTransport", + "TermsOfServiceServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py index 8b5e81529c75..2aef96e99efe 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/base.py @@ -16,20 +16,21 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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.shopping.merchant_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import termsofservice -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__ @@ -38,24 +39,23 @@ class TermsOfServiceServiceTransport(abc.ABC): """Abstract transport class for TermsOfServiceService.""" - 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: @@ -91,30 +91,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 @@ -139,42 +147,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 get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - Union[ - termsofservice.TermsOfService, - Awaitable[termsofservice.TermsOfService] - ]]: + def get_terms_of_service( + self, + ) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + Union[termsofservice.TermsOfService, Awaitable[termsofservice.TermsOfService]], + ]: raise NotImplementedError() @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - Union[ - termsofservice.TermsOfService, - Awaitable[termsofservice.TermsOfService] - ]]: + def retrieve_latest_terms_of_service( + self, + ) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + Union[termsofservice.TermsOfService, Awaitable[termsofservice.TermsOfService]], + ]: raise NotImplementedError() @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - Union[ - termsofservice.AcceptTermsOfServiceResponse, - Awaitable[termsofservice.AcceptTermsOfServiceResponse] - ]]: + def accept_terms_of_service( + self, + ) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + Union[ + termsofservice.AcceptTermsOfServiceResponse, + Awaitable[termsofservice.AcceptTermsOfServiceResponse], + ], + ]: raise NotImplementedError() @property @@ -182,6 +193,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'TermsOfServiceServiceTransport', -) +__all__ = ("TermsOfServiceServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py index 2b35f2ceea6d..a689262992f6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc.py @@ -16,25 +16,25 @@ 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.json_format import MessageToJson import google.protobuf.message - import grpc # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import termsofservice -from .base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, TermsOfServiceServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -44,7 +44,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -65,7 +67,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -76,7 +78,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -91,7 +97,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": client_call_details.method, "response": grpc_response, @@ -113,23 +119,26 @@ class TermsOfServiceServiceGrpcTransport(TermsOfServiceServiceTransport): 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: @@ -251,19 +260,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. @@ -298,19 +311,20 @@ 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 get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - termsofservice.TermsOfService]: + def get_terms_of_service( + self, + ) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], termsofservice.TermsOfService + ]: r"""Return a callable for the get terms of service method over gRPC. Retrieves the ``TermsOfService`` associated with the provided @@ -326,18 +340,21 @@ def get_terms_of_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_terms_of_service' not in self._stubs: - self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceService/GetTermsOfService', + if "get_terms_of_service" not in self._stubs: + self._stubs["get_terms_of_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceService/GetTermsOfService", request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, response_deserializer=termsofservice.TermsOfService.deserialize, ) - return self._stubs['get_terms_of_service'] + return self._stubs["get_terms_of_service"] @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - termsofservice.TermsOfService]: + def retrieve_latest_terms_of_service( + self, + ) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + termsofservice.TermsOfService, + ]: r"""Return a callable for the retrieve latest terms of service method over gRPC. @@ -354,18 +371,23 @@ def retrieve_latest_terms_of_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'retrieve_latest_terms_of_service' not in self._stubs: - self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceService/RetrieveLatestTermsOfService', + if "retrieve_latest_terms_of_service" not in self._stubs: + self._stubs[ + "retrieve_latest_terms_of_service" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceService/RetrieveLatestTermsOfService", request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, response_deserializer=termsofservice.TermsOfService.deserialize, ) - return self._stubs['retrieve_latest_terms_of_service'] + return self._stubs["retrieve_latest_terms_of_service"] @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - termsofservice.AcceptTermsOfServiceResponse]: + def accept_terms_of_service( + self, + ) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + termsofservice.AcceptTermsOfServiceResponse, + ]: r"""Return a callable for the accept terms of service method over gRPC. Accepts a ``TermsOfService``. Executing this method requires @@ -381,13 +403,13 @@ def accept_terms_of_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'accept_terms_of_service' not in self._stubs: - self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceService/AcceptTermsOfService', + if "accept_terms_of_service" not in self._stubs: + self._stubs["accept_terms_of_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceService/AcceptTermsOfService", request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, response_deserializer=termsofservice.AcceptTermsOfServiceResponse.deserialize, ) - return self._stubs['accept_terms_of_service'] + return self._stubs["accept_terms_of_service"] def close(self): self._logged_channel.close() @@ -397,6 +419,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'TermsOfServiceServiceGrpcTransport', -) +__all__ = ("TermsOfServiceServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py index bae98df8e51e..85fa20ea2982 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/grpc_asyncio.py @@ -15,30 +15,30 @@ # 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.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.shopping.merchant_accounts_v1.types import termsofservice -from .base import TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, TermsOfServiceServiceTransport from .grpc import TermsOfServiceServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,9 +46,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -69,7 +73,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -80,7 +84,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -95,7 +103,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -122,13 +130,15 @@ class TermsOfServiceServiceGrpcAsyncIOTransport(TermsOfServiceServiceTransport): _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. @@ -158,24 +168,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: @@ -299,7 +311,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) @@ -314,9 +328,12 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - Awaitable[termsofservice.TermsOfService]]: + def get_terms_of_service( + self, + ) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], + Awaitable[termsofservice.TermsOfService], + ]: r"""Return a callable for the get terms of service method over gRPC. Retrieves the ``TermsOfService`` associated with the provided @@ -332,18 +349,21 @@ def get_terms_of_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_terms_of_service' not in self._stubs: - self._stubs['get_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceService/GetTermsOfService', + if "get_terms_of_service" not in self._stubs: + self._stubs["get_terms_of_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceService/GetTermsOfService", request_serializer=termsofservice.GetTermsOfServiceRequest.serialize, response_deserializer=termsofservice.TermsOfService.deserialize, ) - return self._stubs['get_terms_of_service'] + return self._stubs["get_terms_of_service"] @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - Awaitable[termsofservice.TermsOfService]]: + def retrieve_latest_terms_of_service( + self, + ) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + Awaitable[termsofservice.TermsOfService], + ]: r"""Return a callable for the retrieve latest terms of service method over gRPC. @@ -360,18 +380,23 @@ def retrieve_latest_terms_of_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'retrieve_latest_terms_of_service' not in self._stubs: - self._stubs['retrieve_latest_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceService/RetrieveLatestTermsOfService', + if "retrieve_latest_terms_of_service" not in self._stubs: + self._stubs[ + "retrieve_latest_terms_of_service" + ] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceService/RetrieveLatestTermsOfService", request_serializer=termsofservice.RetrieveLatestTermsOfServiceRequest.serialize, response_deserializer=termsofservice.TermsOfService.deserialize, ) - return self._stubs['retrieve_latest_terms_of_service'] + return self._stubs["retrieve_latest_terms_of_service"] @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - Awaitable[termsofservice.AcceptTermsOfServiceResponse]]: + def accept_terms_of_service( + self, + ) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + Awaitable[termsofservice.AcceptTermsOfServiceResponse], + ]: r"""Return a callable for the accept terms of service method over gRPC. Accepts a ``TermsOfService``. Executing this method requires @@ -387,16 +412,16 @@ def accept_terms_of_service(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'accept_terms_of_service' not in self._stubs: - self._stubs['accept_terms_of_service'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.TermsOfServiceService/AcceptTermsOfService', + if "accept_terms_of_service" not in self._stubs: + self._stubs["accept_terms_of_service"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.TermsOfServiceService/AcceptTermsOfService", request_serializer=termsofservice.AcceptTermsOfServiceRequest.serialize, response_deserializer=termsofservice.AcceptTermsOfServiceResponse.deserialize, ) - return self._stubs['accept_terms_of_service'] + return self._stubs["accept_terms_of_service"] 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.get_terms_of_service: self._wrap_method( self.get_terms_of_service, @@ -428,6 +453,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'TermsOfServiceServiceGrpcAsyncIOTransport', -) +__all__ = ("TermsOfServiceServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py index 05660541d6ae..83d24c580178 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest.py @@ -13,31 +13,25 @@ # 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 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.shopping.merchant_accounts_v1.types import termsofservice - -from .rest_base import _BaseTermsOfServiceServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseTermsOfServiceServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -46,6 +40,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -106,7 +101,15 @@ def post_retrieve_latest_terms_of_service(self, response): """ - def pre_accept_terms_of_service(self, request: termsofservice.AcceptTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.AcceptTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_accept_terms_of_service( + self, + request: termsofservice.AcceptTermsOfServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofservice.AcceptTermsOfServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for accept_terms_of_service Override in a subclass to manipulate the request or metadata @@ -114,7 +117,9 @@ def pre_accept_terms_of_service(self, request: termsofservice.AcceptTermsOfServi """ return request, metadata - def post_accept_terms_of_service(self, response: termsofservice.AcceptTermsOfServiceResponse) -> termsofservice.AcceptTermsOfServiceResponse: + def post_accept_terms_of_service( + self, response: termsofservice.AcceptTermsOfServiceResponse + ) -> termsofservice.AcceptTermsOfServiceResponse: """Post-rpc interceptor for accept_terms_of_service DEPRECATED. Please use the `post_accept_terms_of_service_with_metadata` @@ -127,7 +132,14 @@ def post_accept_terms_of_service(self, response: termsofservice.AcceptTermsOfSer """ return response - def post_accept_terms_of_service_with_metadata(self, response: termsofservice.AcceptTermsOfServiceResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.AcceptTermsOfServiceResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_accept_terms_of_service_with_metadata( + self, + response: termsofservice.AcceptTermsOfServiceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofservice.AcceptTermsOfServiceResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Post-rpc interceptor for accept_terms_of_service Override in a subclass to read or manipulate the response or metadata after it @@ -142,7 +154,13 @@ def post_accept_terms_of_service_with_metadata(self, response: termsofservice.Ac """ return response, metadata - def pre_get_terms_of_service(self, request: termsofservice.GetTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_terms_of_service( + self, + request: termsofservice.GetTermsOfServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofservice.GetTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_terms_of_service Override in a subclass to manipulate the request or metadata @@ -150,7 +168,9 @@ def pre_get_terms_of_service(self, request: termsofservice.GetTermsOfServiceRequ """ return request, metadata - def post_get_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: + def post_get_terms_of_service( + self, response: termsofservice.TermsOfService + ) -> termsofservice.TermsOfService: """Post-rpc interceptor for get_terms_of_service DEPRECATED. Please use the `post_get_terms_of_service_with_metadata` @@ -163,7 +183,11 @@ def post_get_terms_of_service(self, response: termsofservice.TermsOfService) -> """ return response - def post_get_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_terms_of_service_with_metadata( + self, + response: termsofservice.TermsOfService, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_terms_of_service Override in a subclass to read or manipulate the response or metadata after it @@ -178,7 +202,14 @@ def post_get_terms_of_service_with_metadata(self, response: termsofservice.Terms """ return response, metadata - def pre_retrieve_latest_terms_of_service(self, request: termsofservice.RetrieveLatestTermsOfServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.RetrieveLatestTermsOfServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_retrieve_latest_terms_of_service( + self, + request: termsofservice.RetrieveLatestTermsOfServiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + termsofservice.RetrieveLatestTermsOfServiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for retrieve_latest_terms_of_service Override in a subclass to manipulate the request or metadata @@ -186,7 +217,9 @@ def pre_retrieve_latest_terms_of_service(self, request: termsofservice.RetrieveL """ return request, metadata - def post_retrieve_latest_terms_of_service(self, response: termsofservice.TermsOfService) -> termsofservice.TermsOfService: + def post_retrieve_latest_terms_of_service( + self, response: termsofservice.TermsOfService + ) -> termsofservice.TermsOfService: """Post-rpc interceptor for retrieve_latest_terms_of_service DEPRECATED. Please use the `post_retrieve_latest_terms_of_service_with_metadata` @@ -199,7 +232,11 @@ def post_retrieve_latest_terms_of_service(self, response: termsofservice.TermsOf """ return response - def post_retrieve_latest_terms_of_service_with_metadata(self, response: termsofservice.TermsOfService, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_retrieve_latest_terms_of_service_with_metadata( + self, + response: termsofservice.TermsOfService, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[termsofservice.TermsOfService, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for retrieve_latest_terms_of_service Override in a subclass to read or manipulate the response or metadata after it @@ -234,20 +271,21 @@ class TermsOfServiceServiceRestTransport(_BaseTermsOfServiceServiceRestTransport 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[TermsOfServiceServiceRestInterceptor] = 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[TermsOfServiceServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -290,16 +328,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 TermsOfServiceServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _AcceptTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService, TermsOfServiceServiceRestStub): + class _AcceptTermsOfService( + _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService, + TermsOfServiceServiceRestStub, + ): def __hash__(self): return hash("TermsOfServiceServiceRestTransport.AcceptTermsOfService") @@ -311,26 +353,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: termsofservice.AcceptTermsOfServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofservice.AcceptTermsOfServiceResponse: + def __call__( + self, + request: termsofservice.AcceptTermsOfServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.AcceptTermsOfServiceResponse: r"""Call the accept terms of service method over HTTP. Args: @@ -351,30 +395,42 @@ def __call__(self, """ - http_options = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_http_options() + http_options = ( + _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_http_options() + ) - request, metadata = self._interceptor.pre_accept_terms_of_service(request, metadata) - transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_accept_terms_of_service( + request, metadata + ) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceServiceClient.AcceptTermsOfService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": "AcceptTermsOfService", "httpRequest": http_request, @@ -383,7 +439,16 @@ def __call__(self, ) # Send the request - response = TermsOfServiceServiceRestTransport._AcceptTermsOfService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + TermsOfServiceServiceRestTransport._AcceptTermsOfService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -398,20 +463,26 @@ def __call__(self, resp = self._interceptor.post_accept_terms_of_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_accept_terms_of_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_accept_terms_of_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: - response_payload = termsofservice.AcceptTermsOfServiceResponse.to_json(response) + response_payload = ( + termsofservice.AcceptTermsOfServiceResponse.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.accounts_v1.TermsOfServiceServiceClient.accept_terms_of_service", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": "AcceptTermsOfService", "metadata": http_response["headers"], @@ -420,7 +491,10 @@ def __call__(self, ) return resp - class _GetTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService, TermsOfServiceServiceRestStub): + class _GetTermsOfService( + _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService, + TermsOfServiceServiceRestStub, + ): def __hash__(self): return hash("TermsOfServiceServiceRestTransport.GetTermsOfService") @@ -432,26 +506,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: termsofservice.GetTermsOfServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofservice.TermsOfService: + def __call__( + self, + request: termsofservice.GetTermsOfServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: r"""Call the get terms of service method over HTTP. Args: @@ -483,30 +559,42 @@ def __call__(self, """ - http_options = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_http_options() + http_options = ( + _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_http_options() + ) - request, metadata = self._interceptor.pre_get_terms_of_service(request, metadata) - transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_get_terms_of_service( + request, metadata + ) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceServiceClient.GetTermsOfService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": "GetTermsOfService", "httpRequest": http_request, @@ -515,7 +603,16 @@ def __call__(self, ) # Send the request - response = TermsOfServiceServiceRestTransport._GetTermsOfService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = ( + TermsOfServiceServiceRestTransport._GetTermsOfService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -530,20 +627,24 @@ def __call__(self, resp = self._interceptor.post_get_terms_of_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_terms_of_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_terms_of_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = termsofservice.TermsOfService.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.accounts_v1.TermsOfServiceServiceClient.get_terms_of_service", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": "GetTermsOfService", "metadata": http_response["headers"], @@ -552,9 +653,14 @@ def __call__(self, ) return resp - class _RetrieveLatestTermsOfService(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService, TermsOfServiceServiceRestStub): + class _RetrieveLatestTermsOfService( + _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService, + TermsOfServiceServiceRestStub, + ): def __hash__(self): - return hash("TermsOfServiceServiceRestTransport.RetrieveLatestTermsOfService") + return hash( + "TermsOfServiceServiceRestTransport.RetrieveLatestTermsOfService" + ) @staticmethod def _get_response( @@ -564,83 +670,97 @@ 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: termsofservice.RetrieveLatestTermsOfServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> termsofservice.TermsOfService: + def __call__( + self, + request: termsofservice.RetrieveLatestTermsOfServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> termsofservice.TermsOfService: r"""Call the retrieve latest terms of - service method over HTTP. - - Args: - request (~.termsofservice.RetrieveLatestTermsOfServiceRequest): - The request object. Request message for the ``RetrieveLatestTermsOfService`` - 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: - ~.termsofservice.TermsOfService: - The ``TermsOfService`` message represents a specific - version of the terms of service that merchants must - accept to access certain features or services. For more - information, see `Terms of - Service `__. - - This message is important for the onboarding process, - ensuring that merchants agree to the necessary legal - agreements for using the service. Merchants can retrieve - the latest terms of service for a given ``kind`` and - ``region`` through ``RetrieveLatestTermsOfService``, and - accept them as required through - ``AcceptTermsOfService``. + service method over HTTP. + + Args: + request (~.termsofservice.RetrieveLatestTermsOfServiceRequest): + The request object. Request message for the ``RetrieveLatestTermsOfService`` + 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: + ~.termsofservice.TermsOfService: + The ``TermsOfService`` message represents a specific + version of the terms of service that merchants must + accept to access certain features or services. For more + information, see `Terms of + Service `__. + + This message is important for the onboarding process, + ensuring that merchants agree to the necessary legal + agreements for using the service. Merchants can retrieve + the latest terms of service for a given ``kind`` and + ``region`` through ``RetrieveLatestTermsOfService``, and + accept them as required through + ``AcceptTermsOfService``. """ - http_options = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_http_options() + http_options = ( + _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_http_options() + ) - request, metadata = self._interceptor.pre_retrieve_latest_terms_of_service(request, metadata) - transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_transcoded_request(http_options, request) + request, metadata = self._interceptor.pre_retrieve_latest_terms_of_service( + request, metadata + ) + transcoded_request = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_transcoded_request( + http_options, request + ) # Jsonify the query params - query_params = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED 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 = _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED 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.accounts_v1.TermsOfServiceServiceClient.RetrieveLatestTermsOfService", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": "RetrieveLatestTermsOfService", "httpRequest": http_request, @@ -649,7 +769,14 @@ def __call__(self, ) # Send the request - response = TermsOfServiceServiceRestTransport._RetrieveLatestTermsOfService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = TermsOfServiceServiceRestTransport._RetrieveLatestTermsOfService._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -664,20 +791,27 @@ def __call__(self, resp = self._interceptor.post_retrieve_latest_terms_of_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_retrieve_latest_terms_of_service_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + ( + resp, + _, + ) = self._interceptor.post_retrieve_latest_terms_of_service_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = termsofservice.TermsOfService.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.accounts_v1.TermsOfServiceServiceClient.retrieve_latest_terms_of_service", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.TermsOfServiceService", "rpcName": "RetrieveLatestTermsOfService", "metadata": http_response["headers"], @@ -687,28 +821,36 @@ def __call__(self, return resp @property - def accept_terms_of_service(self) -> Callable[ - [termsofservice.AcceptTermsOfServiceRequest], - termsofservice.AcceptTermsOfServiceResponse]: + def accept_terms_of_service( + self, + ) -> Callable[ + [termsofservice.AcceptTermsOfServiceRequest], + termsofservice.AcceptTermsOfServiceResponse, + ]: # 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._AcceptTermsOfService(self._session, self._host, self._interceptor) # type: ignore + return self._AcceptTermsOfService(self._session, self._host, self._interceptor) # type: ignore @property - def get_terms_of_service(self) -> Callable[ - [termsofservice.GetTermsOfServiceRequest], - termsofservice.TermsOfService]: + def get_terms_of_service( + self, + ) -> Callable[ + [termsofservice.GetTermsOfServiceRequest], termsofservice.TermsOfService + ]: # 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._GetTermsOfService(self._session, self._host, self._interceptor) # type: ignore + return self._GetTermsOfService(self._session, self._host, self._interceptor) # type: ignore @property - def retrieve_latest_terms_of_service(self) -> Callable[ - [termsofservice.RetrieveLatestTermsOfServiceRequest], - termsofservice.TermsOfService]: + def retrieve_latest_terms_of_service( + self, + ) -> Callable[ + [termsofservice.RetrieveLatestTermsOfServiceRequest], + termsofservice.TermsOfService, + ]: # 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._RetrieveLatestTermsOfService(self._session, self._host, self._interceptor) # type: ignore + return self._RetrieveLatestTermsOfService(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -718,6 +860,4 @@ def close(self): self._session.close() -__all__=( - 'TermsOfServiceServiceRestTransport', -) +__all__ = ("TermsOfServiceServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py similarity index 61% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py index 8ae3b3ecdbdc..67244a11ba68 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/terms_of_service_service/transports/rest_base.py @@ -14,18 +14,16 @@ # 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 TermsOfServiceServiceTransport, DEFAULT_CLIENT_INFO - import re from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format from google.shopping.merchant_accounts_v1.types import termsofservice +from .base import DEFAULT_CLIENT_INFO, TermsOfServiceServiceTransport + class _BaseTermsOfServiceServiceRestTransport(TermsOfServiceServiceTransport): """Base REST backend transport for TermsOfServiceService. @@ -40,14 +38,16 @@ class _BaseTermsOfServiceServiceRestTransport(TermsOfServiceServiceTransport): 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]): @@ -71,7 +71,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -82,26 +84,33 @@ 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 _BaseAcceptTermsOfService: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "account" : "", "regionCode" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "account": "", + "regionCode": "", + } @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': '/accounts/v1/{name=termsOfService/*}:accept', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{name=termsOfService/*}:accept", + }, ] return http_options @@ -113,11 +122,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(_BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._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( + _BaseTermsOfServiceServiceRestTransport._BaseAcceptTermsOfService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -126,19 +141,23 @@ class _BaseGetTermsOfService: 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': '/accounts/v1/{name=termsOfService/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=termsOfService/*}", + }, ] return http_options @@ -150,11 +169,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(_BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._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( + _BaseTermsOfServiceServiceRestTransport._BaseGetTermsOfService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -163,19 +188,26 @@ class _BaseRetrieveLatestTermsOfService: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "regionCode" : "", "kind" : {}, } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "regionCode": "", + "kind": {}, + } @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': '/accounts/v1/termsOfService:retrieveLatest', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/termsOfService:retrieveLatest", + }, ] return http_options @@ -187,16 +219,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(_BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._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( + _BaseTermsOfServiceServiceRestTransport._BaseRetrieveLatestTermsOfService._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseTermsOfServiceServiceRestTransport', -) +__all__ = ("_BaseTermsOfServiceServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/__init__.py similarity index 92% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/__init__.py index d60a27bcbaf8..08bdfeb823ee 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import UserServiceClient from .async_client import UserServiceAsyncClient +from .client import UserServiceClient __all__ = ( - 'UserServiceClient', - 'UserServiceAsyncClient', + "UserServiceClient", + "UserServiceAsyncClient", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/async_client.py similarity index 83% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/async_client.py index ced4321c9b69..4a719962639c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/async_client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/async_client.py @@ -13,21 +13,31 @@ # 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_accounts_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_accounts_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] @@ -35,22 +45,26 @@ OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.user_service import pagers from google.shopping.merchant_accounts_v1.types import accessright from google.shopping.merchant_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user -from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport + from .client import UserServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, UserServiceTransport +from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport 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 UserServiceAsyncClient: """Service to support user API.""" @@ -67,16 +81,26 @@ class UserServiceAsyncClient: parse_account_path = staticmethod(UserServiceClient.parse_account_path) user_path = staticmethod(UserServiceClient.user_path) parse_user_path = staticmethod(UserServiceClient.parse_user_path) - common_billing_account_path = staticmethod(UserServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + UserServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + UserServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(UserServiceClient.common_folder_path) parse_common_folder_path = staticmethod(UserServiceClient.parse_common_folder_path) common_organization_path = staticmethod(UserServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserServiceClient.parse_common_organization_path) + parse_common_organization_path = staticmethod( + UserServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(UserServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + UserServiceClient.parse_common_project_path + ) common_location_path = staticmethod(UserServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + UserServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -112,7 +136,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: @@ -175,12 +201,16 @@ def universe_domain(self) -> str: get_transport_class = UserServiceClient.get_transport_class - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, UserServiceTransport, Callable[..., UserServiceTransport]]] = "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, UserServiceTransport, Callable[..., UserServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the user service async client. Args: @@ -235,31 +265,39 @@ 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.accounts_v1.UserServiceAsyncClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", - "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.accounts.v1.UserService", "credentialsType": None, - } + }, ) - async def get_user(self, - request: Optional[Union[user.GetUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> user.User: + async def get_user( + self, + request: Optional[Union[user.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: r"""Retrieves a Merchant Center account user. .. code-block:: python @@ -324,10 +362,14 @@ async def sample_get_user(): # - 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. @@ -346,9 +388,7 @@ async def sample_get_user(): # 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. @@ -365,16 +405,17 @@ async def sample_get_user(): # Done; return the response. return response - async def create_user(self, - request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, - *, - parent: Optional[str] = None, - user: Optional[gsma_user.User] = None, - user_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: + async def create_user( + self, + request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[gsma_user.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: r"""Creates a Merchant Center account user. Executing this method requires admin access. @@ -449,10 +490,14 @@ async def sample_create_user(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, user, user_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -470,14 +515,14 @@ async def sample_create_user(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_user] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_user + ] # 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. @@ -494,14 +539,15 @@ async def sample_create_user(): # Done; return the response. return response - async def delete_user(self, - request: Optional[Union[user.DeleteUserRequest, dict]] = None, - *, - name: 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_user( + self, + request: Optional[Union[user.DeleteUserRequest, dict]] = None, + *, + name: 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 a Merchant Center account user. Executing this method requires admin access. The user to be deleted can't be the last admin user of that account. @@ -557,10 +603,14 @@ async def sample_delete_user(): # - 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. @@ -574,14 +624,14 @@ async def sample_delete_user(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_user] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_user + ] # 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. @@ -595,15 +645,16 @@ async def sample_delete_user(): metadata=metadata, ) - async def update_user(self, - request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, - *, - user: Optional[gsma_user.User] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: + async def update_user( + self, + request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, + *, + user: Optional[gsma_user.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: r"""Updates a Merchant Center account user. Executing this method requires admin access. @@ -681,10 +732,14 @@ async def sample_update_user(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [user, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -700,14 +755,16 @@ async def sample_update_user(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_user] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_user + ] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user.name", request.user.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("user.name", request.user.name),) + ), ) # Validate the universe domain. @@ -724,14 +781,15 @@ async def sample_update_user(): # Done; return the response. return response - async def list_users(self, - request: Optional[Union[user.ListUsersRequest, 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.ListUsersAsyncPager: + async def list_users( + self, + request: Optional[Union[user.ListUsersRequest, 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.ListUsersAsyncPager: r"""Lists all users of a Merchant Center account. .. code-block:: python @@ -791,10 +849,14 @@ async def sample_list_users(): # - 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. @@ -808,14 +870,14 @@ async def sample_list_users(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_users] + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_users + ] # 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. @@ -849,12 +911,13 @@ async def __aenter__(self) -> "UserServiceAsyncClient": 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__ = ( - "UserServiceAsyncClient", -) +__all__ = ("UserServiceAsyncClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/client.py similarity index 80% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/client.py index d861ca155b22..92b90323ef09 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/client.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_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_accounts_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_accounts_v1 import gapic_version as package_version + try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] except AttributeError: # pragma: NO COVER @@ -42,6 +54,7 @@ try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -49,11 +62,13 @@ _LOGGER = std_logging.getLogger(__name__) from google.protobuf import field_mask_pb2 # type: ignore + from google.shopping.merchant_accounts_v1.services.user_service import pagers from google.shopping.merchant_accounts_v1.types import accessright from google.shopping.merchant_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user -from .transports.base import UserServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, UserServiceTransport from .transports.grpc import UserServiceGrpcTransport from .transports.grpc_asyncio import UserServiceGrpcAsyncIOTransport from .transports.rest import UserServiceRestTransport @@ -66,14 +81,16 @@ class UserServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[UserServiceTransport]] _transport_registry["grpc"] = UserServiceGrpcTransport _transport_registry["grpc_asyncio"] = UserServiceGrpcAsyncIOTransport _transport_registry["rest"] = UserServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[UserServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[UserServiceTransport]: """Returns an appropriate transport class. Args: @@ -165,8 +182,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: UserServiceClient: 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,84 +199,118 @@ def transport(self) -> UserServiceTransport: return self._transport @staticmethod - def account_path(account: str,) -> str: + def account_path( + account: str, + ) -> str: """Returns a fully-qualified account string.""" - return "accounts/{account}".format(account=account, ) + return "accounts/{account}".format( + account=account, + ) @staticmethod - def parse_account_path(path: str) -> Dict[str,str]: + def parse_account_path(path: str) -> Dict[str, str]: """Parses a account path into its component segments.""" m = re.match(r"^accounts/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod - def user_path(account: str,email: str,) -> str: + def user_path( + account: str, + email: str, + ) -> str: """Returns a fully-qualified user string.""" - return "accounts/{account}/users/{email}".format(account=account, email=email, ) + return "accounts/{account}/users/{email}".format( + account=account, + email=email, + ) @staticmethod - def parse_user_path(path: str) -> Dict[str,str]: + def parse_user_path(path: str) -> Dict[str, str]: """Parses a user path into its component segments.""" m = re.match(r"^accounts/(?P.+?)/users/(?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: @@ -292,16 +342,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 @@ -314,7 +370,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 @@ -335,13 +393,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 @@ -364,7 +428,9 @@ def _get_client_cert_source(provided_cert_source, use_cert_flag): return client_cert_source @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): """Return the API endpoint used by the client. Args: @@ -380,17 +446,25 @@ def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtl """ if api_override is not None: api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): _default_universe = UserServiceClient._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 = UserServiceClient.DEFAULT_MTLS_ENDPOINT else: - api_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + api_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) return api_endpoint @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: """Return the universe domain used by the client. Args: @@ -426,15 +500,18 @@ def _validate_universe_domain(self): return True def _add_cred_info_for_auth_errors( - self, - error: core_exceptions.GoogleAPICallError + self, error: core_exceptions.GoogleAPICallError ) -> None: """Adds credential info string to error details for 401/403/404 errors. Args: error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. """ - if error.code not in [HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN, HTTPStatus.NOT_FOUND]: + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: return cred = self._transport._credentials @@ -467,12 +544,16 @@ def universe_domain(self) -> str: """ return self._universe_domain - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, UserServiceTransport, Callable[..., UserServiceTransport]]] = 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, UserServiceTransport, Callable[..., UserServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the user service client. Args: @@ -527,14 +608,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 = UserServiceClient._read_environment_variables() - self._client_cert_source = UserServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = UserServiceClient._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, + ) = UserServiceClient._read_environment_variables() + self._client_cert_source = UserServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = UserServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` # Initialize the universe domain validation. self._is_universe_domain_valid = False @@ -545,7 +636,9 @@ def __init__(self, *, api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport @@ -554,8 +647,10 @@ def __init__(self, *, if transport_provided: # transport is a UserServiceTransport 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 " @@ -564,20 +659,26 @@ def __init__(self, *, self._transport = cast(UserServiceTransport, transport) self._api_endpoint = self._transport.host - self._api_endpoint = (self._api_endpoint or - UserServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) + self._api_endpoint = self._api_endpoint or UserServiceClient._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) + 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[UserServiceTransport], Callable[..., UserServiceTransport]] = ( + transport_init: Union[ + Type[UserServiceTransport], Callable[..., UserServiceTransport] + ] = ( UserServiceClient.get_transport_class(transport) if isinstance(transport, str) or transport is None else cast(Callable[..., UserServiceTransport], transport) @@ -596,28 +697,37 @@ 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.accounts_v1.UserServiceClient`.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", - "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.accounts.v1.UserService", "credentialsType": None, - } + }, ) - def get_user(self, - request: Optional[Union[user.GetUserRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> user.User: + def get_user( + self, + request: Optional[Union[user.GetUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: r"""Retrieves a Merchant Center account user. .. code-block:: python @@ -682,10 +792,14 @@ def sample_get_user(): # - 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. @@ -703,9 +817,7 @@ def sample_get_user(): # 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. @@ -722,16 +834,17 @@ def sample_get_user(): # Done; return the response. return response - def create_user(self, - request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, - *, - parent: Optional[str] = None, - user: Optional[gsma_user.User] = None, - user_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: + def create_user( + self, + request: Optional[Union[gsma_user.CreateUserRequest, dict]] = None, + *, + parent: Optional[str] = None, + user: Optional[gsma_user.User] = None, + user_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: r"""Creates a Merchant Center account user. Executing this method requires admin access. @@ -806,10 +919,14 @@ def sample_create_user(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [parent, user, user_id] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -831,9 +948,7 @@ def sample_create_user(): # 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. @@ -850,14 +965,15 @@ def sample_create_user(): # Done; return the response. return response - def delete_user(self, - request: Optional[Union[user.DeleteUserRequest, dict]] = None, - *, - name: 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_user( + self, + request: Optional[Union[user.DeleteUserRequest, dict]] = None, + *, + name: 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 a Merchant Center account user. Executing this method requires admin access. The user to be deleted can't be the last admin user of that account. @@ -913,10 +1029,14 @@ def sample_delete_user(): # - 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. @@ -934,9 +1054,7 @@ def sample_delete_user(): # 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. @@ -950,15 +1068,16 @@ def sample_delete_user(): metadata=metadata, ) - def update_user(self, - request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, - *, - user: Optional[gsma_user.User] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> gsma_user.User: + def update_user( + self, + request: Optional[Union[gsma_user.UpdateUserRequest, dict]] = None, + *, + user: Optional[gsma_user.User] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: r"""Updates a Merchant Center account user. Executing this method requires admin access. @@ -1036,10 +1155,14 @@ def sample_update_user(): # - Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. flattened_params = [user, update_mask] - has_flattened_params = len([param for param in flattened_params if param is not None]) > 0 + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # - Use the request object if provided (there's no risk of modifying the input as # there are no flattened fields), or create one. @@ -1059,9 +1182,9 @@ def sample_update_user(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("user.name", request.user.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("user.name", request.user.name),) + ), ) # Validate the universe domain. @@ -1078,14 +1201,15 @@ def sample_update_user(): # Done; return the response. return response - def list_users(self, - request: Optional[Union[user.ListUsersRequest, 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.ListUsersPager: + def list_users( + self, + request: Optional[Union[user.ListUsersRequest, 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.ListUsersPager: r"""Lists all users of a Merchant Center account. .. code-block:: python @@ -1145,10 +1269,14 @@ def sample_list_users(): # - 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. @@ -1166,9 +1294,7 @@ def sample_list_users(): # 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. @@ -1210,16 +1336,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__ = ( - "UserServiceClient", -) +__all__ = ("UserServiceClient",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/pagers.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/pagers.py similarity index 79% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/pagers.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/pagers.py index 826a8336b703..5149655a095c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/pagers.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_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 ListUsersPager: 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[..., user.ListUsersResponse], - request: user.ListUsersRequest, - response: user.ListUsersResponse, - *, - 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[..., user.ListUsersResponse], + request: user.ListUsersRequest, + response: user.ListUsersResponse, + *, + 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[user.ListUsersResponse]: 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[user.User]: @@ -92,7 +114,7 @@ def __iter__(self) -> Iterator[user.User]: yield from page.users 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 ListUsersAsyncPager: @@ -112,14 +134,17 @@ class ListUsersAsyncPager: 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[user.ListUsersResponse]], - request: user.ListUsersRequest, - response: user.ListUsersResponse, - *, - 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[user.ListUsersResponse]], + request: user.ListUsersRequest, + response: user.ListUsersResponse, + *, + 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[user.ListUsersResponse]: 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[user.User]: 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-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/README.rst diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py index b8429533bdc0..8599548ec5b1 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import UserServiceTransport from .grpc import UserServiceGrpcTransport from .grpc_asyncio import UserServiceGrpcAsyncIOTransport -from .rest import UserServiceRestTransport -from .rest import UserServiceRestInterceptor - +from .rest import UserServiceRestInterceptor, UserServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[UserServiceTransport]] -_transport_registry['grpc'] = UserServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserServiceGrpcAsyncIOTransport -_transport_registry['rest'] = UserServiceRestTransport +_transport_registry["grpc"] = UserServiceGrpcTransport +_transport_registry["grpc_asyncio"] = UserServiceGrpcAsyncIOTransport +_transport_registry["rest"] = UserServiceRestTransport __all__ = ( - 'UserServiceTransport', - 'UserServiceGrpcTransport', - 'UserServiceGrpcAsyncIOTransport', - 'UserServiceRestTransport', - 'UserServiceRestInterceptor', + "UserServiceTransport", + "UserServiceGrpcTransport", + "UserServiceGrpcAsyncIOTransport", + "UserServiceRestTransport", + "UserServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py index 2eb9b38addc7..051d26627081 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/base.py @@ -16,22 +16,23 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.shopping.merchant_accounts_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_accounts_v1 import gapic_version as package_version from google.shopping.merchant_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ @@ -40,24 +41,23 @@ class UserServiceTransport(abc.ABC): """Abstract transport class for UserService.""" - 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: @@ -93,30 +93,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 @@ -151,60 +159,54 @@ 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 get_user(self) -> Callable[ - [user.GetUserRequest], - Union[ - user.User, - Awaitable[user.User] - ]]: + def get_user( + self, + ) -> Callable[[user.GetUserRequest], Union[user.User, Awaitable[user.User]]]: raise NotImplementedError() @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - Union[ - gsma_user.User, - Awaitable[gsma_user.User] - ]]: + def create_user( + self, + ) -> Callable[ + [gsma_user.CreateUserRequest], Union[gsma_user.User, Awaitable[gsma_user.User]] + ]: raise NotImplementedError() @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: + def delete_user( + self, + ) -> Callable[ + [user.DeleteUserRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: raise NotImplementedError() @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - Union[ - gsma_user.User, - Awaitable[gsma_user.User] - ]]: + def update_user( + self, + ) -> Callable[ + [gsma_user.UpdateUserRequest], Union[gsma_user.User, Awaitable[gsma_user.User]] + ]: raise NotImplementedError() @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - Union[ - user.ListUsersResponse, - Awaitable[user.ListUsersResponse] - ]]: + def list_users( + self, + ) -> Callable[ + [user.ListUsersRequest], + Union[user.ListUsersResponse, Awaitable[user.ListUsersResponse]], + ]: raise NotImplementedError() @property @@ -212,6 +214,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'UserServiceTransport', -) +__all__ = ("UserServiceTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py index 535cdabf9470..291283d720ca 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc.py @@ -16,27 +16,27 @@ 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_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user -from .base import UserServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, UserServiceTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -46,7 +46,9 @@ class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -67,7 +69,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -78,7 +80,11 @@ def intercept_unary_unary(self, continuation, client_call_details, request): if logging_enabled: # pragma: NO COVER response_metadata = response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = response.result() if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -93,7 +99,7 @@ def intercept_unary_unary(self, continuation, client_call_details, request): } _LOGGER.debug( f"Received response for {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": client_call_details.method, "response": grpc_response, @@ -115,23 +121,26 @@ class UserServiceGrpcTransport(UserServiceTransport): 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,16 @@ 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 get_user(self) -> Callable[ - [user.GetUserRequest], - user.User]: + def get_user(self) -> Callable[[user.GetUserRequest], user.User]: r"""Return a callable for the get user method over gRPC. Retrieves a Merchant Center account user. @@ -327,18 +337,16 @@ def get_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_user' not in self._stubs: - self._stubs['get_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/GetUser', + if "get_user" not in self._stubs: + self._stubs["get_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/GetUser", request_serializer=user.GetUserRequest.serialize, response_deserializer=user.User.deserialize, ) - return self._stubs['get_user'] + return self._stubs["get_user"] @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - gsma_user.User]: + def create_user(self) -> Callable[[gsma_user.CreateUserRequest], gsma_user.User]: r"""Return a callable for the create user method over gRPC. Creates a Merchant Center account user. Executing @@ -354,18 +362,16 @@ def create_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_user' not in self._stubs: - self._stubs['create_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/CreateUser', + if "create_user" not in self._stubs: + self._stubs["create_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/CreateUser", request_serializer=gsma_user.CreateUserRequest.serialize, response_deserializer=gsma_user.User.deserialize, ) - return self._stubs['create_user'] + return self._stubs["create_user"] @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - empty_pb2.Empty]: + def delete_user(self) -> Callable[[user.DeleteUserRequest], empty_pb2.Empty]: r"""Return a callable for the delete user method over gRPC. Deletes a Merchant Center account user. Executing @@ -384,18 +390,16 @@ def delete_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_user' not in self._stubs: - self._stubs['delete_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/DeleteUser', + if "delete_user" not in self._stubs: + self._stubs["delete_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/DeleteUser", request_serializer=user.DeleteUserRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_user'] + return self._stubs["delete_user"] @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - gsma_user.User]: + def update_user(self) -> Callable[[gsma_user.UpdateUserRequest], gsma_user.User]: r"""Return a callable for the update user method over gRPC. Updates a Merchant Center account user. Executing @@ -411,18 +415,16 @@ def update_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_user' not in self._stubs: - self._stubs['update_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/UpdateUser', + if "update_user" not in self._stubs: + self._stubs["update_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/UpdateUser", request_serializer=gsma_user.UpdateUserRequest.serialize, response_deserializer=gsma_user.User.deserialize, ) - return self._stubs['update_user'] + return self._stubs["update_user"] @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - user.ListUsersResponse]: + def list_users(self) -> Callable[[user.ListUsersRequest], user.ListUsersResponse]: r"""Return a callable for the list users method over gRPC. Lists all users of a Merchant Center account. @@ -437,13 +439,13 @@ def list_users(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_users' not in self._stubs: - self._stubs['list_users'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/ListUsers', + if "list_users" not in self._stubs: + self._stubs["list_users"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/ListUsers", request_serializer=user.ListUsersRequest.serialize, response_deserializer=user.ListUsersResponse.deserialize, ) - return self._stubs['list_users'] + return self._stubs["list_users"] def close(self): self._logged_channel.close() @@ -453,6 +455,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'UserServiceGrpcTransport', -) +__all__ = ("UserServiceGrpcTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py similarity index 82% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py index 21e6e8b4ecda..aa3ba89c182b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/grpc_asyncio.py @@ -15,32 +15,32 @@ # 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_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user -from .base import UserServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, UserServiceTransport from .grpc import UserServiceGrpcTransport try: from google.api_core import client_logging # type: ignore + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER except ImportError: # pragma: NO COVER CLIENT_LOGGING_SUPPORTED = False @@ -48,9 +48,13 @@ _LOGGER = std_logging.getLogger(__name__) -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) if logging_enabled: # pragma: NO COVER request_metadata = client_call_details.metadata if isinstance(request, proto.Message): @@ -71,7 +75,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Sending request for {client_call_details.method}", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": str(client_call_details.method), "request": grpc_request, @@ -82,7 +86,11 @@ async def intercept_unary_unary(self, continuation, client_call_details, request if logging_enabled: # pragma: NO COVER response_metadata = await response.trailing_metadata() # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) result = await response if isinstance(result, proto.Message): response_payload = type(result).to_json(result) @@ -97,7 +105,7 @@ async def intercept_unary_unary(self, continuation, client_call_details, request } _LOGGER.debug( f"Received response to rpc {client_call_details.method}.", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": str(client_call_details.method), "response": grpc_response, @@ -124,13 +132,15 @@ class UserServiceGrpcAsyncIOTransport(UserServiceTransport): _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,7 @@ def grpc_channel(self) -> aio.Channel: return self._grpc_channel @property - def get_user(self) -> Callable[ - [user.GetUserRequest], - Awaitable[user.User]]: + def get_user(self) -> Callable[[user.GetUserRequest], Awaitable[user.User]]: r"""Return a callable for the get user method over gRPC. Retrieves a Merchant Center account user. @@ -333,18 +345,18 @@ def get_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_user' not in self._stubs: - self._stubs['get_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/GetUser', + if "get_user" not in self._stubs: + self._stubs["get_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/GetUser", request_serializer=user.GetUserRequest.serialize, response_deserializer=user.User.deserialize, ) - return self._stubs['get_user'] + return self._stubs["get_user"] @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - Awaitable[gsma_user.User]]: + def create_user( + self, + ) -> Callable[[gsma_user.CreateUserRequest], Awaitable[gsma_user.User]]: r"""Return a callable for the create user method over gRPC. Creates a Merchant Center account user. Executing @@ -360,18 +372,18 @@ def create_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_user' not in self._stubs: - self._stubs['create_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/CreateUser', + if "create_user" not in self._stubs: + self._stubs["create_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/CreateUser", request_serializer=gsma_user.CreateUserRequest.serialize, response_deserializer=gsma_user.User.deserialize, ) - return self._stubs['create_user'] + return self._stubs["create_user"] @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - Awaitable[empty_pb2.Empty]]: + def delete_user( + self, + ) -> Callable[[user.DeleteUserRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete user method over gRPC. Deletes a Merchant Center account user. Executing @@ -390,18 +402,18 @@ def delete_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_user' not in self._stubs: - self._stubs['delete_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/DeleteUser', + if "delete_user" not in self._stubs: + self._stubs["delete_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/DeleteUser", request_serializer=user.DeleteUserRequest.serialize, response_deserializer=empty_pb2.Empty.FromString, ) - return self._stubs['delete_user'] + return self._stubs["delete_user"] @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - Awaitable[gsma_user.User]]: + def update_user( + self, + ) -> Callable[[gsma_user.UpdateUserRequest], Awaitable[gsma_user.User]]: r"""Return a callable for the update user method over gRPC. Updates a Merchant Center account user. Executing @@ -417,18 +429,18 @@ def update_user(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_user' not in self._stubs: - self._stubs['update_user'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/UpdateUser', + if "update_user" not in self._stubs: + self._stubs["update_user"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/UpdateUser", request_serializer=gsma_user.UpdateUserRequest.serialize, response_deserializer=gsma_user.User.deserialize, ) - return self._stubs['update_user'] + return self._stubs["update_user"] @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - Awaitable[user.ListUsersResponse]]: + def list_users( + self, + ) -> Callable[[user.ListUsersRequest], Awaitable[user.ListUsersResponse]]: r"""Return a callable for the list users method over gRPC. Lists all users of a Merchant Center account. @@ -443,16 +455,16 @@ def list_users(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_users' not in self._stubs: - self._stubs['list_users'] = self._logged_channel.unary_unary( - '/google.shopping.merchant.accounts.v1.UserService/ListUsers', + if "list_users" not in self._stubs: + self._stubs["list_users"] = self._logged_channel.unary_unary( + "/google.shopping.merchant.accounts.v1.UserService/ListUsers", request_serializer=user.ListUsersRequest.serialize, response_deserializer=user.ListUsersResponse.deserialize, ) - return self._stubs['list_users'] + return self._stubs["list_users"] 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.get_user: self._wrap_method( self.get_user, @@ -494,6 +506,4 @@ def kind(self) -> str: return "grpc_asyncio" -__all__ = ( - 'UserServiceGrpcAsyncIOTransport', -) +__all__ = ("UserServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py similarity index 71% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py index 776d02cced2a..54c95cae9f8f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/rest.py @@ -13,33 +13,27 @@ # 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_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user - -from .rest_base import _BaseUserServiceRestTransport from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseUserServiceRestTransport try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] @@ -48,6 +42,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 @@ -120,7 +115,12 @@ def post_update_user(self, response): """ - def pre_create_user(self, request: gsma_user.CreateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + + def pre_create_user( + self, + request: gsma_user.CreateUserRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gsma_user.CreateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for create_user Override in a subclass to manipulate the request or metadata @@ -141,7 +141,11 @@ def post_create_user(self, response: gsma_user.User) -> gsma_user.User: """ return response - def post_create_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_create_user_with_metadata( + self, + response: gsma_user.User, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for create_user Override in a subclass to read or manipulate the response or metadata after it @@ -156,7 +160,11 @@ def post_create_user_with_metadata(self, response: gsma_user.User, metadata: Seq """ return response, metadata - def pre_delete_user(self, request: user.DeleteUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_delete_user( + self, + request: user.DeleteUserRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[user.DeleteUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for delete_user Override in a subclass to manipulate the request or metadata @@ -164,7 +172,11 @@ def pre_delete_user(self, request: user.DeleteUserRequest, metadata: Sequence[Tu """ return request, metadata - def pre_get_user(self, request: user.GetUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_get_user( + self, + request: user.GetUserRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[user.GetUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for get_user Override in a subclass to manipulate the request or metadata @@ -185,7 +197,9 @@ def post_get_user(self, response: user.User) -> user.User: """ return response - def post_get_user_with_metadata(self, response: user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_get_user_with_metadata( + self, response: user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[user.User, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for get_user Override in a subclass to read or manipulate the response or metadata after it @@ -200,7 +214,11 @@ def post_get_user_with_metadata(self, response: user.User, metadata: Sequence[Tu """ return response, metadata - def pre_list_users(self, request: user.ListUsersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_list_users( + self, + request: user.ListUsersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[user.ListUsersRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for list_users Override in a subclass to manipulate the request or metadata @@ -208,7 +226,9 @@ def pre_list_users(self, request: user.ListUsersRequest, metadata: Sequence[Tupl """ return request, metadata - def post_list_users(self, response: user.ListUsersResponse) -> user.ListUsersResponse: + def post_list_users( + self, response: user.ListUsersResponse + ) -> user.ListUsersResponse: """Post-rpc interceptor for list_users DEPRECATED. Please use the `post_list_users_with_metadata` @@ -221,7 +241,11 @@ def post_list_users(self, response: user.ListUsersResponse) -> user.ListUsersRes """ return response - def post_list_users_with_metadata(self, response: user.ListUsersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[user.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_list_users_with_metadata( + self, + response: user.ListUsersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[user.ListUsersResponse, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for list_users Override in a subclass to read or manipulate the response or metadata after it @@ -236,7 +260,11 @@ def post_list_users_with_metadata(self, response: user.ListUsersResponse, metada """ return response, metadata - def pre_update_user(self, request: gsma_user.UpdateUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + def pre_update_user( + self, + request: gsma_user.UpdateUserRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gsma_user.UpdateUserRequest, Sequence[Tuple[str, Union[str, bytes]]]]: """Pre-rpc interceptor for update_user Override in a subclass to manipulate the request or metadata @@ -257,7 +285,11 @@ def post_update_user(self, response: gsma_user.User) -> gsma_user.User: """ return response - def post_update_user_with_metadata(self, response: gsma_user.User, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: + def post_update_user_with_metadata( + self, + response: gsma_user.User, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gsma_user.User, Sequence[Tuple[str, Union[str, bytes]]]]: """Post-rpc interceptor for update_user Override in a subclass to read or manipulate the response or metadata after it @@ -292,20 +324,21 @@ class UserServiceRestTransport(_BaseUserServiceRestTransport): 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[UserServiceRestInterceptor] = 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[UserServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -348,16 +381,19 @@ 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 UserServiceRestInterceptor() self._prep_wrapped_messages(client_info) - class _CreateUser(_BaseUserServiceRestTransport._BaseCreateUser, UserServiceRestStub): + class _CreateUser( + _BaseUserServiceRestTransport._BaseCreateUser, UserServiceRestStub + ): def __hash__(self): return hash("UserServiceRestTransport.CreateUser") @@ -369,27 +405,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: gsma_user.CreateUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_user.User: + def __call__( + self, + request: gsma_user.CreateUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: r"""Call the create user method over HTTP. Args: @@ -414,32 +452,48 @@ def __call__(self, """ - http_options = _BaseUserServiceRestTransport._BaseCreateUser._get_http_options() + http_options = ( + _BaseUserServiceRestTransport._BaseCreateUser._get_http_options() + ) request, metadata = self._interceptor.pre_create_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseCreateUser._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseUserServiceRestTransport._BaseCreateUser._get_transcoded_request( + http_options, request + ) + ) - body = _BaseUserServiceRestTransport._BaseCreateUser._get_request_body_json(transcoded_request) + body = _BaseUserServiceRestTransport._BaseCreateUser._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseCreateUser._get_query_params_json(transcoded_request) + query_params = ( + _BaseUserServiceRestTransport._BaseCreateUser._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.shopping.merchant.accounts_v1.UserServiceClient.CreateUser", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "CreateUser", "httpRequest": http_request, @@ -448,7 +502,15 @@ def __call__(self, ) # Send the request - response = UserServiceRestTransport._CreateUser._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = UserServiceRestTransport._CreateUser._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 +525,24 @@ def __call__(self, resp = self._interceptor.post_create_user(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_create_user_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = gsma_user.User.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.accounts_v1.UserServiceClient.create_user", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "CreateUser", "metadata": http_response["headers"], @@ -485,7 +551,9 @@ def __call__(self, ) return resp - class _DeleteUser(_BaseUserServiceRestTransport._BaseDeleteUser, UserServiceRestStub): + class _DeleteUser( + _BaseUserServiceRestTransport._BaseDeleteUser, UserServiceRestStub + ): def __hash__(self): return hash("UserServiceRestTransport.DeleteUser") @@ -497,26 +565,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: user.DeleteUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): + def __call__( + self, + request: user.DeleteUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): r"""Call the delete user method over HTTP. Args: @@ -531,30 +601,44 @@ def __call__(self, be of type `bytes`. """ - http_options = _BaseUserServiceRestTransport._BaseDeleteUser._get_http_options() + http_options = ( + _BaseUserServiceRestTransport._BaseDeleteUser._get_http_options() + ) request, metadata = self._interceptor.pre_delete_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseDeleteUser._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseUserServiceRestTransport._BaseDeleteUser._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseDeleteUser._get_query_params_json(transcoded_request) + query_params = ( + _BaseUserServiceRestTransport._BaseDeleteUser._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = 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.accounts_v1.UserServiceClient.DeleteUser", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "DeleteUser", "httpRequest": http_request, @@ -563,7 +647,14 @@ def __call__(self, ) # Send the request - response = UserServiceRestTransport._DeleteUser._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = UserServiceRestTransport._DeleteUser._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -582,26 +673,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: user.GetUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> user.User: + def __call__( + self, + request: user.GetUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.User: r"""Call the get user method over HTTP. Args: @@ -626,30 +719,44 @@ def __call__(self, """ - http_options = _BaseUserServiceRestTransport._BaseGetUser._get_http_options() + http_options = ( + _BaseUserServiceRestTransport._BaseGetUser._get_http_options() + ) request, metadata = self._interceptor.pre_get_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseGetUser._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseUserServiceRestTransport._BaseGetUser._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseGetUser._get_query_params_json(transcoded_request) + query_params = ( + _BaseUserServiceRestTransport._BaseGetUser._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.shopping.merchant.accounts_v1.UserServiceClient.GetUser", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "GetUser", "httpRequest": http_request, @@ -658,7 +765,14 @@ def __call__(self, ) # Send the request - response = UserServiceRestTransport._GetUser._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = UserServiceRestTransport._GetUser._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -673,20 +787,24 @@ def __call__(self, resp = self._interceptor.post_get_user(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_get_user_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = user.User.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.accounts_v1.UserServiceClient.get_user", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "GetUser", "metadata": http_response["headers"], @@ -707,26 +825,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: user.ListUsersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> user.ListUsersResponse: + def __call__( + self, + request: user.ListUsersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> user.ListUsersResponse: r"""Call the list users method over HTTP. Args: @@ -745,30 +865,44 @@ def __call__(self, Response message for the ``ListUsers`` method. """ - http_options = _BaseUserServiceRestTransport._BaseListUsers._get_http_options() + http_options = ( + _BaseUserServiceRestTransport._BaseListUsers._get_http_options() + ) request, metadata = self._interceptor.pre_list_users(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseListUsers._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseUserServiceRestTransport._BaseListUsers._get_transcoded_request( + http_options, request + ) + ) # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseListUsers._get_query_params_json(transcoded_request) + query_params = ( + _BaseUserServiceRestTransport._BaseListUsers._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.shopping.merchant.accounts_v1.UserServiceClient.ListUsers", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "ListUsers", "httpRequest": http_request, @@ -777,7 +911,14 @@ def __call__(self, ) # Send the request - response = UserServiceRestTransport._ListUsers._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + response = UserServiceRestTransport._ListUsers._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -792,20 +933,24 @@ def __call__(self, resp = self._interceptor.post_list_users(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_users_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_list_users_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = user.ListUsersResponse.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.accounts_v1.UserServiceClient.list_users", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "ListUsers", "metadata": http_response["headers"], @@ -814,7 +959,9 @@ def __call__(self, ) return resp - class _UpdateUser(_BaseUserServiceRestTransport._BaseUpdateUser, UserServiceRestStub): + class _UpdateUser( + _BaseUserServiceRestTransport._BaseUpdateUser, UserServiceRestStub + ): def __hash__(self): return hash("UserServiceRestTransport.UpdateUser") @@ -826,27 +973,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: gsma_user.UpdateUserRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> gsma_user.User: + def __call__( + self, + request: gsma_user.UpdateUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gsma_user.User: r"""Call the update user method over HTTP. Args: @@ -871,32 +1020,48 @@ def __call__(self, """ - http_options = _BaseUserServiceRestTransport._BaseUpdateUser._get_http_options() + http_options = ( + _BaseUserServiceRestTransport._BaseUpdateUser._get_http_options() + ) request, metadata = self._interceptor.pre_update_user(request, metadata) - transcoded_request = _BaseUserServiceRestTransport._BaseUpdateUser._get_transcoded_request(http_options, request) + transcoded_request = ( + _BaseUserServiceRestTransport._BaseUpdateUser._get_transcoded_request( + http_options, request + ) + ) - body = _BaseUserServiceRestTransport._BaseUpdateUser._get_request_body_json(transcoded_request) + body = _BaseUserServiceRestTransport._BaseUpdateUser._get_request_body_json( + transcoded_request + ) # Jsonify the query params - query_params = _BaseUserServiceRestTransport._BaseUpdateUser._get_query_params_json(transcoded_request) + query_params = ( + _BaseUserServiceRestTransport._BaseUpdateUser._get_query_params_json( + transcoded_request + ) + ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] try: request_payload = type(request).to_json(request) except: request_payload = None http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), } _LOGGER.debug( f"Sending request for google.shopping.merchant.accounts_v1.UserServiceClient.UpdateUser", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "UpdateUser", "httpRequest": http_request, @@ -905,7 +1070,15 @@ def __call__(self, ) # Send the request - response = UserServiceRestTransport._UpdateUser._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + response = UserServiceRestTransport._UpdateUser._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -920,20 +1093,24 @@ def __call__(self, resp = self._interceptor.post_update_user(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_user_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + resp, _ = self._interceptor.post_update_user_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER try: response_payload = gsma_user.User.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.accounts_v1.UserServiceClient.update_user", - extra = { + extra={ "serviceName": "google.shopping.merchant.accounts.v1.UserService", "rpcName": "UpdateUser", "metadata": http_response["headers"], @@ -943,44 +1120,34 @@ def __call__(self, return resp @property - def create_user(self) -> Callable[ - [gsma_user.CreateUserRequest], - gsma_user.User]: + def create_user(self) -> Callable[[gsma_user.CreateUserRequest], gsma_user.User]: # 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._CreateUser(self._session, self._host, self._interceptor) # type: ignore + return self._CreateUser(self._session, self._host, self._interceptor) # type: ignore @property - def delete_user(self) -> Callable[ - [user.DeleteUserRequest], - empty_pb2.Empty]: + def delete_user(self) -> Callable[[user.DeleteUserRequest], 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._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore @property - def get_user(self) -> Callable[ - [user.GetUserRequest], - user.User]: + def get_user(self) -> Callable[[user.GetUserRequest], user.User]: # 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._GetUser(self._session, self._host, self._interceptor) # type: ignore + return self._GetUser(self._session, self._host, self._interceptor) # type: ignore @property - def list_users(self) -> Callable[ - [user.ListUsersRequest], - user.ListUsersResponse]: + def list_users(self) -> Callable[[user.ListUsersRequest], user.ListUsersResponse]: # 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._ListUsers(self._session, self._host, self._interceptor) # type: ignore + return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore @property - def update_user(self) -> Callable[ - [gsma_user.UpdateUserRequest], - gsma_user.User]: + def update_user(self) -> Callable[[gsma_user.UpdateUserRequest], gsma_user.User]: # 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._UpdateUser(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateUser(self._session, self._host, self._interceptor) # type: ignore @property def kind(self) -> str: @@ -990,6 +1157,4 @@ def close(self): self._session.close() -__all__=( - 'UserServiceRestTransport', -) +__all__ = ("UserServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py similarity index 58% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py index 8de3929910a7..4efcb304949c 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/services/user_service/transports/rest_base.py @@ -14,20 +14,18 @@ # limitations under the License. # import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from .base import UserServiceTransport, 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_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user +from .base import DEFAULT_CLIENT_INFO, UserServiceTransport + class _BaseUserServiceRestTransport(UserServiceTransport): """Base REST backend transport for UserService. @@ -42,14 +40,16 @@ class _BaseUserServiceRestTransport(UserServiceTransport): 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]): @@ -73,7 +73,9 @@ def __init__(self, *, # Run the base constructor maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -84,27 +86,33 @@ 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 _BaseCreateUser: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userId" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userId": "", + } @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': '/accounts/v1/{parent=accounts/*}/users', - 'body': 'user', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/accounts/v1/{parent=accounts/*}/users", + "body": "user", + }, ] return http_options @@ -119,17 +127,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(_BaseUserServiceRestTransport._BaseCreateUser._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( + _BaseUserServiceRestTransport._BaseCreateUser._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -138,19 +152,23 @@ class _BaseDeleteUser: 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': '/accounts/v1/{name=accounts/*/users/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/accounts/v1/{name=accounts/*/users/*}", + }, ] return http_options @@ -162,11 +180,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(_BaseUserServiceRestTransport._BaseDeleteUser._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( + _BaseUserServiceRestTransport._BaseDeleteUser._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -175,19 +199,23 @@ class _BaseGetUser: 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': '/accounts/v1/{name=accounts/*/users/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{name=accounts/*/users/*}", + }, ] return http_options @@ -199,11 +227,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(_BaseUserServiceRestTransport._BaseGetUser._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( + _BaseUserServiceRestTransport._BaseGetUser._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -212,19 +246,23 @@ class _BaseListUsers: 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': '/accounts/v1/{parent=accounts/*}/users', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/accounts/v1/{parent=accounts/*}/users", + }, ] return http_options @@ -236,11 +274,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(_BaseUserServiceRestTransport._BaseListUsers._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( + _BaseUserServiceRestTransport._BaseListUsers._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params @@ -249,20 +293,24 @@ class _BaseUpdateUser: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } @staticmethod def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/accounts/v1/{user.name=accounts/*/users/*}', - 'body': 'user', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/accounts/v1/{user.name=accounts/*/users/*}", + "body": "user", + }, ] return http_options @@ -277,22 +325,26 @@ def _get_request_body_json(transcoded_request): # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True + transcoded_request["body"], use_integers_for_enums=True ) return body + @staticmethod def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseUserServiceRestTransport._BaseUpdateUser._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( + _BaseUserServiceRestTransport._BaseUpdateUser._get_unset_required_fields( + query_params + ) + ) query_params["$alt"] = "json;enum-encoding=int" return query_params -__all__=( - '_BaseUserServiceRestTransport', -) +__all__ = ("_BaseUserServiceRestTransport",) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/__init__.py similarity index 53% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/__init__.py index c79bc85f5c8c..9843920a31a6 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/__init__.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/__init__.py @@ -13,9 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .accessright import ( - AccessRight, -) +from .accessright import AccessRight from .accountissue import ( AccountIssue, ListAccountIssuesRequest, @@ -85,9 +83,7 @@ UpdateCheckoutSettingsRequest, UriSettings, ) -from .customerservice import ( - CustomerService, -) +from .customerservice import CustomerService from .developerregistration import ( DeveloperRegistration, GetDeveloperRegistrationRequest, @@ -145,9 +141,7 @@ ListOnlineReturnPoliciesResponse, OnlineReturnPolicy, ) -from .phoneverificationstate import ( - PhoneVerificationState, -) +from .phoneverificationstate import PhoneVerificationState from .programs import ( DisableProgramRequest, EnableProgramRequest, @@ -202,9 +196,7 @@ RetrieveForApplicationTermsOfServiceAgreementStateRequest, TermsOfServiceAgreementState, ) -from .termsofservicekind import ( - TermsOfServiceKind, -) +from .termsofservicekind import TermsOfServiceKind from .user import ( CreateUserRequest, DeleteUserRequest, @@ -216,153 +208,153 @@ ) __all__ = ( - 'AccessRight', - 'AccountIssue', - 'ListAccountIssuesRequest', - 'ListAccountIssuesResponse', - 'AccountRelationship', - 'GetAccountRelationshipRequest', - 'ListAccountRelationshipsRequest', - 'ListAccountRelationshipsResponse', - 'UpdateAccountRelationshipRequest', - 'Account', - 'CreateAndConfigureAccountRequest', - 'DeleteAccountRequest', - 'GetAccountRequest', - 'ListAccountsRequest', - 'ListAccountsResponse', - 'ListSubAccountsRequest', - 'ListSubAccountsResponse', - 'UpdateAccountRequest', - 'AccountAggregation', - 'AccountManagement', - 'AccountService', - 'ApproveAccountServiceRequest', - 'CampaignsManagement', - 'GetAccountServiceRequest', - 'Handshake', - 'ListAccountServicesRequest', - 'ListAccountServicesResponse', - 'LocalListingManagement', - 'ProductsManagement', - 'ProposeAccountServiceRequest', - 'RejectAccountServiceRequest', - 'AutofeedSettings', - 'GetAutofeedSettingsRequest', - 'UpdateAutofeedSettingsRequest', - 'AutomaticImageImprovements', - 'AutomaticImprovements', - 'AutomaticItemUpdates', - 'AutomaticShippingImprovements', - 'GetAutomaticImprovementsRequest', - 'UpdateAutomaticImprovementsRequest', - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', - 'CheckoutSettings', - 'CreateCheckoutSettingsRequest', - 'DeleteCheckoutSettingsRequest', - 'GetCheckoutSettingsRequest', - 'UpdateCheckoutSettingsRequest', - 'UriSettings', - 'CustomerService', - 'DeveloperRegistration', - 'GetDeveloperRegistrationRequest', - 'RegisterGcpRequest', - 'UnregisterGcpRequest', - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', - 'GbpAccount', - 'LinkGbpAccountRequest', - 'LinkGbpAccountResponse', - 'ListGbpAccountsRequest', - 'ListGbpAccountsResponse', - 'ClaimHomepageRequest', - 'GetHomepageRequest', - 'Homepage', - 'UnclaimHomepageRequest', - 'UpdateHomepageRequest', - 'FindLfpProvidersRequest', - 'FindLfpProvidersResponse', - 'LfpProvider', - 'LinkLfpProviderRequest', - 'LinkLfpProviderResponse', - 'About', - 'CreateOmnichannelSettingRequest', - 'GetOmnichannelSettingRequest', - 'InStock', - 'InventoryVerification', - 'LfpLink', - 'ListOmnichannelSettingsRequest', - 'ListOmnichannelSettingsResponse', - 'OmnichannelSetting', - 'OnDisplayToOrder', - 'Pickup', - 'RequestInventoryVerificationRequest', - 'RequestInventoryVerificationResponse', - 'ReviewState', - 'UpdateOmnichannelSettingRequest', - 'CreateOnlineReturnPolicyRequest', - 'DeleteOnlineReturnPolicyRequest', - 'GetOnlineReturnPolicyRequest', - 'ListOnlineReturnPoliciesRequest', - 'ListOnlineReturnPoliciesResponse', - 'OnlineReturnPolicy', - 'PhoneVerificationState', - 'DisableProgramRequest', - 'EnableProgramRequest', - 'GetProgramRequest', - 'ListProgramsRequest', - 'ListProgramsResponse', - 'Program', - 'CreateRegionRequest', - 'DeleteRegionRequest', - 'GetRegionRequest', - 'ListRegionsRequest', - 'ListRegionsResponse', - 'Region', - 'UpdateRegionRequest', - 'Address', - 'BusinessDayConfig', - 'CarrierRate', - 'CutoffTime', - 'DeliveryTime', - 'Distance', - 'GetShippingSettingsRequest', - 'Headers', - 'InsertShippingSettingsRequest', - 'LocationIdSet', - 'MinimumOrderValueTable', - 'RateGroup', - 'Row', - 'Service', - 'ShippingSettings', - 'Table', - 'TransitTable', - 'Value', - 'Warehouse', - 'WarehouseBasedDeliveryTime', - 'WarehouseCutoffTime', - 'AcceptTermsOfServiceRequest', - 'AcceptTermsOfServiceResponse', - 'GetTermsOfServiceRequest', - 'RetrieveLatestTermsOfServiceRequest', - 'TermsOfService', - 'Accepted', - 'GetTermsOfServiceAgreementStateRequest', - 'Required', - 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', - 'TermsOfServiceAgreementState', - 'TermsOfServiceKind', - 'CreateUserRequest', - 'DeleteUserRequest', - 'GetUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', - 'UpdateUserRequest', - 'User', + "AccessRight", + "AccountIssue", + "ListAccountIssuesRequest", + "ListAccountIssuesResponse", + "AccountRelationship", + "GetAccountRelationshipRequest", + "ListAccountRelationshipsRequest", + "ListAccountRelationshipsResponse", + "UpdateAccountRelationshipRequest", + "Account", + "CreateAndConfigureAccountRequest", + "DeleteAccountRequest", + "GetAccountRequest", + "ListAccountsRequest", + "ListAccountsResponse", + "ListSubAccountsRequest", + "ListSubAccountsResponse", + "UpdateAccountRequest", + "AccountAggregation", + "AccountManagement", + "AccountService", + "ApproveAccountServiceRequest", + "CampaignsManagement", + "GetAccountServiceRequest", + "Handshake", + "ListAccountServicesRequest", + "ListAccountServicesResponse", + "LocalListingManagement", + "ProductsManagement", + "ProposeAccountServiceRequest", + "RejectAccountServiceRequest", + "AutofeedSettings", + "GetAutofeedSettingsRequest", + "UpdateAutofeedSettingsRequest", + "AutomaticImageImprovements", + "AutomaticImprovements", + "AutomaticItemUpdates", + "AutomaticShippingImprovements", + "GetAutomaticImprovementsRequest", + "UpdateAutomaticImprovementsRequest", + "BusinessIdentity", + "GetBusinessIdentityRequest", + "UpdateBusinessIdentityRequest", + "BusinessInfo", + "GetBusinessInfoRequest", + "UpdateBusinessInfoRequest", + "CheckoutSettings", + "CreateCheckoutSettingsRequest", + "DeleteCheckoutSettingsRequest", + "GetCheckoutSettingsRequest", + "UpdateCheckoutSettingsRequest", + "UriSettings", + "CustomerService", + "DeveloperRegistration", + "GetDeveloperRegistrationRequest", + "RegisterGcpRequest", + "UnregisterGcpRequest", + "EmailPreferences", + "GetEmailPreferencesRequest", + "UpdateEmailPreferencesRequest", + "GbpAccount", + "LinkGbpAccountRequest", + "LinkGbpAccountResponse", + "ListGbpAccountsRequest", + "ListGbpAccountsResponse", + "ClaimHomepageRequest", + "GetHomepageRequest", + "Homepage", + "UnclaimHomepageRequest", + "UpdateHomepageRequest", + "FindLfpProvidersRequest", + "FindLfpProvidersResponse", + "LfpProvider", + "LinkLfpProviderRequest", + "LinkLfpProviderResponse", + "About", + "CreateOmnichannelSettingRequest", + "GetOmnichannelSettingRequest", + "InStock", + "InventoryVerification", + "LfpLink", + "ListOmnichannelSettingsRequest", + "ListOmnichannelSettingsResponse", + "OmnichannelSetting", + "OnDisplayToOrder", + "Pickup", + "RequestInventoryVerificationRequest", + "RequestInventoryVerificationResponse", + "ReviewState", + "UpdateOmnichannelSettingRequest", + "CreateOnlineReturnPolicyRequest", + "DeleteOnlineReturnPolicyRequest", + "GetOnlineReturnPolicyRequest", + "ListOnlineReturnPoliciesRequest", + "ListOnlineReturnPoliciesResponse", + "OnlineReturnPolicy", + "PhoneVerificationState", + "DisableProgramRequest", + "EnableProgramRequest", + "GetProgramRequest", + "ListProgramsRequest", + "ListProgramsResponse", + "Program", + "CreateRegionRequest", + "DeleteRegionRequest", + "GetRegionRequest", + "ListRegionsRequest", + "ListRegionsResponse", + "Region", + "UpdateRegionRequest", + "Address", + "BusinessDayConfig", + "CarrierRate", + "CutoffTime", + "DeliveryTime", + "Distance", + "GetShippingSettingsRequest", + "Headers", + "InsertShippingSettingsRequest", + "LocationIdSet", + "MinimumOrderValueTable", + "RateGroup", + "Row", + "Service", + "ShippingSettings", + "Table", + "TransitTable", + "Value", + "Warehouse", + "WarehouseBasedDeliveryTime", + "WarehouseCutoffTime", + "AcceptTermsOfServiceRequest", + "AcceptTermsOfServiceResponse", + "GetTermsOfServiceRequest", + "RetrieveLatestTermsOfServiceRequest", + "TermsOfService", + "Accepted", + "GetTermsOfServiceAgreementStateRequest", + "Required", + "RetrieveForApplicationTermsOfServiceAgreementStateRequest", + "TermsOfServiceAgreementState", + "TermsOfServiceKind", + "CreateUserRequest", + "DeleteUserRequest", + "GetUserRequest", + "ListUsersRequest", + "ListUsersResponse", + "UpdateUserRequest", + "User", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accessright.py similarity index 95% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accessright.py index 08b75f89ef8c..e36e0a87c928 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accessright.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accessright.py @@ -19,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'AccessRight', + "AccessRight", }, ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountissue.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountissue.py index 5014a9b66738..ff57d53b4179 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountissue.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountissue.py @@ -17,17 +17,15 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.shopping.type.types import types - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'AccountIssue', - 'ListAccountIssuesRequest', - 'ListAccountIssuesResponse', + "AccountIssue", + "ListAccountIssuesRequest", + "ListAccountIssuesResponse", }, ) @@ -57,6 +55,7 @@ class AccountIssue(proto.Message): further information about the issue and how to fix it. """ + class Severity(proto.Enum): r"""All possible issue severities. @@ -107,10 +106,10 @@ class Impact(proto.Message): proto.STRING, number=1, ) - severity: 'AccountIssue.Severity' = proto.Field( + severity: "AccountIssue.Severity" = proto.Field( proto.ENUM, number=2, - enum='AccountIssue.Severity', + enum="AccountIssue.Severity", ) reporting_context: types.ReportingContext.ReportingContextEnum = proto.Field( @@ -119,10 +118,12 @@ class Impact(proto.Message): optional=True, enum=types.ReportingContext.ReportingContextEnum, ) - impacts: MutableSequence['AccountIssue.ImpactedDestination.Impact'] = proto.RepeatedField( + impacts: MutableSequence[ + "AccountIssue.ImpactedDestination.Impact" + ] = proto.RepeatedField( proto.MESSAGE, number=2, - message='AccountIssue.ImpactedDestination.Impact', + message="AccountIssue.ImpactedDestination.Impact", ) name: str = proto.Field( @@ -225,10 +226,10 @@ class ListAccountIssuesResponse(proto.Message): def raw_page(self): return self - account_issues: MutableSequence['AccountIssue'] = proto.RepeatedField( + account_issues: MutableSequence["AccountIssue"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AccountIssue', + message="AccountIssue", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountrelationships.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountrelationships.py index 97dc0cdd5333..4bb8c696b5b9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountrelationships.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountrelationships.py @@ -17,19 +17,17 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'AccountRelationship', - 'GetAccountRelationshipRequest', - 'UpdateAccountRelationshipRequest', - 'ListAccountRelationshipsRequest', - 'ListAccountRelationshipsResponse', + "AccountRelationship", + "GetAccountRelationshipRequest", + "UpdateAccountRelationshipRequest", + "ListAccountRelationshipsRequest", + "ListAccountRelationshipsResponse", }, ) @@ -128,10 +126,10 @@ class UpdateAccountRelationshipRequest(proto.Message): - ``account_id_alias`` """ - account_relationship: 'AccountRelationship' = proto.Field( + account_relationship: "AccountRelationship" = proto.Field( proto.MESSAGE, number=1, - message='AccountRelationship', + message="AccountRelationship", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -188,10 +186,10 @@ class ListAccountRelationshipsResponse(proto.Message): def raw_page(self): return self - account_relationships: MutableSequence['AccountRelationship'] = proto.RepeatedField( + account_relationships: MutableSequence["AccountRelationship"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AccountRelationship', + message="AccountRelationship", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accounts.py similarity index 95% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accounts.py index 18b283ad6fa5..25ef06209b82 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accounts.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accounts.py @@ -17,26 +17,25 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import field_mask_pb2 # type: ignore +from google.type import datetime_pb2 # type: ignore import proto # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore from google.shopping.merchant_accounts_v1.types import accountservices from google.shopping.merchant_accounts_v1.types import user as gsma_user -from google.type import datetime_pb2 # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'Account', - 'GetAccountRequest', - 'CreateAndConfigureAccountRequest', - 'DeleteAccountRequest', - 'UpdateAccountRequest', - 'ListAccountsRequest', - 'ListAccountsResponse', - 'ListSubAccountsRequest', - 'ListSubAccountsResponse', + "Account", + "GetAccountRequest", + "CreateAndConfigureAccountRequest", + "DeleteAccountRequest", + "UpdateAccountRequest", + "ListAccountsRequest", + "ListAccountsResponse", + "ListSubAccountsRequest", + "ListSubAccountsResponse", }, ) @@ -216,7 +215,7 @@ class AddAccountService(proto.Message): account_aggregation: accountservices.AccountAggregation = proto.Field( proto.MESSAGE, number=103, - oneof='service_type', + oneof="service_type", message=accountservices.AccountAggregation, ) provider: str = proto.Field( @@ -225,10 +224,10 @@ class AddAccountService(proto.Message): optional=True, ) - account: 'Account' = proto.Field( + account: "Account" = proto.Field( proto.MESSAGE, number=1, - message='Account', + message="Account", ) user: MutableSequence[AddUser] = proto.RepeatedField( proto.MESSAGE, @@ -283,10 +282,10 @@ class UpdateAccountRequest(proto.Message): - ``time_zone`` """ - account: 'Account' = proto.Field( + account: "Account" = proto.Field( proto.MESSAGE, number=1, - message='Account', + message="Account", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -350,10 +349,10 @@ class ListAccountsResponse(proto.Message): def raw_page(self): return self - accounts: MutableSequence['Account'] = proto.RepeatedField( + accounts: MutableSequence["Account"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='Account', + message="Account", ) next_page_token: str = proto.Field( proto.STRING, @@ -415,10 +414,10 @@ class ListSubAccountsResponse(proto.Message): def raw_page(self): return self - accounts: MutableSequence['Account'] = proto.RepeatedField( + accounts: MutableSequence["Account"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='Account', + message="Account", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountservices.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountservices.py index 57f4ff4775da..bc0c30202aea 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/accountservices.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/accountservices.py @@ -19,23 +19,22 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'AccountService', - 'GetAccountServiceRequest', - 'ListAccountServicesRequest', - 'ListAccountServicesResponse', - 'ProposeAccountServiceRequest', - 'ApproveAccountServiceRequest', - 'RejectAccountServiceRequest', - 'ProductsManagement', - 'CampaignsManagement', - 'AccountManagement', - 'AccountAggregation', - 'LocalListingManagement', - 'Handshake', + "AccountService", + "GetAccountServiceRequest", + "ListAccountServicesRequest", + "ListAccountServicesResponse", + "ProposeAccountServiceRequest", + "ApproveAccountServiceRequest", + "RejectAccountServiceRequest", + "ProductsManagement", + "CampaignsManagement", + "AccountManagement", + "AccountAggregation", + "LocalListingManagement", + "Handshake", }, ) @@ -152,6 +151,7 @@ class AccountService(proto.Message): ensuring accurate linking and integration between Google and the provider. """ + class Mutability(proto.Enum): r"""The list of mutability option settings a service can have. @@ -169,35 +169,35 @@ class Mutability(proto.Enum): MUTABLE = 1 IMMUTABLE = 2 - products_management: 'ProductsManagement' = proto.Field( + products_management: "ProductsManagement" = proto.Field( proto.MESSAGE, number=100, - oneof='service_type', - message='ProductsManagement', + oneof="service_type", + message="ProductsManagement", ) - campaigns_management: 'CampaignsManagement' = proto.Field( + campaigns_management: "CampaignsManagement" = proto.Field( proto.MESSAGE, number=101, - oneof='service_type', - message='CampaignsManagement', + oneof="service_type", + message="CampaignsManagement", ) - account_management: 'AccountManagement' = proto.Field( + account_management: "AccountManagement" = proto.Field( proto.MESSAGE, number=102, - oneof='service_type', - message='AccountManagement', + oneof="service_type", + message="AccountManagement", ) - account_aggregation: 'AccountAggregation' = proto.Field( + account_aggregation: "AccountAggregation" = proto.Field( proto.MESSAGE, number=103, - oneof='service_type', - message='AccountAggregation', + oneof="service_type", + message="AccountAggregation", ) - local_listing_management: 'LocalListingManagement' = proto.Field( + local_listing_management: "LocalListingManagement" = proto.Field( proto.MESSAGE, number=104, - oneof='service_type', - message='LocalListingManagement', + oneof="service_type", + message="LocalListingManagement", ) name: str = proto.Field( proto.STRING, @@ -212,10 +212,10 @@ class Mutability(proto.Enum): proto.STRING, number=3, ) - handshake: 'Handshake' = proto.Field( + handshake: "Handshake" = proto.Field( proto.MESSAGE, number=4, - message='Handshake', + message="Handshake", ) mutability: Mutability = proto.Field( proto.ENUM, @@ -290,10 +290,10 @@ class ListAccountServicesResponse(proto.Message): def raw_page(self): return self - account_services: MutableSequence['AccountService'] = proto.RepeatedField( + account_services: MutableSequence["AccountService"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='AccountService', + message="AccountService", ) next_page_token: str = proto.Field( proto.STRING, @@ -325,10 +325,10 @@ class ProposeAccountServiceRequest(proto.Message): proto.STRING, number=2, ) - account_service: 'AccountService' = proto.Field( + account_service: "AccountService" = proto.Field( proto.MESSAGE, number=4, - message='AccountService', + message="AccountService", ) @@ -363,28 +363,23 @@ class RejectAccountServiceRequest(proto.Message): class ProductsManagement(proto.Message): - r"""``ProductsManagement`` payload. - """ + r"""``ProductsManagement`` payload.""" class CampaignsManagement(proto.Message): - r"""``CampaignManagement`` payload. - """ + r"""``CampaignManagement`` payload.""" class AccountManagement(proto.Message): - r"""``AccountManagement`` payload. - """ + r"""``AccountManagement`` payload.""" class AccountAggregation(proto.Message): - r"""``AccountAggregation`` payload. - """ + r"""``AccountAggregation`` payload.""" class LocalListingManagement(proto.Message): - r"""``LocalListingManagement`` payload. - """ + r"""``LocalListingManagement`` payload.""" class Handshake(proto.Message): @@ -399,6 +394,7 @@ class Handshake(proto.Message): Output only. The most recent account to modify the account service's ``approval_status``. """ + class ApprovalState(proto.Enum): r"""The approal state of a handshake. diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/autofeedsettings.py similarity index 92% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/autofeedsettings.py index 25b4fa8cb1d9..b5e2dd166605 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/autofeedsettings.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/autofeedsettings.py @@ -17,17 +17,15 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'AutofeedSettings', - 'GetAutofeedSettingsRequest', - 'UpdateAutofeedSettingsRequest', + "AutofeedSettings", + "GetAutofeedSettingsRequest", + "UpdateAutofeedSettingsRequest", }, ) @@ -96,10 +94,10 @@ class UpdateAutofeedSettingsRequest(proto.Message): Required. List of fields being updated. """ - autofeed_settings: 'AutofeedSettings' = proto.Field( + autofeed_settings: "AutofeedSettings" = proto.Field( proto.MESSAGE, number=1, - message='AutofeedSettings', + message="AutofeedSettings", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/automaticimprovements.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/automaticimprovements.py index fde803eb73e1..8126bdffb729 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/automaticimprovements.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/automaticimprovements.py @@ -17,20 +17,18 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'AutomaticImprovements', - 'AutomaticItemUpdates', - 'AutomaticImageImprovements', - 'AutomaticShippingImprovements', - 'GetAutomaticImprovementsRequest', - 'UpdateAutomaticImprovementsRequest', + "AutomaticImprovements", + "AutomaticItemUpdates", + "AutomaticImageImprovements", + "AutomaticShippingImprovements", + "GetAutomaticImprovementsRequest", + "UpdateAutomaticImprovementsRequest", }, ) @@ -95,23 +93,23 @@ class AutomaticImprovements(proto.Message): proto.STRING, number=1, ) - item_updates: 'AutomaticItemUpdates' = proto.Field( + item_updates: "AutomaticItemUpdates" = proto.Field( proto.MESSAGE, number=2, optional=True, - message='AutomaticItemUpdates', + message="AutomaticItemUpdates", ) - image_improvements: 'AutomaticImageImprovements' = proto.Field( + image_improvements: "AutomaticImageImprovements" = proto.Field( proto.MESSAGE, number=3, optional=True, - message='AutomaticImageImprovements', + message="AutomaticImageImprovements", ) - shipping_improvements: 'AutomaticShippingImprovements' = proto.Field( + shipping_improvements: "AutomaticShippingImprovements" = proto.Field( proto.MESSAGE, number=4, optional=True, - message='AutomaticShippingImprovements', + message="AutomaticShippingImprovements", ) @@ -291,11 +289,13 @@ class ImageImprovementsAccountLevelSettings(proto.Message): optional=True, ) - account_image_improvements_settings: ImageImprovementsAccountLevelSettings = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message=ImageImprovementsAccountLevelSettings, + account_image_improvements_settings: ImageImprovementsAccountLevelSettings = ( + proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=ImageImprovementsAccountLevelSettings, + ) ) effective_allow_automatic_image_improvements: bool = proto.Field( proto.BOOL, @@ -371,10 +371,10 @@ class UpdateAutomaticImprovementsRequest(proto.Message): - ``shipping_improvements.allow_shipping_improvements`` """ - automatic_improvements: 'AutomaticImprovements' = proto.Field( + automatic_improvements: "AutomaticImprovements" = proto.Field( proto.MESSAGE, number=1, - message='AutomaticImprovements', + message="AutomaticImprovements", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/businessidentity.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/businessidentity.py index 55adc191417b..ed0f4149958b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessidentity.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/businessidentity.py @@ -17,17 +17,15 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'BusinessIdentity', - 'GetBusinessIdentityRequest', - 'UpdateBusinessIdentityRequest', + "BusinessIdentity", + "GetBusinessIdentityRequest", + "UpdateBusinessIdentityRequest", }, ) @@ -73,6 +71,7 @@ class BusinessIdentity(proto.Message): available for businesses with a business country set to ``US``. It is also not applicable for marketplaces. """ + class PromotionsConsent(proto.Enum): r"""All possible settings regarding promotions related to the business identity. @@ -102,6 +101,7 @@ class IdentityAttribute(proto.Message): Required. The declaration of identity for this attribute. """ + class IdentityDeclaration(proto.Enum): r"""All possible settings regarding the declaration of an identity. @@ -121,10 +121,10 @@ class IdentityDeclaration(proto.Enum): SELF_IDENTIFIES_AS = 1 DOES_NOT_SELF_IDENTIFY_AS = 2 - identity_declaration: 'BusinessIdentity.IdentityAttribute.IdentityDeclaration' = proto.Field( + identity_declaration: "BusinessIdentity.IdentityAttribute.IdentityDeclaration" = proto.Field( proto.ENUM, number=1, - enum='BusinessIdentity.IdentityAttribute.IdentityDeclaration', + enum="BusinessIdentity.IdentityAttribute.IdentityDeclaration", ) name: str = proto.Field( @@ -200,10 +200,10 @@ class UpdateBusinessIdentityRequest(proto.Message): - ``women_owned`` """ - business_identity: 'BusinessIdentity' = proto.Field( + business_identity: "BusinessIdentity" = proto.Field( proto.MESSAGE, number=1, - message='BusinessIdentity', + message="BusinessIdentity", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/businessinfo.py similarity index 90% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/businessinfo.py index 2438cbe06be4..b99b3622d89f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/businessinfo.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/businessinfo.py @@ -17,21 +17,22 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.types import customerservice -from google.shopping.merchant_accounts_v1.types import phoneverificationstate from google.type import phone_number_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore +import proto # type: ignore +from google.shopping.merchant_accounts_v1.types import ( + customerservice, + phoneverificationstate, +) __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'BusinessInfo', - 'GetBusinessInfoRequest', - 'UpdateBusinessInfoRequest', + "BusinessInfo", + "GetBusinessInfoRequest", + "UpdateBusinessInfoRequest", }, ) @@ -96,11 +97,13 @@ class BusinessInfo(proto.Message): optional=True, message=phone_number_pb2.PhoneNumber, ) - phone_verification_state: phoneverificationstate.PhoneVerificationState = proto.Field( - proto.ENUM, - number=4, - optional=True, - enum=phoneverificationstate.PhoneVerificationState, + phone_verification_state: phoneverificationstate.PhoneVerificationState = ( + proto.Field( + proto.ENUM, + number=4, + optional=True, + enum=phoneverificationstate.PhoneVerificationState, + ) ) customer_service: customerservice.CustomerService = proto.Field( proto.MESSAGE, @@ -149,10 +152,10 @@ class UpdateBusinessInfoRequest(proto.Message): - ``korean_business_registration_number`` """ - business_info: 'BusinessInfo' = proto.Field( + business_info: "BusinessInfo" = proto.Field( proto.MESSAGE, number=1, - message='BusinessInfo', + message="BusinessInfo", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/checkoutsettings.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/checkoutsettings.py index 9175c01b1307..fd1836a5b264 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/checkoutsettings.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/checkoutsettings.py @@ -17,21 +17,19 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore from google.shopping.type.types import types - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'GetCheckoutSettingsRequest', - 'CreateCheckoutSettingsRequest', - 'UpdateCheckoutSettingsRequest', - 'DeleteCheckoutSettingsRequest', - 'CheckoutSettings', - 'UriSettings', + "GetCheckoutSettingsRequest", + "CreateCheckoutSettingsRequest", + "UpdateCheckoutSettingsRequest", + "DeleteCheckoutSettingsRequest", + "CheckoutSettings", + "UriSettings", }, ) @@ -67,10 +65,10 @@ class CreateCheckoutSettingsRequest(proto.Message): proto.STRING, number=1, ) - checkout_settings: 'CheckoutSettings' = proto.Field( + checkout_settings: "CheckoutSettings" = proto.Field( proto.MESSAGE, number=2, - message='CheckoutSettings', + message="CheckoutSettings", ) @@ -92,10 +90,10 @@ class UpdateCheckoutSettingsRequest(proto.Message): - ``uri_settings`` """ - checkout_settings: 'CheckoutSettings' = proto.Field( + checkout_settings: "CheckoutSettings" = proto.Field( proto.MESSAGE, number=1, - message='CheckoutSettings', + message="CheckoutSettings", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -181,6 +179,7 @@ class CheckoutSettings(proto.Message): This field is a member of `oneof`_ ``_effective_review_state``. """ + class CheckoutEnrollmentState(proto.Enum): r"""Enum indicating the enrollment state of merchant in ``Checkout`` program. @@ -231,13 +230,15 @@ class CheckoutReviewState(proto.Enum): proto.STRING, number=1, ) - uri_settings: 'UriSettings' = proto.Field( + uri_settings: "UriSettings" = proto.Field( proto.MESSAGE, number=2, optional=True, - message='UriSettings', + message="UriSettings", ) - eligible_destinations: MutableSequence[types.Destination.DestinationEnum] = proto.RepeatedField( + eligible_destinations: MutableSequence[ + types.Destination.DestinationEnum + ] = proto.RepeatedField( proto.ENUM, number=8, enum=types.Destination.DestinationEnum, @@ -254,10 +255,10 @@ class CheckoutReviewState(proto.Enum): optional=True, enum=CheckoutReviewState, ) - effective_uri_settings: 'UriSettings' = proto.Field( + effective_uri_settings: "UriSettings" = proto.Field( proto.MESSAGE, number=5, - message='UriSettings', + message="UriSettings", ) effective_enrollment_state: CheckoutEnrollmentState = proto.Field( proto.ENUM, @@ -305,12 +306,12 @@ class UriSettings(proto.Message): checkout_uri_template: str = proto.Field( proto.STRING, number=1, - oneof='uri_template', + oneof="uri_template", ) cart_uri_template: str = proto.Field( proto.STRING, number=2, - oneof='uri_template', + oneof="uri_template", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/customerservice.py similarity index 96% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/customerservice.py index c34d9eab4e24..b412c19bd177 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/customerservice.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/customerservice.py @@ -17,15 +17,13 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.type import phone_number_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'CustomerService', + "CustomerService", }, ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/developerregistration.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/developerregistration.py index bf865ae956db..aaa14722688e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/developerregistration.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/developerregistration.py @@ -19,14 +19,13 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'DeveloperRegistration', - 'RegisterGcpRequest', - 'UnregisterGcpRequest', - 'GetDeveloperRegistrationRequest', + "DeveloperRegistration", + "RegisterGcpRequest", + "UnregisterGcpRequest", + "GetDeveloperRegistrationRequest", }, ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/emailpreferences.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/emailpreferences.py index 792e2661f2f9..f8c5d7fe53db 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/emailpreferences.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/emailpreferences.py @@ -17,17 +17,15 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'EmailPreferences', - 'GetEmailPreferencesRequest', - 'UpdateEmailPreferencesRequest', + "EmailPreferences", + "GetEmailPreferencesRequest", + "UpdateEmailPreferencesRequest", }, ) @@ -46,6 +44,7 @@ class EmailPreferences(proto.Message): Optional. Updates on new features, tips and best practices. """ + class OptInState(proto.Enum): r"""Opt in state of the email preference. @@ -111,10 +110,10 @@ class UpdateEmailPreferencesRequest(proto.Message): - ``news_and_tips`` """ - email_preferences: 'EmailPreferences' = proto.Field( + email_preferences: "EmailPreferences" = proto.Field( proto.MESSAGE, number=1, - message='EmailPreferences', + message="EmailPreferences", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/gbpaccounts.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/gbpaccounts.py index 0e923f851a24..e024d70b6ff2 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/gbpaccounts.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/gbpaccounts.py @@ -17,19 +17,17 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import empty_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'GbpAccount', - 'ListGbpAccountsRequest', - 'ListGbpAccountsResponse', - 'LinkGbpAccountRequest', - 'LinkGbpAccountResponse', + "GbpAccount", + "ListGbpAccountsRequest", + "ListGbpAccountsResponse", + "LinkGbpAccountRequest", + "LinkGbpAccountResponse", }, ) @@ -54,6 +52,7 @@ class GbpAccount(proto.Message): listing_count (int): Number of listings under this account. """ + class Type(proto.Enum): r"""The type of the GBP account. @@ -147,10 +146,10 @@ class ListGbpAccountsResponse(proto.Message): def raw_page(self): return self - gbp_accounts: MutableSequence['GbpAccount'] = proto.RepeatedField( + gbp_accounts: MutableSequence["GbpAccount"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='GbpAccount', + message="GbpAccount", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/homepage.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/homepage.py index d83372bb01da..8b7af7906515 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/homepage.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/homepage.py @@ -17,19 +17,17 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'Homepage', - 'GetHomepageRequest', - 'UpdateHomepageRequest', - 'ClaimHomepageRequest', - 'UnclaimHomepageRequest', + "Homepage", + "GetHomepageRequest", + "UpdateHomepageRequest", + "ClaimHomepageRequest", + "UnclaimHomepageRequest", }, ) @@ -109,10 +107,10 @@ class UpdateHomepageRequest(proto.Message): - ``uri`` """ - homepage: 'Homepage' = proto.Field( + homepage: "Homepage" = proto.Field( proto.MESSAGE, number=1, - message='Homepage', + message="Homepage", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/lfpproviders.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/lfpproviders.py index 221b564d97bf..4c367c6950dd 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/lfpproviders.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/lfpproviders.py @@ -17,19 +17,17 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import empty_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'LfpProvider', - 'FindLfpProvidersRequest', - 'FindLfpProvidersResponse', - 'LinkLfpProviderRequest', - 'LinkLfpProviderResponse', + "LfpProvider", + "FindLfpProvidersRequest", + "FindLfpProvidersResponse", + "LinkLfpProviderRequest", + "LinkLfpProviderResponse", }, ) @@ -119,10 +117,10 @@ class FindLfpProvidersResponse(proto.Message): def raw_page(self): return self - lfp_providers: MutableSequence['LfpProvider'] = proto.RepeatedField( + lfp_providers: MutableSequence["LfpProvider"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='LfpProvider', + message="LfpProvider", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py similarity index 89% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py index 85ec2ef18d8e..a2b82b77a865 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/omnichannelsettings.py @@ -17,29 +17,27 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'OmnichannelSetting', - 'ReviewState', - 'InStock', - 'Pickup', - 'LfpLink', - 'OnDisplayToOrder', - 'About', - 'InventoryVerification', - 'GetOmnichannelSettingRequest', - 'ListOmnichannelSettingsRequest', - 'ListOmnichannelSettingsResponse', - 'CreateOmnichannelSettingRequest', - 'UpdateOmnichannelSettingRequest', - 'RequestInventoryVerificationRequest', - 'RequestInventoryVerificationResponse', + "OmnichannelSetting", + "ReviewState", + "InStock", + "Pickup", + "LfpLink", + "OnDisplayToOrder", + "About", + "InventoryVerification", + "GetOmnichannelSettingRequest", + "ListOmnichannelSettingsRequest", + "ListOmnichannelSettingsResponse", + "CreateOmnichannelSettingRequest", + "UpdateOmnichannelSettingRequest", + "RequestInventoryVerificationRequest", + "RequestInventoryVerificationResponse", }, ) @@ -79,6 +77,7 @@ class OmnichannelSetting(proto.Message): Optional. The inventory verification contact and state for this country. """ + class LsfType(proto.Enum): r"""The product page experience type, which is also called the Local Store Front (LSF) type. Check the `HC @@ -119,41 +118,41 @@ class LsfType(proto.Enum): number=12, enum=LsfType, ) - in_stock: 'InStock' = proto.Field( + in_stock: "InStock" = proto.Field( proto.MESSAGE, number=13, - message='InStock', + message="InStock", ) - pickup: 'Pickup' = proto.Field( + pickup: "Pickup" = proto.Field( proto.MESSAGE, number=14, - message='Pickup', + message="Pickup", ) - lfp_link: 'LfpLink' = proto.Field( + lfp_link: "LfpLink" = proto.Field( proto.MESSAGE, number=5, - message='LfpLink', + message="LfpLink", ) - odo: 'OnDisplayToOrder' = proto.Field( + odo: "OnDisplayToOrder" = proto.Field( proto.MESSAGE, number=6, - message='OnDisplayToOrder', + message="OnDisplayToOrder", ) - about: 'About' = proto.Field( + about: "About" = proto.Field( proto.MESSAGE, number=7, - message='About', + message="About", ) - inventory_verification: 'InventoryVerification' = proto.Field( + inventory_verification: "InventoryVerification" = proto.Field( proto.MESSAGE, number=8, - message='InventoryVerification', + message="InventoryVerification", ) class ReviewState(proto.Message): - r"""The state of a omnichannel setting related review process. - """ + r"""The state of a omnichannel setting related review process.""" + class State(proto.Enum): r"""The state of the review process. @@ -197,10 +196,10 @@ class InStock(proto.Message): proto.STRING, number=1, ) - state: 'ReviewState.State' = proto.Field( + state: "ReviewState.State" = proto.Field( proto.ENUM, number=2, - enum='ReviewState.State', + enum="ReviewState.State", ) @@ -221,10 +220,10 @@ class Pickup(proto.Message): proto.STRING, number=1, ) - state: 'ReviewState.State' = proto.Field( + state: "ReviewState.State" = proto.Field( proto.ENUM, number=2, - enum='ReviewState.State', + enum="ReviewState.State", ) @@ -250,10 +249,10 @@ class LfpLink(proto.Message): proto.STRING, number=2, ) - state: 'ReviewState.State' = proto.Field( + state: "ReviewState.State" = proto.Field( proto.ENUM, number=3, - enum='ReviewState.State', + enum="ReviewState.State", ) @@ -273,10 +272,10 @@ class OnDisplayToOrder(proto.Message): proto.STRING, number=1, ) - state: 'ReviewState.State' = proto.Field( + state: "ReviewState.State" = proto.Field( proto.ENUM, number=2, - enum='ReviewState.State', + enum="ReviewState.State", ) @@ -295,10 +294,10 @@ class About(proto.Message): proto.STRING, number=1, ) - state: 'ReviewState.State' = proto.Field( + state: "ReviewState.State" = proto.Field( proto.ENUM, number=2, - enum='ReviewState.State', + enum="ReviewState.State", ) @@ -320,6 +319,7 @@ class InventoryVerification(proto.Message): Output only. The state of the contact verification. """ + class State(proto.Enum): r"""The state of the `inventory verification `__ @@ -366,10 +366,10 @@ class State(proto.Enum): proto.STRING, number=3, ) - contact_state: 'ReviewState.State' = proto.Field( + contact_state: "ReviewState.State" = proto.Field( proto.ENUM, number=4, - enum='ReviewState.State', + enum="ReviewState.State", ) @@ -444,10 +444,10 @@ class ListOmnichannelSettingsResponse(proto.Message): def raw_page(self): return self - omnichannel_settings: MutableSequence['OmnichannelSetting'] = proto.RepeatedField( + omnichannel_settings: MutableSequence["OmnichannelSetting"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='OmnichannelSetting', + message="OmnichannelSetting", ) next_page_token: str = proto.Field( proto.STRING, @@ -470,10 +470,10 @@ class CreateOmnichannelSettingRequest(proto.Message): proto.STRING, number=1, ) - omnichannel_setting: 'OmnichannelSetting' = proto.Field( + omnichannel_setting: "OmnichannelSetting" = proto.Field( proto.MESSAGE, number=2, - message='OmnichannelSetting', + message="OmnichannelSetting", ) @@ -502,10 +502,10 @@ class UpdateOmnichannelSettingRequest(proto.Message): empty/implied update mask is not. """ - omnichannel_setting: 'OmnichannelSetting' = proto.Field( + omnichannel_setting: "OmnichannelSetting" = proto.Field( proto.MESSAGE, number=1, - message='OmnichannelSetting', + message="OmnichannelSetting", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -538,10 +538,10 @@ class RequestInventoryVerificationResponse(proto.Message): The omnichannel setting that was updated. """ - omnichannel_setting: 'OmnichannelSetting' = proto.Field( + omnichannel_setting: "OmnichannelSetting" = proto.Field( proto.MESSAGE, number=1, - message='OmnichannelSetting', + message="OmnichannelSetting", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/online_return_policy.py similarity index 95% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/online_return_policy.py index d5a0f2c452f0..9aefca60e40b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/online_return_policy.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/online_return_policy.py @@ -17,21 +17,19 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.shopping.type.types import types from google.type import date_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'GetOnlineReturnPolicyRequest', - 'CreateOnlineReturnPolicyRequest', - 'DeleteOnlineReturnPolicyRequest', - 'ListOnlineReturnPoliciesRequest', - 'ListOnlineReturnPoliciesResponse', - 'OnlineReturnPolicy', + "GetOnlineReturnPolicyRequest", + "CreateOnlineReturnPolicyRequest", + "DeleteOnlineReturnPolicyRequest", + "ListOnlineReturnPoliciesRequest", + "ListOnlineReturnPoliciesResponse", + "OnlineReturnPolicy", }, ) @@ -66,10 +64,10 @@ class CreateOnlineReturnPolicyRequest(proto.Message): proto.STRING, number=1, ) - online_return_policy: 'OnlineReturnPolicy' = proto.Field( + online_return_policy: "OnlineReturnPolicy" = proto.Field( proto.MESSAGE, number=2, - message='OnlineReturnPolicy', + message="OnlineReturnPolicy", ) @@ -145,10 +143,10 @@ class ListOnlineReturnPoliciesResponse(proto.Message): def raw_page(self): return self - online_return_policies: MutableSequence['OnlineReturnPolicy'] = proto.RepeatedField( + online_return_policies: MutableSequence["OnlineReturnPolicy"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='OnlineReturnPolicy', + message="OnlineReturnPolicy", ) next_page_token: str = proto.Field( proto.STRING, @@ -238,6 +236,7 @@ class OnlineReturnPolicy(proto.Message): This field is a member of `oneof`_ ``_return_label_source``. """ + class ReturnMethod(proto.Enum): r"""The available return methods. @@ -303,6 +302,7 @@ class ReturnShippingFee(proto.Message): shipping fee as free if type is ``FIXED`` and this value is not set. """ + class Type(proto.Enum): r"""Return shipping fee types. @@ -319,10 +319,10 @@ class Type(proto.Enum): FIXED = 1 CUSTOMER_PAYING_ACTUAL_FEE = 2 - type_: 'OnlineReturnPolicy.ReturnShippingFee.Type' = proto.Field( + type_: "OnlineReturnPolicy.ReturnShippingFee.Type" = proto.Field( proto.ENUM, number=1, - enum='OnlineReturnPolicy.ReturnShippingFee.Type', + enum="OnlineReturnPolicy.ReturnShippingFee.Type", ) fixed_fee: types.Price = proto.Field( proto.MESSAGE, @@ -356,13 +356,13 @@ class RestockingFee(proto.Message): fixed_fee: types.Price = proto.Field( proto.MESSAGE, number=1, - oneof='type', + oneof="type", message=types.Price, ) micro_percent: int = proto.Field( proto.INT32, number=2, - oneof='type', + oneof="type", ) class Policy(proto.Message): @@ -377,6 +377,7 @@ class Policy(proto.Message): timestamp. Required for ``NUMBER_OF_DAYS_AFTER_DELIVERY`` returns. """ + class Type(proto.Enum): r"""Return policy types. @@ -396,10 +397,10 @@ class Type(proto.Enum): NO_RETURNS = 2 LIFETIME_RETURNS = 3 - type_: 'OnlineReturnPolicy.Policy.Type' = proto.Field( + type_: "OnlineReturnPolicy.Policy.Type" = proto.Field( proto.ENUM, number=1, - enum='OnlineReturnPolicy.Policy.Type', + enum="OnlineReturnPolicy.Policy.Type", ) days: int = proto.Field( proto.INT64, @@ -442,12 +443,12 @@ class SeasonalOverride(proto.Message): return_days: int = proto.Field( proto.INT32, number=5, - oneof='return_window', + oneof="return_window", ) return_until_date: date_pb2.Date = proto.Field( proto.MESSAGE, number=6, - oneof='return_window', + oneof="return_window", message=date_pb2.Date, ) label: str = proto.Field( diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py index 46605ab3ba80..12fb7b63c125 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/phoneverificationstate.py @@ -19,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'PhoneVerificationState', + "PhoneVerificationState", }, ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/programs.py similarity index 96% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/programs.py index cbe5f7f7f447..ffa6eb3a070e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/programs.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/programs.py @@ -19,16 +19,15 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'Program', - 'GetProgramRequest', - 'ListProgramsRequest', - 'ListProgramsResponse', - 'EnableProgramRequest', - 'DisableProgramRequest', + "Program", + "GetProgramRequest", + "ListProgramsRequest", + "ListProgramsResponse", + "EnableProgramRequest", + "DisableProgramRequest", }, ) @@ -74,6 +73,7 @@ class Program(proto.Message): account has not yet satisfied that are affecting participation in the program. """ + class State(proto.Enum): r"""Possible program participation states for the account. @@ -216,10 +216,10 @@ class ListProgramsResponse(proto.Message): def raw_page(self): return self - programs: MutableSequence['Program'] = proto.RepeatedField( + programs: MutableSequence["Program"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='Program', + message="Program", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/regions.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/regions.py index 64e05a85b688..896b65f59e20 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/regions.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/regions.py @@ -17,22 +17,20 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'GetRegionRequest', - 'CreateRegionRequest', - 'UpdateRegionRequest', - 'DeleteRegionRequest', - 'ListRegionsRequest', - 'ListRegionsResponse', - 'Region', + "GetRegionRequest", + "CreateRegionRequest", + "UpdateRegionRequest", + "DeleteRegionRequest", + "ListRegionsRequest", + "ListRegionsResponse", + "Region", }, ) @@ -74,10 +72,10 @@ class CreateRegionRequest(proto.Message): proto.STRING, number=2, ) - region: 'Region' = proto.Field( + region: "Region" = proto.Field( proto.MESSAGE, number=3, - message='Region', + message="Region", ) @@ -93,10 +91,10 @@ class UpdateRegionRequest(proto.Message): ``"displayName,postalCodeArea.regionCode"``. """ - region: 'Region' = proto.Field( + region: "Region" = proto.Field( proto.MESSAGE, number=1, - message='Region', + message="Region", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -173,10 +171,10 @@ class ListRegionsResponse(proto.Message): def raw_page(self): return self - regions: MutableSequence['Region'] = proto.RepeatedField( + regions: MutableSequence["Region"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='Region', + message="Region", ) next_page_token: str = proto.Field( proto.STRING, @@ -267,10 +265,12 @@ class PostalCodeRange(proto.Message): proto.STRING, number=1, ) - postal_codes: MutableSequence['Region.PostalCodeArea.PostalCodeRange'] = proto.RepeatedField( + postal_codes: MutableSequence[ + "Region.PostalCodeArea.PostalCodeRange" + ] = proto.RepeatedField( proto.MESSAGE, number=2, - message='Region.PostalCodeArea.PostalCodeRange', + message="Region.PostalCodeArea.PostalCodeRange", ) class GeoTargetArea(proto.Message): diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/shippingsettings.py similarity index 92% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/shippingsettings.py index d9428c926229..05b8754b1091 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/shippingsettings.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/shippingsettings.py @@ -17,35 +17,33 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - from google.shopping.type.types import types - +import proto # type: ignore __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'ShippingSettings', - 'Service', - 'Distance', - 'Warehouse', - 'WarehouseCutoffTime', - 'Address', - 'DeliveryTime', - 'CutoffTime', - 'BusinessDayConfig', - 'WarehouseBasedDeliveryTime', - 'RateGroup', - 'Table', - 'TransitTable', - 'MinimumOrderValueTable', - 'Headers', - 'LocationIdSet', - 'Row', - 'Value', - 'CarrierRate', - 'GetShippingSettingsRequest', - 'InsertShippingSettingsRequest', + "ShippingSettings", + "Service", + "Distance", + "Warehouse", + "WarehouseCutoffTime", + "Address", + "DeliveryTime", + "CutoffTime", + "BusinessDayConfig", + "WarehouseBasedDeliveryTime", + "RateGroup", + "Table", + "TransitTable", + "MinimumOrderValueTable", + "Headers", + "LocationIdSet", + "Row", + "Value", + "CarrierRate", + "GetShippingSettingsRequest", + "InsertShippingSettingsRequest", }, ) @@ -97,15 +95,15 @@ class ShippingSettings(proto.Message): proto.STRING, number=1, ) - services: MutableSequence['Service'] = proto.RepeatedField( + services: MutableSequence["Service"] = proto.RepeatedField( proto.MESSAGE, number=2, - message='Service', + message="Service", ) - warehouses: MutableSequence['Warehouse'] = proto.RepeatedField( + warehouses: MutableSequence["Warehouse"] = proto.RepeatedField( proto.MESSAGE, number=3, - message='Warehouse', + message="Warehouse", ) etag: str = proto.Field( proto.STRING, @@ -177,6 +175,7 @@ class Service(proto.Message): Optional. Loyalty programs that this shipping service is limited to. """ + class ShipmentType(proto.Enum): r"""Shipment type of shipping service. @@ -229,6 +228,7 @@ class StoreConfig(proto.Message): This field is a member of `oneof`_ ``_service_radius``. """ + class StoreServiceType(proto.Enum): r"""Indicates whether all stores, or selected stores, listed by the business provide local delivery. @@ -307,11 +307,13 @@ class LocalCutoffTime(proto.Message): optional=True, ) - local_cutoff_time: 'Service.StoreConfig.CutoffConfig.LocalCutoffTime' = proto.Field( - proto.MESSAGE, - number=1, - optional=True, - message='Service.StoreConfig.CutoffConfig.LocalCutoffTime', + local_cutoff_time: "Service.StoreConfig.CutoffConfig.LocalCutoffTime" = ( + proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message="Service.StoreConfig.CutoffConfig.LocalCutoffTime", + ) ) store_close_offset_hours: int = proto.Field( proto.INT64, @@ -324,27 +326,27 @@ class LocalCutoffTime(proto.Message): optional=True, ) - store_service_type: 'Service.StoreConfig.StoreServiceType' = proto.Field( + store_service_type: "Service.StoreConfig.StoreServiceType" = proto.Field( proto.ENUM, number=1, optional=True, - enum='Service.StoreConfig.StoreServiceType', + enum="Service.StoreConfig.StoreServiceType", ) store_codes: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=2, ) - cutoff_config: 'Service.StoreConfig.CutoffConfig' = proto.Field( + cutoff_config: "Service.StoreConfig.CutoffConfig" = proto.Field( proto.MESSAGE, number=3, optional=True, - message='Service.StoreConfig.CutoffConfig', + message="Service.StoreConfig.CutoffConfig", ) - service_radius: 'Distance' = proto.Field( + service_radius: "Distance" = proto.Field( proto.MESSAGE, number=4, optional=True, - message='Distance', + message="Distance", ) class LoyaltyProgram(proto.Message): @@ -395,10 +397,12 @@ class LoyaltyProgramTiers(proto.Message): number=1, optional=True, ) - loyalty_program_tiers: MutableSequence['Service.LoyaltyProgram.LoyaltyProgramTiers'] = proto.RepeatedField( + loyalty_program_tiers: MutableSequence[ + "Service.LoyaltyProgram.LoyaltyProgramTiers" + ] = proto.RepeatedField( proto.MESSAGE, number=2, - message='Service.LoyaltyProgram.LoyaltyProgramTiers', + message="Service.LoyaltyProgram.LoyaltyProgramTiers", ) service_name: str = proto.Field( @@ -420,16 +424,16 @@ class LoyaltyProgramTiers(proto.Message): number=4, optional=True, ) - delivery_time: 'DeliveryTime' = proto.Field( + delivery_time: "DeliveryTime" = proto.Field( proto.MESSAGE, number=5, optional=True, - message='DeliveryTime', + message="DeliveryTime", ) - rate_groups: MutableSequence['RateGroup'] = proto.RepeatedField( + rate_groups: MutableSequence["RateGroup"] = proto.RepeatedField( proto.MESSAGE, number=6, - message='RateGroup', + message="RateGroup", ) shipment_type: ShipmentType = proto.Field( proto.ENUM, @@ -443,11 +447,11 @@ class LoyaltyProgramTiers(proto.Message): optional=True, message=types.Price, ) - minimum_order_value_table: 'MinimumOrderValueTable' = proto.Field( + minimum_order_value_table: "MinimumOrderValueTable" = proto.Field( proto.MESSAGE, number=9, optional=True, - message='MinimumOrderValueTable', + message="MinimumOrderValueTable", ) store_config: StoreConfig = proto.Field( proto.MESSAGE, @@ -480,6 +484,7 @@ class Distance(proto.Message): This field is a member of `oneof`_ ``_unit``. """ + class Unit(proto.Enum): r"""Unit can differ based on country, it is parameterized to include miles and kilometers. @@ -551,28 +556,28 @@ class Warehouse(proto.Message): number=1, optional=True, ) - shipping_address: 'Address' = proto.Field( + shipping_address: "Address" = proto.Field( proto.MESSAGE, number=2, optional=True, - message='Address', + message="Address", ) - cutoff_time: 'WarehouseCutoffTime' = proto.Field( + cutoff_time: "WarehouseCutoffTime" = proto.Field( proto.MESSAGE, number=3, optional=True, - message='WarehouseCutoffTime', + message="WarehouseCutoffTime", ) handling_days: int = proto.Field( proto.INT64, number=4, optional=True, ) - business_day_config: 'BusinessDayConfig' = proto.Field( + business_day_config: "BusinessDayConfig" = proto.Field( proto.MESSAGE, number=5, optional=True, - message='BusinessDayConfig', + message="BusinessDayConfig", ) @@ -757,11 +762,11 @@ class DeliveryTime(proto.Message): number=2, optional=True, ) - cutoff_time: 'CutoffTime' = proto.Field( + cutoff_time: "CutoffTime" = proto.Field( proto.MESSAGE, number=3, optional=True, - message='CutoffTime', + message="CutoffTime", ) min_handling_days: int = proto.Field( proto.INT32, @@ -773,28 +778,30 @@ class DeliveryTime(proto.Message): number=5, optional=True, ) - transit_time_table: 'TransitTable' = proto.Field( + transit_time_table: "TransitTable" = proto.Field( proto.MESSAGE, number=6, optional=True, - message='TransitTable', + message="TransitTable", ) - handling_business_day_config: 'BusinessDayConfig' = proto.Field( + handling_business_day_config: "BusinessDayConfig" = proto.Field( proto.MESSAGE, number=7, optional=True, - message='BusinessDayConfig', + message="BusinessDayConfig", ) - transit_business_day_config: 'BusinessDayConfig' = proto.Field( + transit_business_day_config: "BusinessDayConfig" = proto.Field( proto.MESSAGE, number=8, optional=True, - message='BusinessDayConfig', + message="BusinessDayConfig", ) - warehouse_based_delivery_times: MutableSequence['WarehouseBasedDeliveryTime'] = proto.RepeatedField( + warehouse_based_delivery_times: MutableSequence[ + "WarehouseBasedDeliveryTime" + ] = proto.RepeatedField( proto.MESSAGE, number=9, - message='WarehouseBasedDeliveryTime', + message="WarehouseBasedDeliveryTime", ) @@ -849,6 +856,7 @@ class BusinessDayConfig(proto.Message): Required. Regular business days. May not be empty. """ + class Weekday(proto.Enum): r""" @@ -977,27 +985,27 @@ class RateGroup(proto.Message): proto.STRING, number=1, ) - single_value: 'Value' = proto.Field( + single_value: "Value" = proto.Field( proto.MESSAGE, number=2, optional=True, - message='Value', + message="Value", ) - main_table: 'Table' = proto.Field( + main_table: "Table" = proto.Field( proto.MESSAGE, number=3, optional=True, - message='Table', + message="Table", ) - subtables: MutableSequence['Table'] = proto.RepeatedField( + subtables: MutableSequence["Table"] = proto.RepeatedField( proto.MESSAGE, number=4, - message='Table', + message="Table", ) - carrier_rates: MutableSequence['CarrierRate'] = proto.RepeatedField( + carrier_rates: MutableSequence["CarrierRate"] = proto.RepeatedField( proto.MESSAGE, number=5, - message='CarrierRate', + message="CarrierRate", ) name: str = proto.Field( proto.STRING, @@ -1038,22 +1046,22 @@ class Table(proto.Message): number=1, optional=True, ) - row_headers: 'Headers' = proto.Field( + row_headers: "Headers" = proto.Field( proto.MESSAGE, number=2, optional=True, - message='Headers', + message="Headers", ) - column_headers: 'Headers' = proto.Field( + column_headers: "Headers" = proto.Field( proto.MESSAGE, number=3, optional=True, - message='Headers', + message="Headers", ) - rows: MutableSequence['Row'] = proto.RepeatedField( + rows: MutableSequence["Row"] = proto.RepeatedField( proto.MESSAGE, number=4, - message='Row', + message="Row", ) @@ -1126,10 +1134,12 @@ class TransitTimeValue(proto.Message): optional=True, ) - values: MutableSequence['TransitTable.TransitTimeRow.TransitTimeValue'] = proto.RepeatedField( + values: MutableSequence[ + "TransitTable.TransitTimeRow.TransitTimeValue" + ] = proto.RepeatedField( proto.MESSAGE, number=1, - message='TransitTable.TransitTimeRow.TransitTimeValue', + message="TransitTable.TransitTimeRow.TransitTimeValue", ) postal_code_group_names: MutableSequence[str] = proto.RepeatedField( @@ -1193,7 +1203,9 @@ class StoreCodeSetWithMov(proto.Message): message=types.Price, ) - store_code_set_with_movs: MutableSequence[StoreCodeSetWithMov] = proto.RepeatedField( + store_code_set_with_movs: MutableSequence[ + StoreCodeSetWithMov + ] = proto.RepeatedField( proto.MESSAGE, number=1, message=StoreCodeSetWithMov, @@ -1261,10 +1273,10 @@ class Headers(proto.Message): proto.STRING, number=4, ) - locations: MutableSequence['LocationIdSet'] = proto.RepeatedField( + locations: MutableSequence["LocationIdSet"] = proto.RepeatedField( proto.MESSAGE, number=5, - message='LocationIdSet', + message="LocationIdSet", ) @@ -1297,10 +1309,10 @@ class Row(proto.Message): tables. """ - cells: MutableSequence['Value'] = proto.RepeatedField( + cells: MutableSequence["Value"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='Value', + message="Value", ) @@ -1486,10 +1498,10 @@ class InsertShippingSettingsRequest(proto.Message): proto.STRING, number=1, ) - shipping_setting: 'ShippingSettings' = proto.Field( + shipping_setting: "ShippingSettings" = proto.Field( proto.MESSAGE, number=2, - message='ShippingSettings', + message="ShippingSettings", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofservice.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofservice.py index 4313b1734be3..3f835d500b80 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservice.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofservice.py @@ -19,18 +19,19 @@ import proto # type: ignore -from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind - +from google.shopping.merchant_accounts_v1.types import ( + termsofserviceagreementstate, + termsofservicekind, +) __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'TermsOfService', - 'GetTermsOfServiceRequest', - 'RetrieveLatestTermsOfServiceRequest', - 'AcceptTermsOfServiceRequest', - 'AcceptTermsOfServiceResponse', + "TermsOfService", + "GetTermsOfServiceRequest", + "RetrieveLatestTermsOfServiceRequest", + "AcceptTermsOfServiceRequest", + "AcceptTermsOfServiceResponse", }, ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py index 61cee91adc5a..2f09ec87eeb4 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofserviceagreementstate.py @@ -17,20 +17,19 @@ from typing import MutableMapping, MutableSequence +from google.type import date_pb2 # type: ignore import proto # type: ignore from google.shopping.merchant_accounts_v1.types import termsofservicekind -from google.type import date_pb2 # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'TermsOfServiceAgreementState', - 'Accepted', - 'Required', - 'GetTermsOfServiceAgreementStateRequest', - 'RetrieveForApplicationTermsOfServiceAgreementStateRequest', + "TermsOfServiceAgreementState", + "Accepted", + "Required", + "GetTermsOfServiceAgreementStateRequest", + "RetrieveForApplicationTermsOfServiceAgreementStateRequest", }, ) @@ -105,17 +104,17 @@ class TermsOfServiceAgreementState(proto.Message): number=3, enum=termsofservicekind.TermsOfServiceKind, ) - accepted: 'Accepted' = proto.Field( + accepted: "Accepted" = proto.Field( proto.MESSAGE, number=4, optional=True, - message='Accepted', + message="Accepted", ) - required: 'Required' = proto.Field( + required: "Required" = proto.Field( proto.MESSAGE, number=5, optional=True, - message='Required', + message="Required", ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofservicekind.py similarity index 93% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofservicekind.py index 407306d2393e..843a5e3f3e0d 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/termsofservicekind.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/termsofservicekind.py @@ -19,11 +19,10 @@ import proto # type: ignore - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'TermsOfServiceKind', + "TermsOfServiceKind", }, ) diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/user.py similarity index 94% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py rename to packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/user.py index 6d773870e188..b47409fbf158 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/google/shopping/merchant_accounts_v1/types/user.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1/types/user.py @@ -17,22 +17,21 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import field_mask_pb2 # type: ignore import proto # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore from google.shopping.merchant_accounts_v1.types import accessright - __protobuf__ = proto.module( - package='google.shopping.merchant.accounts.v1', + package="google.shopping.merchant.accounts.v1", manifest={ - 'User', - 'GetUserRequest', - 'CreateUserRequest', - 'DeleteUserRequest', - 'UpdateUserRequest', - 'ListUsersRequest', - 'ListUsersResponse', + "User", + "GetUserRequest", + "CreateUserRequest", + "DeleteUserRequest", + "UpdateUserRequest", + "ListUsersRequest", + "ListUsersResponse", }, ) @@ -58,6 +57,7 @@ class User(proto.Message): rights `__ the user has. """ + class State(proto.Enum): r"""The possible states of a user. @@ -132,10 +132,10 @@ class CreateUserRequest(proto.Message): proto.STRING, number=2, ) - user: 'User' = proto.Field( + user: "User" = proto.Field( proto.MESSAGE, number=3, - message='User', + message="User", ) @@ -176,10 +176,10 @@ class UpdateUserRequest(proto.Message): - ``access_rights`` """ - user: 'User' = proto.Field( + user: "User" = proto.Field( proto.MESSAGE, number=1, - message='User', + message="User", ) update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, @@ -241,10 +241,10 @@ class ListUsersResponse(proto.Message): def raw_page(self): return self - users: MutableSequence['User'] = proto.RepeatedField( + users: MutableSequence["User"] = proto.RepeatedField( proto.MESSAGE, number=1, - message='User', + message="User", ) next_page_token: str = proto.Field( proto.STRING, diff --git a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/gapic_version.py b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/gapic_version.py index 694729f5d88b..20a9cd975b02 100644 --- a/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/gapic_version.py +++ b/packages/google-shopping-merchant-accounts/google/shopping/merchant_accounts_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.5" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_issue_service_list_account_issues_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_get_account_relationship_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_list_account_relationships_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_relationships_service_update_account_relationship_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_approve_account_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_get_account_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_list_account_services_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_propose_account_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_account_services_service_reject_account_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_create_and_configure_account_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_delete_account_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_get_account_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_accounts_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_list_sub_accounts_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_accounts_service_update_account_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_get_autofeed_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_autofeed_settings_service_update_autofeed_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_get_automatic_improvements_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_automatic_improvements_service_update_automatic_improvements_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_get_business_identity_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_identity_service_update_business_identity_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_get_business_info_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_business_info_service_update_business_info_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_create_checkout_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_delete_checkout_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_get_checkout_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_checkout_settings_service_update_checkout_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_get_developer_registration_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_register_gcp_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_developer_registration_service_unregister_gcp_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_get_email_preferences_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_email_preferences_service_update_email_preferences_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_link_gbp_account_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_gbp_accounts_service_list_gbp_accounts_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_claim_homepage_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_get_homepage_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_unclaim_homepage_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_homepage_service_update_homepage_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_find_lfp_providers_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_lfp_providers_service_link_lfp_provider_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_create_omnichannel_setting_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_get_omnichannel_setting_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_list_omnichannel_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_request_inventory_verification_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_omnichannel_settings_service_update_omnichannel_setting_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_create_online_return_policy_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_delete_online_return_policy_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_get_online_return_policy_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_online_return_policy_service_list_online_return_policies_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_disable_program_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_enable_program_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_get_program_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_programs_service_list_programs_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_create_region_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_delete_region_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_get_region_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_list_regions_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_regions_service_update_region_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_get_shipping_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_shipping_settings_service_insert_shipping_settings_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_get_terms_of_service_agreement_state_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_agreement_state_service_retrieve_for_application_terms_of_service_agreement_state_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_accept_terms_of_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_get_terms_of_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_terms_of_service_service_retrieve_latest_terms_of_service_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_create_user_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_delete_user_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_get_user_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_list_users_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_async.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py b/packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py rename to packages/google-shopping-merchant-accounts/samples/generated_samples/merchantapi_v1_generated_user_service_update_user_sync.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json b/packages/google-shopping-merchant-accounts/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json rename to packages/google-shopping-merchant-accounts/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1.json diff --git a/packages/google-shopping-merchant-accounts/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json b/packages/google-shopping-merchant-accounts/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json index 2985c0cae6ea..006404653801 100644 --- a/packages/google-shopping-merchant-accounts/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json +++ b/packages/google-shopping-merchant-accounts/samples/generated_samples/snippet_metadata_google.shopping.merchant.accounts.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-shopping-merchant-accounts", - "version": "0.3.5" + "version": "0.1.0" }, "snippets": [ { diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/scripts/fixup_merchant_accounts_v1_keywords.py b/packages/google-shopping-merchant-accounts/scripts/fixup_merchant_accounts_v1_keywords.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/scripts/fixup_merchant_accounts_v1_keywords.py rename to packages/google-shopping-merchant-accounts/scripts/fixup_merchant_accounts_v1_keywords.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/__init__.py similarity index 100% rename from owl-bot-staging/google-shopping-merchant-accounts/v1beta/google/shopping/merchant_accounts_v1beta/services/__init__.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/__init__.py diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py index 37a6168e8021..eb69e29856bb 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_issue_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_issue_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,45 +22,43 @@ 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.shopping.merchant_accounts_v1.services.account_issue_service import AccountIssueServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.account_issue_service import AccountIssueServiceClient -from google.shopping.merchant_accounts_v1.services.account_issue_service import pagers -from google.shopping.merchant_accounts_v1.services.account_issue_service import transports -from google.shopping.merchant_accounts_v1.types import accountissue -import google.auth - +from google.shopping.merchant_accounts_v1.services.account_issue_service import ( + AccountIssueServiceAsyncClient, + AccountIssueServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import accountissue CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,243 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AccountIssueServiceClient._get_default_mtls_endpoint(None) is None - assert AccountIssueServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountIssueServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AccountIssueServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountIssueServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountIssueServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountIssueServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountIssueServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountIssueServiceClient._read_environment_variables() == (True, "auto", None) + assert AccountIssueServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountIssueServiceClient._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: AccountIssueServiceClient._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 AccountIssueServiceClient._read_environment_variables() == (False, "never", None) + assert AccountIssueServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountIssueServiceClient._read_environment_variables() == (False, "always", None) + assert AccountIssueServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountIssueServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountIssueServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AccountIssueServiceClient._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 AccountIssueServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, False) is None - assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AccountIssueServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + AccountIssueServiceClient._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 ( + AccountIssueServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AccountIssueServiceClient._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 AccountIssueServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountIssueServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +@mock.patch.object( + AccountIssueServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceClient), +) +@mock.patch.object( + AccountIssueServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert AccountIssueServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountIssueServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountIssueServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountIssueServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AccountIssueServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AccountIssueServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountIssueServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + AccountIssueServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountIssueServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AccountIssueServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountIssueServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + AccountIssueServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AccountIssueServiceClient._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." + AccountIssueServiceClient._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 AccountIssueServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountIssueServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountIssueServiceClient._get_universe_domain(None, None) == AccountIssueServiceClient._DEFAULT_UNIVERSE + assert ( + AccountIssueServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AccountIssueServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + AccountIssueServiceClient._get_universe_domain(None, None) + == AccountIssueServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AccountIssueServiceClient._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) @@ -215,7 +368,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") @@ -228,14 +382,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", [ - (AccountIssueServiceClient, "grpc"), - (AccountIssueServiceAsyncClient, "grpc_asyncio"), - (AccountIssueServiceClient, "rest"), -]) -def test_account_issue_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountIssueServiceClient, "grpc"), + (AccountIssueServiceAsyncClient, "grpc_asyncio"), + (AccountIssueServiceClient, "rest"), + ], +) +def test_account_issue_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) @@ -243,52 +405,70 @@ def test_account_issue_service_client_from_service_account_info(client_class, tr 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.AccountIssueServiceGrpcTransport, "grpc"), - (transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountIssueServiceRestTransport, "rest"), -]) -def test_account_issue_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.AccountIssueServiceGrpcTransport, "grpc"), + (transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountIssueServiceRestTransport, "rest"), + ], +) +def test_account_issue_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", [ - (AccountIssueServiceClient, "grpc"), - (AccountIssueServiceAsyncClient, "grpc_asyncio"), - (AccountIssueServiceClient, "rest"), -]) -def test_account_issue_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountIssueServiceClient, "grpc"), + (AccountIssueServiceAsyncClient, "grpc_asyncio"), + (AccountIssueServiceClient, "rest"), + ], +) +def test_account_issue_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" ) @@ -304,30 +484,53 @@ def test_account_issue_service_client_get_transport_class(): assert transport == transports.AccountIssueServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) -def test_account_issue_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AccountIssueServiceClient, + transports.AccountIssueServiceGrpcTransport, + "grpc", + ), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AccountIssueServiceClient, + transports.AccountIssueServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + AccountIssueServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceClient), +) +@mock.patch.object( + AccountIssueServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceAsyncClient), +) +def test_account_issue_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(AccountIssueServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(AccountIssueServiceClient, "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(AccountIssueServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(AccountIssueServiceClient, "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( @@ -345,13 +548,15 @@ def test_account_issue_service_client_client_options(client_class, transport_cla # 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, @@ -363,7 +568,7 @@ def test_account_issue_service_client_client_options(client_class, transport_cla # 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( @@ -383,23 +588,33 @@ def test_account_issue_service_client_client_options(client_class, transport_cla 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", @@ -408,48 +623,102 @@ def test_account_issue_service_client_client_options(client_class, transport_cla 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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "true"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", "false"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "true"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AccountIssueServiceClient, + transports.AccountIssueServiceGrpcTransport, + "grpc", + "true", + ), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AccountIssueServiceClient, + transports.AccountIssueServiceGrpcTransport, + "grpc", + "false", + ), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AccountIssueServiceClient, + transports.AccountIssueServiceRestTransport, + "rest", + "true", + ), + ( + AccountIssueServiceClient, + transports.AccountIssueServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AccountIssueServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceClient), +) +@mock.patch.object( + AccountIssueServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_account_issue_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_account_issue_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 @@ -468,12 +737,22 @@ def test_account_issue_service_client_mtls_env_auto(client_class, transport_clas # 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 @@ -494,15 +773,22 @@ def test_account_issue_service_client_mtls_env_auto(client_class, transport_clas ) # 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, @@ -512,19 +798,31 @@ def test_account_issue_service_client_mtls_env_auto(client_class, transport_clas ) -@pytest.mark.parametrize("client_class", [ - AccountIssueServiceClient, AccountIssueServiceAsyncClient -]) -@mock.patch.object(AccountIssueServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountIssueServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [AccountIssueServiceClient, AccountIssueServiceAsyncClient] +) +@mock.patch.object( + AccountIssueServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountIssueServiceClient), +) +@mock.patch.object( + AccountIssueServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountIssueServiceAsyncClient), +) def test_account_issue_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 @@ -532,8 +830,12 @@ def test_account_issue_service_client_get_mtls_endpoint_and_cert_source(client_c 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 @@ -551,16 +853,28 @@ def test_account_issue_service_client_get_mtls_endpoint_and_cert_source(client_c # 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 @@ -570,34 +884,62 @@ def test_account_issue_service_client_get_mtls_endpoint_and_cert_source(client_c 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", [ - AccountIssueServiceClient, AccountIssueServiceAsyncClient -]) -@mock.patch.object(AccountIssueServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceClient)) -@mock.patch.object(AccountIssueServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountIssueServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [AccountIssueServiceClient, AccountIssueServiceAsyncClient] +) +@mock.patch.object( + AccountIssueServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceClient), +) +@mock.patch.object( + AccountIssueServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountIssueServiceAsyncClient), +) def test_account_issue_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AccountIssueServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AccountIssueServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountIssueServiceClient._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", @@ -620,11 +962,19 @@ def test_account_issue_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. @@ -632,27 +982,48 @@ def test_account_issue_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", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc"), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest"), -]) -def test_account_issue_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AccountIssueServiceClient, + transports.AccountIssueServiceGrpcTransport, + "grpc", + ), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AccountIssueServiceClient, + transports.AccountIssueServiceRestTransport, + "rest", + ), + ], +) +def test_account_issue_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, @@ -661,24 +1032,45 @@ def test_account_issue_service_client_client_options_scopes(client_class, transp api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountIssueServiceClient, transports.AccountIssueServiceRestTransport, "rest", None), -]) -def test_account_issue_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", + [ + ( + AccountIssueServiceClient, + transports.AccountIssueServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AccountIssueServiceClient, + transports.AccountIssueServiceRestTransport, + "rest", + None, + ), + ], +) +def test_account_issue_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, @@ -687,11 +1079,14 @@ def test_account_issue_service_client_client_options_credentials_file(client_cla api_audience=None, ) + def test_account_issue_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AccountIssueServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1101,38 @@ def test_account_issue_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport, "grpc", grpc_helpers), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_account_issue_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", + [ + ( + AccountIssueServiceClient, + transports.AccountIssueServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_account_issue_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, @@ -749,9 +1159,7 @@ def test_account_issue_service_client_create_channel_credentials_file(client_cla 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, @@ -762,11 +1170,14 @@ def test_account_issue_service_client_create_channel_credentials_file(client_cla ) -@pytest.mark.parametrize("request_type", [ - accountissue.ListAccountIssuesRequest, - dict, -]) -def test_list_account_issues(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountissue.ListAccountIssuesRequest, + dict, + ], +) +def test_list_account_issues(request_type, transport: str = "grpc"): client = AccountIssueServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,11 +1189,11 @@ def test_list_account_issues(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_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_account_issues(request) @@ -794,7 +1205,7 @@ def test_list_account_issues(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountIssuesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_account_issues_non_empty_request_with_auto_populated_field(): @@ -802,34 +1213,37 @@ def test_list_account_issues_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountIssueServiceClient( 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 = accountissue.ListAccountIssuesRequest( - parent='parent_value', - page_token='page_token_value', - language_code='language_code_value', - time_zone='time_zone_value', + parent="parent_value", + page_token="page_token_value", + language_code="language_code_value", + time_zone="time_zone_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_account_issues), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_account_issues(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountissue.ListAccountIssuesRequest( - parent='parent_value', - page_token='page_token_value', - language_code='language_code_value', - time_zone='time_zone_value', + parent="parent_value", + page_token="page_token_value", + language_code="language_code_value", + time_zone="time_zone_value", ) + def test_list_account_issues_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -844,12 +1258,18 @@ def test_list_account_issues_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_account_issues in client._transport._wrapped_methods + assert ( + client._transport.list_account_issues in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_account_issues] = 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_account_issues + ] = mock_rpc request = {} client.list_account_issues(request) @@ -862,8 +1282,11 @@ def test_list_account_issues_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_account_issues_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_account_issues_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 +1300,17 @@ async def test_list_account_issues_async_use_cached_wrapped_rpc(transport: str = wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_account_issues in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_account_issues + 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_account_issues] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_account_issues + ] = mock_rpc request = {} await client.list_account_issues(request) @@ -896,8 +1324,11 @@ async def test_list_account_issues_async_use_cached_wrapped_rpc(transport: str = assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_account_issues_async(transport: str = 'grpc_asyncio', request_type=accountissue.ListAccountIssuesRequest): +async def test_list_account_issues_async( + transport: str = "grpc_asyncio", request_type=accountissue.ListAccountIssuesRequest +): client = AccountIssueServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -909,12 +1340,14 @@ async def test_list_account_issues_async(transport: str = 'grpc_asyncio', reques # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountissue.ListAccountIssuesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_account_issues(request) # Establish that the underlying gRPC stub method was called. @@ -925,13 +1358,14 @@ async def test_list_account_issues_async(transport: str = 'grpc_asyncio', reques # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountIssuesAsyncPager) - 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_account_issues_async_from_dict(): await test_list_account_issues_async(request_type=dict) + def test_list_account_issues_field_headers(): client = AccountIssueServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -941,12 +1375,12 @@ def test_list_account_issues_field_headers(): # a field header. Set these to a non-empty value. request = accountissue.ListAccountIssuesRequest() - 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_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: call.return_value = accountissue.ListAccountIssuesResponse() client.list_account_issues(request) @@ -958,9 +1392,9 @@ def test_list_account_issues_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 +1407,15 @@ async def test_list_account_issues_field_headers_async(): # a field header. Set these to a non-empty value. request = accountissue.ListAccountIssuesRequest() - 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_account_issues), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) + type(client.transport.list_account_issues), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountissue.ListAccountIssuesResponse() + ) await client.list_account_issues(request) # Establish that the underlying gRPC stub method was called. @@ -990,9 +1426,9 @@ async def test_list_account_issues_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_account_issues_flattened(): @@ -1002,14 +1438,14 @@ def test_list_account_issues_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountissue.ListAccountIssuesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_account_issues( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1017,7 +1453,7 @@ def test_list_account_issues_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 +1467,10 @@ def test_list_account_issues_flattened_error(): with pytest.raises(ValueError): client.list_account_issues( accountissue.ListAccountIssuesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_account_issues_flattened_async(): client = AccountIssueServiceAsyncClient( @@ -1042,16 +1479,18 @@ async def test_list_account_issues_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountissue.ListAccountIssuesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountissue.ListAccountIssuesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_account_issues( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1059,9 +1498,10 @@ async def test_list_account_issues_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_account_issues_flattened_error_async(): client = AccountIssueServiceAsyncClient( @@ -1073,7 +1513,7 @@ async def test_list_account_issues_flattened_error_async(): with pytest.raises(ValueError): await client.list_account_issues( accountissue.ListAccountIssuesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1085,8 +1525,8 @@ def test_list_account_issues_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_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accountissue.ListAccountIssuesResponse( @@ -1095,17 +1535,17 @@ def test_list_account_issues_pager(transport_name: str = "grpc"): accountissue.AccountIssue(), accountissue.AccountIssue(), ], - next_page_token='abc', + next_page_token="abc", ), accountissue.ListAccountIssuesResponse( account_issues=[], - next_page_token='def', + next_page_token="def", ), accountissue.ListAccountIssuesResponse( account_issues=[ accountissue.AccountIssue(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountissue.ListAccountIssuesResponse( account_issues=[ @@ -1120,9 +1560,7 @@ def test_list_account_issues_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_account_issues(request={}, retry=retry, timeout=timeout) @@ -1132,8 +1570,9 @@ def test_list_account_issues_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accountissue.AccountIssue) - for i in results) + assert all(isinstance(i, accountissue.AccountIssue) for i in results) + + def test_list_account_issues_pages(transport_name: str = "grpc"): client = AccountIssueServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1142,8 +1581,8 @@ def test_list_account_issues_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_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accountissue.ListAccountIssuesResponse( @@ -1152,17 +1591,17 @@ def test_list_account_issues_pages(transport_name: str = "grpc"): accountissue.AccountIssue(), accountissue.AccountIssue(), ], - next_page_token='abc', + next_page_token="abc", ), accountissue.ListAccountIssuesResponse( account_issues=[], - next_page_token='def', + next_page_token="def", ), accountissue.ListAccountIssuesResponse( account_issues=[ accountissue.AccountIssue(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountissue.ListAccountIssuesResponse( account_issues=[ @@ -1173,9 +1612,10 @@ def test_list_account_issues_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_account_issues(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_account_issues_async_pager(): client = AccountIssueServiceAsyncClient( @@ -1184,8 +1624,10 @@ async def test_list_account_issues_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_account_issues), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accountissue.ListAccountIssuesResponse( @@ -1194,17 +1636,17 @@ async def test_list_account_issues_async_pager(): accountissue.AccountIssue(), accountissue.AccountIssue(), ], - next_page_token='abc', + next_page_token="abc", ), accountissue.ListAccountIssuesResponse( account_issues=[], - next_page_token='def', + next_page_token="def", ), accountissue.ListAccountIssuesResponse( account_issues=[ accountissue.AccountIssue(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountissue.ListAccountIssuesResponse( account_issues=[ @@ -1214,15 +1656,16 @@ async def test_list_account_issues_async_pager(): ), RuntimeError, ) - async_pager = await client.list_account_issues(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_account_issues( + 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, accountissue.AccountIssue) - for i in responses) + assert all(isinstance(i, accountissue.AccountIssue) for i in responses) @pytest.mark.asyncio @@ -1233,8 +1676,10 @@ async def test_list_account_issues_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_account_issues), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accountissue.ListAccountIssuesResponse( @@ -1243,17 +1688,17 @@ async def test_list_account_issues_async_pages(): accountissue.AccountIssue(), accountissue.AccountIssue(), ], - next_page_token='abc', + next_page_token="abc", ), accountissue.ListAccountIssuesResponse( account_issues=[], - next_page_token='def', + next_page_token="def", ), accountissue.ListAccountIssuesResponse( account_issues=[ accountissue.AccountIssue(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountissue.ListAccountIssuesResponse( account_issues=[ @@ -1266,11 +1711,11 @@ async def test_list_account_issues_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_account_issues(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 @@ -1288,12 +1733,18 @@ def test_list_account_issues_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_account_issues in client._transport._wrapped_methods + assert ( + client._transport.list_account_issues in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_account_issues] = 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_account_issues + ] = mock_rpc request = {} client.list_account_issues(request) @@ -1308,57 +1759,69 @@ def test_list_account_issues_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_account_issues_rest_required_fields(request_type=accountissue.ListAccountIssuesRequest): +def test_list_account_issues_rest_required_fields( + request_type=accountissue.ListAccountIssuesRequest, +): transport_class = transports.AccountIssueServiceRestTransport 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_account_issues._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_account_issues._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_account_issues._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_account_issues._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("language_code", "page_size", "page_token", "time_zone", )) + assert not set(unset_fields) - set( + ( + "language_code", + "page_size", + "page_token", + "time_zone", + ) + ) 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 = AccountIssueServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountissue.ListAccountIssuesResponse() # Mock the http request 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 @@ -1369,24 +1832,34 @@ def test_list_account_issues_rest_required_fields(request_type=accountissue.List return_value = accountissue.ListAccountIssuesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_account_issues(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_account_issues_rest_unset_required_fields(): - transport = transports.AccountIssueServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountIssueServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_account_issues._get_unset_required_fields({}) - assert set(unset_fields) == (set(("languageCode", "pageSize", "pageToken", "timeZone", )) & set(("parent", ))) + assert set(unset_fields) == ( + set( + ( + "languageCode", + "pageSize", + "pageToken", + "timeZone", + ) + ) + & set(("parent",)) + ) def test_list_account_issues_rest_flattened(): @@ -1396,16 +1869,16 @@ def test_list_account_issues_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 = accountissue.ListAccountIssuesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1415,7 +1888,7 @@ def test_list_account_issues_rest_flattened(): # Convert return value to protobuf type return_value = accountissue.ListAccountIssuesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1425,10 +1898,13 @@ def test_list_account_issues_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/issues" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/issues" % client.transport._host, + args[1], + ) -def test_list_account_issues_rest_flattened_error(transport: str = 'rest'): +def test_list_account_issues_rest_flattened_error(transport: str = "rest"): client = AccountIssueServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1439,20 +1915,20 @@ def test_list_account_issues_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_account_issues( accountissue.ListAccountIssuesRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_account_issues_rest_pager(transport: str = 'rest'): +def test_list_account_issues_rest_pager(transport: str = "rest"): client = AccountIssueServiceClient( 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 = ( accountissue.ListAccountIssuesResponse( @@ -1461,17 +1937,17 @@ def test_list_account_issues_rest_pager(transport: str = 'rest'): accountissue.AccountIssue(), accountissue.AccountIssue(), ], - next_page_token='abc', + next_page_token="abc", ), accountissue.ListAccountIssuesResponse( account_issues=[], - next_page_token='def', + next_page_token="def", ), accountissue.ListAccountIssuesResponse( account_issues=[ accountissue.AccountIssue(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountissue.ListAccountIssuesResponse( account_issues=[ @@ -1484,24 +1960,25 @@ def test_list_account_issues_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(accountissue.ListAccountIssuesResponse.to_json(x) for x in response) + response = tuple( + accountissue.ListAccountIssuesResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_account_issues(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accountissue.AccountIssue) - for i in results) + assert all(isinstance(i, accountissue.AccountIssue) for i in results) pages = list(client.list_account_issues(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 @@ -1543,8 +2020,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AccountIssueServiceClient( - 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. @@ -1566,6 +2042,7 @@ def test_transport_instance(): client = AccountIssueServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AccountIssueServiceGrpcTransport( @@ -1580,18 +2057,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AccountIssueServiceGrpcTransport, - transports.AccountIssueServiceGrpcAsyncIOTransport, - transports.AccountIssueServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + transports.AccountIssueServiceRestTransport, + ], +) 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 = AccountIssueServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1601,8 +2083,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1617,8 +2098,8 @@ def test_list_account_issues_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: call.return_value = accountissue.ListAccountIssuesResponse() client.list_account_issues(request=None) @@ -1639,8 +2120,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = AccountIssueServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1656,12 +2136,14 @@ async def test_list_account_issues_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountissue.ListAccountIssuesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_account_issues(request=None) # Establish that the underlying stub method was called. @@ -1679,20 +2161,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_list_account_issues_rest_bad_request(request_type=accountissue.ListAccountIssuesRequest): +def test_list_account_issues_rest_bad_request( + request_type=accountissue.ListAccountIssuesRequest, +): client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -1701,25 +2186,27 @@ def test_list_account_issues_rest_bad_request(request_type=accountissue.ListAcco client.list_account_issues(request) -@pytest.mark.parametrize("request_type", [ - accountissue.ListAccountIssuesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountissue.ListAccountIssuesRequest, + dict, + ], +) def test_list_account_issues_rest_call_success(request_type): client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accountissue.ListAccountIssuesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -1729,33 +2216,44 @@ def test_list_account_issues_rest_call_success(request_type): # Convert return value to protobuf type return_value = accountissue.ListAccountIssuesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_account_issues(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountIssuesPager) - 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_account_issues_rest_interceptors(null_interceptor): transport = transports.AccountIssueServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountIssueServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountIssueServiceRestInterceptor(), + ) client = AccountIssueServiceClient(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.AccountIssueServiceRestInterceptor, "post_list_account_issues") as post, \ - mock.patch.object(transports.AccountIssueServiceRestInterceptor, "post_list_account_issues_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountIssueServiceRestInterceptor, "pre_list_account_issues") 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.AccountIssueServiceRestInterceptor, "post_list_account_issues" + ) as post, mock.patch.object( + transports.AccountIssueServiceRestInterceptor, + "post_list_account_issues_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountIssueServiceRestInterceptor, "pre_list_account_issues" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountissue.ListAccountIssuesRequest.pb(accountissue.ListAccountIssuesRequest()) + pb_message = accountissue.ListAccountIssuesRequest.pb( + accountissue.ListAccountIssuesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -1766,28 +2264,39 @@ def test_list_account_issues_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 = accountissue.ListAccountIssuesResponse.to_json(accountissue.ListAccountIssuesResponse()) + return_value = accountissue.ListAccountIssuesResponse.to_json( + accountissue.ListAccountIssuesResponse() + ) req.return_value.content = return_value request = accountissue.ListAccountIssuesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = accountissue.ListAccountIssuesResponse() - post_with_metadata.return_value = accountissue.ListAccountIssuesResponse(), metadata + post_with_metadata.return_value = ( + accountissue.ListAccountIssuesResponse(), + metadata, + ) - client.list_account_issues(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_account_issues( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = AccountIssueServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -1802,8 +2311,8 @@ def test_list_account_issues_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_issues), - '__call__') as call: + type(client.transport.list_account_issues), "__call__" + ) as call: client.list_account_issues(request=None) # Establish that the underlying stub method was called. @@ -1824,18 +2333,21 @@ def test_transport_grpc_default(): transports.AccountIssueServiceGrpcTransport, ) + def test_account_issue_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AccountIssueServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_account_issue_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AccountIssueServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -1843,9 +2355,7 @@ def test_account_issue_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. - methods = ( - 'list_account_issues', - ) + methods = ("list_account_issues",) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) @@ -1855,7 +2365,7 @@ def test_account_issue_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -1864,25 +2374,30 @@ def test_account_issue_service_base_transport(): def test_account_issue_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_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport._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_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountIssueServiceTransport( 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_account_issue_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_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.account_issue_service.transports.AccountIssueServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountIssueServiceTransport() @@ -1891,14 +2406,12 @@ def test_account_issue_service_base_transport_with_adc(): def test_account_issue_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) AccountIssueServiceClient() 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, ) @@ -1913,12 +2426,12 @@ def test_account_issue_service_auth_adc(): def test_account_issue_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", ) @@ -1932,48 +2445,45 @@ def test_account_issue_service_transport_auth_adc(transport_class): ], ) def test_account_issue_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.AccountIssueServiceGrpcTransport, grpc_helpers), - (transports.AccountIssueServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.AccountIssueServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_account_issue_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, @@ -1984,9 +2494,15 @@ def test_account_issue_service_transport_create_channel(transport_class, grpc_he ) -@pytest.mark.parametrize("transport_class", [transports.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + ], +) def test_account_issue_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -1996,7 +2512,7 @@ def test_account_issue_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", @@ -2017,61 +2533,77 @@ def test_account_issue_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_account_issue_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.AccountIssueServiceRestTransport ( - 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.AccountIssueServiceRestTransport( + 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_account_issue_service_host_no_port(transport_name): client = AccountIssueServiceClient( 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_account_issue_service_host_with_port(transport_name): client = AccountIssueServiceClient( 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_account_issue_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2086,8 +2618,10 @@ def test_account_issue_service_client_transport_session_collision(transport_name session1 = client1.transport.list_account_issues._session session2 = client2.transport.list_account_issues._session assert session1 != session2 + + def test_account_issue_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.AccountIssueServiceGrpcTransport( @@ -2100,7 +2634,7 @@ def test_account_issue_service_grpc_transport_channel(): def test_account_issue_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.AccountIssueServiceGrpcAsyncIOTransport( @@ -2114,12 +2648,22 @@ def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + ], +) def test_account_issue_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 @@ -2128,7 +2672,7 @@ def test_account_issue_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", @@ -2158,17 +2702,23 @@ def test_account_issue_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.AccountIssueServiceGrpcTransport, transports.AccountIssueServiceGrpcAsyncIOTransport]) -def test_account_issue_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountIssueServiceGrpcTransport, + transports.AccountIssueServiceGrpcAsyncIOTransport, + ], +) +def test_account_issue_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() @@ -2198,7 +2748,9 @@ def test_account_issue_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = AccountIssueServiceClient.account_path(account) assert expected == actual @@ -2213,10 +2765,14 @@ def test_parse_account_path(): actual = AccountIssueServiceClient.parse_account_path(path) assert expected == actual + def test_account_issue_path(): account = "whelk" issue = "octopus" - expected = "accounts/{account}/issues/{issue}".format(account=account, issue=issue, ) + expected = "accounts/{account}/issues/{issue}".format( + account=account, + issue=issue, + ) actual = AccountIssueServiceClient.account_issue_path(account, issue) assert expected == actual @@ -2232,9 +2788,12 @@ def test_parse_account_issue_path(): actual = AccountIssueServiceClient.parse_account_issue_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 = AccountIssueServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2249,9 +2808,12 @@ def test_parse_common_billing_account_path(): actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_folder_path(folder) assert expected == actual @@ -2266,9 +2828,12 @@ def test_parse_common_folder_path(): actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_organization_path(organization) assert expected == actual @@ -2283,9 +2848,12 @@ def test_parse_common_organization_path(): actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_project_path(project) assert expected == actual @@ -2300,10 +2868,14 @@ def test_parse_common_project_path(): actual = AccountIssueServiceClient.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 = AccountIssueServiceClient.common_location_path(project, location) assert expected == actual @@ -2323,14 +2895,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.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountIssueServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AccountIssueServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AccountIssueServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountIssueServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AccountIssueServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2341,10 +2917,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = AccountIssueServiceClient( - 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() @@ -2353,10 +2930,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AccountIssueServiceAsyncClient( - 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() @@ -2364,10 +2942,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AccountIssueServiceClient( - 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() @@ -2375,13 +2954,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AccountIssueServiceClient( - 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: @@ -2390,10 +2968,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport), - (AccountIssueServiceAsyncClient, transports.AccountIssueServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (AccountIssueServiceClient, transports.AccountIssueServiceGrpcTransport), + ( + AccountIssueServiceAsyncClient, + transports.AccountIssueServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2408,7 +2993,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py index 2aa76d82571e..4260ae53b844 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_relationships_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,46 +22,44 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.account_relationships_service import AccountRelationshipsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.account_relationships_service import AccountRelationshipsServiceClient -from google.shopping.merchant_accounts_v1.services.account_relationships_service import pagers -from google.shopping.merchant_accounts_v1.services.account_relationships_service import transports -from google.shopping.merchant_accounts_v1.types import accountrelationships -import google.auth - +from google.shopping.merchant_accounts_v1.services.account_relationships_service import ( + AccountRelationshipsServiceAsyncClient, + AccountRelationshipsServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import accountrelationships CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +74,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(): @@ -85,17 +86,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(): @@ -106,101 +117,253 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(None) is None - assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountRelationshipsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AccountRelationshipsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountRelationshipsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountRelationshipsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountRelationshipsServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + AccountRelationshipsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountRelationshipsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountRelationshipsServiceClient._read_environment_variables() == (True, "auto", None) + assert AccountRelationshipsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountRelationshipsServiceClient._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: AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._read_environment_variables() == (False, "never", None) + assert AccountRelationshipsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "always", None) + assert AccountRelationshipsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountRelationshipsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._get_client_cert_source(None, False) is None - assert AccountRelationshipsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountRelationshipsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AccountRelationshipsServiceClient._get_client_cert_source(None, False) is None + ) + assert ( + AccountRelationshipsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountRelationshipsServiceClient._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 ( + AccountRelationshipsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AccountRelationshipsServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) -@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) -@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) + +@mock.patch.object( + AccountRelationshipsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceClient), +) +@mock.patch.object( + AccountRelationshipsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert AccountRelationshipsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountRelationshipsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountRelationshipsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountRelationshipsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AccountRelationshipsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + AccountRelationshipsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AccountRelationshipsServiceClient._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." + AccountRelationshipsServiceClient._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 AccountRelationshipsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountRelationshipsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountRelationshipsServiceClient._get_universe_domain(None, None) == AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + assert ( + AccountRelationshipsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AccountRelationshipsServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + AccountRelationshipsServiceClient._get_universe_domain(None, None) + == AccountRelationshipsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AccountRelationshipsServiceClient._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) @@ -216,7 +379,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") @@ -229,14 +393,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", [ - (AccountRelationshipsServiceClient, "grpc"), - (AccountRelationshipsServiceAsyncClient, "grpc_asyncio"), - (AccountRelationshipsServiceClient, "rest"), -]) -def test_account_relationships_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountRelationshipsServiceClient, "grpc"), + (AccountRelationshipsServiceAsyncClient, "grpc_asyncio"), + (AccountRelationshipsServiceClient, "rest"), + ], +) +def test_account_relationships_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) @@ -244,52 +416,70 @@ def test_account_relationships_service_client_from_service_account_info(client_c 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.AccountRelationshipsServiceGrpcTransport, "grpc"), - (transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountRelationshipsServiceRestTransport, "rest"), -]) -def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, "grpc"), + (transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountRelationshipsServiceRestTransport, "rest"), + ], +) +def test_account_relationships_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", [ - (AccountRelationshipsServiceClient, "grpc"), - (AccountRelationshipsServiceAsyncClient, "grpc_asyncio"), - (AccountRelationshipsServiceClient, "rest"), -]) -def test_account_relationships_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountRelationshipsServiceClient, "grpc"), + (AccountRelationshipsServiceAsyncClient, "grpc_asyncio"), + (AccountRelationshipsServiceClient, "rest"), + ], +) +def test_account_relationships_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" ) @@ -305,30 +495,57 @@ def test_account_relationships_service_client_get_transport_class(): assert transport == transports.AccountRelationshipsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc"), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) -@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) -def test_account_relationships_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + "grpc", + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + AccountRelationshipsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceClient), +) +@mock.patch.object( + AccountRelationshipsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient), +) +def test_account_relationships_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(AccountRelationshipsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + AccountRelationshipsServiceClient, "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(AccountRelationshipsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + AccountRelationshipsServiceClient, "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( @@ -346,13 +563,15 @@ def test_account_relationships_service_client_client_options(client_class, trans # 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, @@ -364,7 +583,7 @@ def test_account_relationships_service_client_client_options(client_class, trans # 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( @@ -384,23 +603,33 @@ def test_account_relationships_service_client_client_options(client_class, trans 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", @@ -409,48 +638,102 @@ def test_account_relationships_service_client_client_options(client_class, trans 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", [ - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", "true"), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", "false"), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest", "true"), - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) -@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + "grpc", + "true", + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + "grpc", + "false", + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceRestTransport, + "rest", + "true", + ), + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AccountRelationshipsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceClient), +) +@mock.patch.object( + AccountRelationshipsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_account_relationships_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_account_relationships_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 @@ -469,12 +752,22 @@ def test_account_relationships_service_client_mtls_env_auto(client_class, transp # 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 @@ -495,15 +788,22 @@ def test_account_relationships_service_client_mtls_env_auto(client_class, transp ) # 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, @@ -513,19 +813,34 @@ def test_account_relationships_service_client_mtls_env_auto(client_class, transp ) -@pytest.mark.parametrize("client_class", [ - AccountRelationshipsServiceClient, AccountRelationshipsServiceAsyncClient -]) -@mock.patch.object(AccountRelationshipsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountRelationshipsServiceClient)) -@mock.patch.object(AccountRelationshipsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountRelationshipsServiceAsyncClient)) -def test_account_relationships_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [AccountRelationshipsServiceClient, AccountRelationshipsServiceAsyncClient], +) +@mock.patch.object( + AccountRelationshipsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountRelationshipsServiceClient), +) +@mock.patch.object( + AccountRelationshipsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountRelationshipsServiceAsyncClient), +) +def test_account_relationships_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 @@ -533,8 +848,12 @@ def test_account_relationships_service_client_get_mtls_endpoint_and_cert_source( 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 @@ -552,16 +871,28 @@ def test_account_relationships_service_client_get_mtls_endpoint_and_cert_source( # 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 @@ -571,34 +902,65 @@ def test_account_relationships_service_client_get_mtls_endpoint_and_cert_source( 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", [ - AccountRelationshipsServiceClient, AccountRelationshipsServiceAsyncClient -]) -@mock.patch.object(AccountRelationshipsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceClient)) -@mock.patch.object(AccountRelationshipsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [AccountRelationshipsServiceClient, AccountRelationshipsServiceAsyncClient], +) +@mock.patch.object( + AccountRelationshipsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceClient), +) +@mock.patch.object( + AccountRelationshipsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountRelationshipsServiceAsyncClient), +) def test_account_relationships_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AccountRelationshipsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = AccountRelationshipsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountRelationshipsServiceClient._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", @@ -621,11 +983,19 @@ def test_account_relationships_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. @@ -633,27 +1003,48 @@ def test_account_relationships_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", [ - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc"), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest"), -]) -def test_account_relationships_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + "grpc", + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceRestTransport, + "rest", + ), + ], +) +def test_account_relationships_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, @@ -662,24 +1053,45 @@ def test_account_relationships_service_client_client_options_scopes(client_class api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", grpc_helpers), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceRestTransport, "rest", None), -]) -def test_account_relationships_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", + [ + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_account_relationships_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, @@ -688,11 +1100,14 @@ def test_account_relationships_service_client_client_options_credentials_file(cl api_audience=None, ) + def test_account_relationships_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AccountRelationshipsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1122,38 @@ def test_account_relationships_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport, "grpc", grpc_helpers), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_account_relationships_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", + [ + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_account_relationships_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, @@ -750,9 +1180,7 @@ def test_account_relationships_service_client_create_channel_credentials_file(cl 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, @@ -763,11 +1191,14 @@ def test_account_relationships_service_client_create_channel_credentials_file(cl ) -@pytest.mark.parametrize("request_type", [ - accountrelationships.GetAccountRelationshipRequest, - dict, -]) -def test_get_account_relationship(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountrelationships.GetAccountRelationshipRequest, + dict, + ], +) +def test_get_account_relationship(request_type, transport: str = "grpc"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,14 +1210,14 @@ def test_get_account_relationship(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", ) response = client.get_account_relationship(request) @@ -798,10 +1229,10 @@ def test_get_account_relationship(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accountrelationships.AccountRelationship) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' - assert response.account_id_alias == 'account_id_alias_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" + assert response.account_id_alias == "account_id_alias_value" def test_get_account_relationship_non_empty_request_with_auto_populated_field(): @@ -809,28 +1240,31 @@ def test_get_account_relationship_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountRelationshipsServiceClient( 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 = accountrelationships.GetAccountRelationshipRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_account_relationship), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_account_relationship(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountrelationships.GetAccountRelationshipRequest( - name='name_value', + name="name_value", ) + def test_get_account_relationship_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -845,12 +1279,19 @@ def test_get_account_relationship_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_account_relationship in client._transport._wrapped_methods + assert ( + client._transport.get_account_relationship + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account_relationship] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_account_relationship + ] = mock_rpc request = {} client.get_account_relationship(request) @@ -863,8 +1304,11 @@ def test_get_account_relationship_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_account_relationship_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_account_relationship_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: @@ -878,12 +1322,17 @@ async def test_get_account_relationship_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_account_relationship in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_account_relationship + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_account_relationship] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_account_relationship + ] = mock_rpc request = {} await client.get_account_relationship(request) @@ -897,8 +1346,12 @@ async def test_get_account_relationship_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_account_relationship_async(transport: str = 'grpc_asyncio', request_type=accountrelationships.GetAccountRelationshipRequest): +async def test_get_account_relationship_async( + transport: str = "grpc_asyncio", + request_type=accountrelationships.GetAccountRelationshipRequest, +): client = AccountRelationshipsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -910,15 +1363,17 @@ async def test_get_account_relationship_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", + ) + ) response = await client.get_account_relationship(request) # Establish that the underlying gRPC stub method was called. @@ -929,16 +1384,17 @@ async def test_get_account_relationship_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, accountrelationships.AccountRelationship) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' - assert response.account_id_alias == 'account_id_alias_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" + assert response.account_id_alias == "account_id_alias_value" @pytest.mark.asyncio async def test_get_account_relationship_async_from_dict(): await test_get_account_relationship_async(request_type=dict) + def test_get_account_relationship_field_headers(): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -948,12 +1404,12 @@ def test_get_account_relationship_field_headers(): # a field header. Set these to a non-empty value. request = accountrelationships.GetAccountRelationshipRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: call.return_value = accountrelationships.AccountRelationship() client.get_account_relationship(request) @@ -965,9 +1421,9 @@ def test_get_account_relationship_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 @@ -980,13 +1436,15 @@ async def test_get_account_relationship_field_headers_async(): # a field header. Set these to a non-empty value. request = accountrelationships.GetAccountRelationshipRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + type(client.transport.get_account_relationship), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship() + ) await client.get_account_relationship(request) # Establish that the underlying gRPC stub method was called. @@ -997,9 +1455,9 @@ async def test_get_account_relationship_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_account_relationship_flattened(): @@ -1009,14 +1467,14 @@ def test_get_account_relationship_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.AccountRelationship() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_account_relationship( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1024,7 +1482,7 @@ def test_get_account_relationship_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 @@ -1038,9 +1496,10 @@ def test_get_account_relationship_flattened_error(): with pytest.raises(ValueError): client.get_account_relationship( accountrelationships.GetAccountRelationshipRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_account_relationship_flattened_async(): client = AccountRelationshipsServiceAsyncClient( @@ -1049,16 +1508,18 @@ async def test_get_account_relationship_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.AccountRelationship() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_account_relationship( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1066,9 +1527,10 @@ async def test_get_account_relationship_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_account_relationship_flattened_error_async(): client = AccountRelationshipsServiceAsyncClient( @@ -1080,15 +1542,18 @@ async def test_get_account_relationship_flattened_error_async(): with pytest.raises(ValueError): await client.get_account_relationship( accountrelationships.GetAccountRelationshipRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - accountrelationships.UpdateAccountRelationshipRequest, - dict, -]) -def test_update_account_relationship(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountrelationships.UpdateAccountRelationshipRequest, + dict, + ], +) +def test_update_account_relationship(request_type, transport: str = "grpc"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1100,14 +1565,14 @@ def test_update_account_relationship(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", ) response = client.update_account_relationship(request) @@ -1119,10 +1584,10 @@ def test_update_account_relationship(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accountrelationships.AccountRelationship) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' - assert response.account_id_alias == 'account_id_alias_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" + assert response.account_id_alias == "account_id_alias_value" def test_update_account_relationship_non_empty_request_with_auto_populated_field(): @@ -1130,25 +1595,26 @@ def test_update_account_relationship_non_empty_request_with_auto_populated_field # automatically populated, according to AIP-4235, with non-empty requests. client = AccountRelationshipsServiceClient( 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 = accountrelationships.UpdateAccountRelationshipRequest( - ) + request = accountrelationships.UpdateAccountRelationshipRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_account_relationship), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_account_relationship(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == accountrelationships.UpdateAccountRelationshipRequest( - ) + assert args[0] == accountrelationships.UpdateAccountRelationshipRequest() + def test_update_account_relationship_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1164,12 +1630,19 @@ def test_update_account_relationship_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_account_relationship in client._transport._wrapped_methods + assert ( + client._transport.update_account_relationship + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_account_relationship] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_account_relationship + ] = mock_rpc request = {} client.update_account_relationship(request) @@ -1182,8 +1655,11 @@ def test_update_account_relationship_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_account_relationship_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_account_relationship_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: @@ -1197,12 +1673,17 @@ async def test_update_account_relationship_async_use_cached_wrapped_rpc(transpor wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_account_relationship in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_account_relationship + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_account_relationship] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_account_relationship + ] = mock_rpc request = {} await client.update_account_relationship(request) @@ -1216,8 +1697,12 @@ async def test_update_account_relationship_async_use_cached_wrapped_rpc(transpor assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_account_relationship_async(transport: str = 'grpc_asyncio', request_type=accountrelationships.UpdateAccountRelationshipRequest): +async def test_update_account_relationship_async( + transport: str = "grpc_asyncio", + request_type=accountrelationships.UpdateAccountRelationshipRequest, +): client = AccountRelationshipsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1229,15 +1714,17 @@ async def test_update_account_relationship_async(transport: str = 'grpc_asyncio' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", + ) + ) response = await client.update_account_relationship(request) # Establish that the underlying gRPC stub method was called. @@ -1248,16 +1735,17 @@ async def test_update_account_relationship_async(transport: str = 'grpc_asyncio' # Establish that the response is the type that we expect. assert isinstance(response, accountrelationships.AccountRelationship) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' - assert response.account_id_alias == 'account_id_alias_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" + assert response.account_id_alias == "account_id_alias_value" @pytest.mark.asyncio async def test_update_account_relationship_async_from_dict(): await test_update_account_relationship_async(request_type=dict) + def test_update_account_relationship_field_headers(): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1267,12 +1755,12 @@ def test_update_account_relationship_field_headers(): # a field header. Set these to a non-empty value. request = accountrelationships.UpdateAccountRelationshipRequest() - request.account_relationship.name = 'name_value' + request.account_relationship.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: call.return_value = accountrelationships.AccountRelationship() client.update_account_relationship(request) @@ -1284,9 +1772,9 @@ def test_update_account_relationship_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'account_relationship.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "account_relationship.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1299,13 +1787,15 @@ async def test_update_account_relationship_field_headers_async(): # a field header. Set these to a non-empty value. request = accountrelationships.UpdateAccountRelationshipRequest() - request.account_relationship.name = 'name_value' + request.account_relationship.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + type(client.transport.update_account_relationship), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship() + ) await client.update_account_relationship(request) # Establish that the underlying gRPC stub method was called. @@ -1316,9 +1806,9 @@ async def test_update_account_relationship_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'account_relationship.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "account_relationship.name=name_value", + ) in kw["metadata"] def test_update_account_relationship_flattened(): @@ -1328,15 +1818,17 @@ def test_update_account_relationship_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.AccountRelationship() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_account_relationship( - account_relationship=accountrelationships.AccountRelationship(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account_relationship=accountrelationships.AccountRelationship( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1344,10 +1836,10 @@ def test_update_account_relationship_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].account_relationship - mock_val = accountrelationships.AccountRelationship(name='name_value') + mock_val = accountrelationships.AccountRelationship(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1361,10 +1853,13 @@ def test_update_account_relationship_flattened_error(): with pytest.raises(ValueError): client.update_account_relationship( accountrelationships.UpdateAccountRelationshipRequest(), - account_relationship=accountrelationships.AccountRelationship(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account_relationship=accountrelationships.AccountRelationship( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_account_relationship_flattened_async(): client = AccountRelationshipsServiceAsyncClient( @@ -1373,17 +1868,21 @@ async def test_update_account_relationship_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.AccountRelationship() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_account_relationship( - account_relationship=accountrelationships.AccountRelationship(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account_relationship=accountrelationships.AccountRelationship( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1391,12 +1890,13 @@ async def test_update_account_relationship_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].account_relationship - mock_val = accountrelationships.AccountRelationship(name='name_value') + mock_val = accountrelationships.AccountRelationship(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_account_relationship_flattened_error_async(): client = AccountRelationshipsServiceAsyncClient( @@ -1408,16 +1908,21 @@ async def test_update_account_relationship_flattened_error_async(): with pytest.raises(ValueError): await client.update_account_relationship( accountrelationships.UpdateAccountRelationshipRequest(), - account_relationship=accountrelationships.AccountRelationship(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account_relationship=accountrelationships.AccountRelationship( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - accountrelationships.ListAccountRelationshipsRequest, - dict, -]) -def test_list_account_relationships(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountrelationships.ListAccountRelationshipsRequest, + dict, + ], +) +def test_list_account_relationships(request_type, transport: str = "grpc"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1429,11 +1934,11 @@ def test_list_account_relationships(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_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.ListAccountRelationshipsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_account_relationships(request) @@ -1445,7 +1950,7 @@ def test_list_account_relationships(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountRelationshipsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_account_relationships_non_empty_request_with_auto_populated_field(): @@ -1453,30 +1958,33 @@ def test_list_account_relationships_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = AccountRelationshipsServiceClient( 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 = accountrelationships.ListAccountRelationshipsRequest( - 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_account_relationships), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_account_relationships), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_account_relationships(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountrelationships.ListAccountRelationshipsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_account_relationships_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1491,12 +1999,19 @@ def test_list_account_relationships_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_account_relationships in client._transport._wrapped_methods + assert ( + client._transport.list_account_relationships + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_account_relationships] = 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_account_relationships + ] = mock_rpc request = {} client.list_account_relationships(request) @@ -1509,8 +2024,11 @@ def test_list_account_relationships_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_account_relationships_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_account_relationships_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: @@ -1524,12 +2042,17 @@ async def test_list_account_relationships_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_account_relationships in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_account_relationships + 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_account_relationships] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_account_relationships + ] = mock_rpc request = {} await client.list_account_relationships(request) @@ -1543,8 +2066,12 @@ async def test_list_account_relationships_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_account_relationships_async(transport: str = 'grpc_asyncio', request_type=accountrelationships.ListAccountRelationshipsRequest): +async def test_list_account_relationships_async( + transport: str = "grpc_asyncio", + request_type=accountrelationships.ListAccountRelationshipsRequest, +): client = AccountRelationshipsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1556,12 +2083,14 @@ async def test_list_account_relationships_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_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.ListAccountRelationshipsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_account_relationships(request) # Establish that the underlying gRPC stub method was called. @@ -1572,13 +2101,14 @@ async def test_list_account_relationships_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountRelationshipsAsyncPager) - 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_account_relationships_async_from_dict(): await test_list_account_relationships_async(request_type=dict) + def test_list_account_relationships_field_headers(): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1588,12 +2118,12 @@ def test_list_account_relationships_field_headers(): # a field header. Set these to a non-empty value. request = accountrelationships.ListAccountRelationshipsRequest() - 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_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: call.return_value = accountrelationships.ListAccountRelationshipsResponse() client.list_account_relationships(request) @@ -1605,9 +2135,9 @@ def test_list_account_relationships_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 @@ -1620,13 +2150,15 @@ async def test_list_account_relationships_field_headers_async(): # a field header. Set these to a non-empty value. request = accountrelationships.ListAccountRelationshipsRequest() - 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_account_relationships), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse()) + type(client.transport.list_account_relationships), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.ListAccountRelationshipsResponse() + ) await client.list_account_relationships(request) # Establish that the underlying gRPC stub method was called. @@ -1637,9 +2169,9 @@ async def test_list_account_relationships_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_account_relationships_flattened(): @@ -1649,14 +2181,14 @@ def test_list_account_relationships_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.ListAccountRelationshipsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_account_relationships( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1664,7 +2196,7 @@ def test_list_account_relationships_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 @@ -1678,9 +2210,10 @@ def test_list_account_relationships_flattened_error(): with pytest.raises(ValueError): client.list_account_relationships( accountrelationships.ListAccountRelationshipsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_account_relationships_flattened_async(): client = AccountRelationshipsServiceAsyncClient( @@ -1689,16 +2222,18 @@ async def test_list_account_relationships_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountrelationships.ListAccountRelationshipsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.ListAccountRelationshipsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_account_relationships( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1706,9 +2241,10 @@ async def test_list_account_relationships_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_account_relationships_flattened_error_async(): client = AccountRelationshipsServiceAsyncClient( @@ -1720,7 +2256,7 @@ async def test_list_account_relationships_flattened_error_async(): with pytest.raises(ValueError): await client.list_account_relationships( accountrelationships.ListAccountRelationshipsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1732,8 +2268,8 @@ def test_list_account_relationships_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_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accountrelationships.ListAccountRelationshipsResponse( @@ -1742,17 +2278,17 @@ def test_list_account_relationships_pager(transport_name: str = "grpc"): accountrelationships.AccountRelationship(), accountrelationships.AccountRelationship(), ], - next_page_token='abc', + next_page_token="abc", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[], - next_page_token='def', + next_page_token="def", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ accountrelationships.AccountRelationship(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ @@ -1767,11 +2303,11 @@ def test_list_account_relationships_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_account_relationships( + request={}, retry=retry, timeout=timeout ) - pager = client.list_account_relationships(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -1779,8 +2315,11 @@ def test_list_account_relationships_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accountrelationships.AccountRelationship) - for i in results) + assert all( + isinstance(i, accountrelationships.AccountRelationship) for i in results + ) + + def test_list_account_relationships_pages(transport_name: str = "grpc"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1789,8 +2328,8 @@ def test_list_account_relationships_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_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accountrelationships.ListAccountRelationshipsResponse( @@ -1799,17 +2338,17 @@ def test_list_account_relationships_pages(transport_name: str = "grpc"): accountrelationships.AccountRelationship(), accountrelationships.AccountRelationship(), ], - next_page_token='abc', + next_page_token="abc", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[], - next_page_token='def', + next_page_token="def", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ accountrelationships.AccountRelationship(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ @@ -1820,9 +2359,10 @@ def test_list_account_relationships_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_account_relationships(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_account_relationships_async_pager(): client = AccountRelationshipsServiceAsyncClient( @@ -1831,8 +2371,10 @@ async def test_list_account_relationships_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_account_relationships), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accountrelationships.ListAccountRelationshipsResponse( @@ -1841,17 +2383,17 @@ async def test_list_account_relationships_async_pager(): accountrelationships.AccountRelationship(), accountrelationships.AccountRelationship(), ], - next_page_token='abc', + next_page_token="abc", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[], - next_page_token='def', + next_page_token="def", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ accountrelationships.AccountRelationship(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ @@ -1861,15 +2403,18 @@ async def test_list_account_relationships_async_pager(): ), RuntimeError, ) - async_pager = await client.list_account_relationships(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_account_relationships( + 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, accountrelationships.AccountRelationship) - for i in responses) + assert all( + isinstance(i, accountrelationships.AccountRelationship) for i in responses + ) @pytest.mark.asyncio @@ -1880,8 +2425,10 @@ async def test_list_account_relationships_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_account_relationships), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accountrelationships.ListAccountRelationshipsResponse( @@ -1890,17 +2437,17 @@ async def test_list_account_relationships_async_pages(): accountrelationships.AccountRelationship(), accountrelationships.AccountRelationship(), ], - next_page_token='abc', + next_page_token="abc", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[], - next_page_token='def', + next_page_token="def", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ accountrelationships.AccountRelationship(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ @@ -1913,11 +2460,11 @@ async def test_list_account_relationships_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_account_relationships(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 @@ -1935,12 +2482,19 @@ def test_get_account_relationship_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_account_relationship in client._transport._wrapped_methods + assert ( + client._transport.get_account_relationship + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account_relationship] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_account_relationship + ] = mock_rpc request = {} client.get_account_relationship(request) @@ -1955,55 +2509,60 @@ def test_get_account_relationship_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_account_relationship_rest_required_fields(request_type=accountrelationships.GetAccountRelationshipRequest): +def test_get_account_relationship_rest_required_fields( + request_type=accountrelationships.GetAccountRelationshipRequest, +): transport_class = transports.AccountRelationshipsServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_relationship._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account_relationship._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_relationship._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account_relationship._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 = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountrelationships.AccountRelationship() # Mock the http request 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 @@ -2014,24 +2573,24 @@ def test_get_account_relationship_rest_required_fields(request_type=accountrelat return_value = accountrelationships.AccountRelationship.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_account_relationship(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_account_relationship_rest_unset_required_fields(): - transport = transports.AccountRelationshipsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountRelationshipsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_account_relationship._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_account_relationship_rest_flattened(): @@ -2041,16 +2600,16 @@ def test_get_account_relationship_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 = accountrelationships.AccountRelationship() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/relationships/sample2'} + sample_request = {"name": "accounts/sample1/relationships/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2060,7 +2619,7 @@ def test_get_account_relationship_rest_flattened(): # Convert return value to protobuf type return_value = accountrelationships.AccountRelationship.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2070,10 +2629,13 @@ def test_get_account_relationship_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/relationships/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/relationships/*}" % client.transport._host, + args[1], + ) -def test_get_account_relationship_rest_flattened_error(transport: str = 'rest'): +def test_get_account_relationship_rest_flattened_error(transport: str = "rest"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2084,7 +2646,7 @@ def test_get_account_relationship_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_account_relationship( accountrelationships.GetAccountRelationshipRequest(), - name='name_value', + name="name_value", ) @@ -2102,12 +2664,19 @@ def test_update_account_relationship_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_account_relationship in client._transport._wrapped_methods + assert ( + client._transport.update_account_relationship + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_account_relationship] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_account_relationship + ] = mock_rpc request = {} client.update_account_relationship(request) @@ -2122,54 +2691,59 @@ def test_update_account_relationship_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_account_relationship_rest_required_fields(request_type=accountrelationships.UpdateAccountRelationshipRequest): +def test_update_account_relationship_rest_required_fields( + request_type=accountrelationships.UpdateAccountRelationshipRequest, +): transport_class = transports.AccountRelationshipsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_relationship._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_account_relationship._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account_relationship._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_account_relationship._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountrelationships.AccountRelationship() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2179,24 +2753,24 @@ def test_update_account_relationship_rest_required_fields(request_type=accountre return_value = accountrelationships.AccountRelationship.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_account_relationship(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_account_relationship_rest_unset_required_fields(): - transport = transports.AccountRelationshipsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountRelationshipsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_account_relationship._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("accountRelationship", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("accountRelationship",))) def test_update_account_relationship_rest_flattened(): @@ -2206,17 +2780,21 @@ def test_update_account_relationship_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 = accountrelationships.AccountRelationship() # get arguments that satisfy an http rule for this method - sample_request = {'account_relationship': {'name': 'accounts/sample1/relationships/sample2'}} + sample_request = { + "account_relationship": {"name": "accounts/sample1/relationships/sample2"} + } # get truthy value for each flattened field mock_args = dict( - account_relationship=accountrelationships.AccountRelationship(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account_relationship=accountrelationships.AccountRelationship( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -2226,7 +2804,7 @@ def test_update_account_relationship_rest_flattened(): # Convert return value to protobuf type return_value = accountrelationships.AccountRelationship.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2236,10 +2814,14 @@ def test_update_account_relationship_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{account_relationship.name=accounts/*/relationships/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{account_relationship.name=accounts/*/relationships/*}" + % client.transport._host, + args[1], + ) -def test_update_account_relationship_rest_flattened_error(transport: str = 'rest'): +def test_update_account_relationship_rest_flattened_error(transport: str = "rest"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2250,8 +2832,10 @@ def test_update_account_relationship_rest_flattened_error(transport: str = 'rest with pytest.raises(ValueError): client.update_account_relationship( accountrelationships.UpdateAccountRelationshipRequest(), - account_relationship=accountrelationships.AccountRelationship(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account_relationship=accountrelationships.AccountRelationship( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2269,12 +2853,19 @@ def test_list_account_relationships_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_account_relationships in client._transport._wrapped_methods + assert ( + client._transport.list_account_relationships + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_account_relationships] = 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_account_relationships + ] = mock_rpc request = {} client.list_account_relationships(request) @@ -2289,57 +2880,67 @@ def test_list_account_relationships_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_account_relationships_rest_required_fields(request_type=accountrelationships.ListAccountRelationshipsRequest): +def test_list_account_relationships_rest_required_fields( + request_type=accountrelationships.ListAccountRelationshipsRequest, +): transport_class = transports.AccountRelationshipsServiceRestTransport 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_account_relationships._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_account_relationships._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_account_relationships._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_account_relationships._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 = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountrelationships.ListAccountRelationshipsResponse() # Mock the http request 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 @@ -2347,27 +2948,37 @@ def test_list_account_relationships_rest_required_fields(request_type=accountrel response_value.status_code = 200 # Convert return value to protobuf type - return_value = accountrelationships.ListAccountRelationshipsResponse.pb(return_value) + return_value = accountrelationships.ListAccountRelationshipsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_account_relationships(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_account_relationships_rest_unset_required_fields(): - transport = transports.AccountRelationshipsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountRelationshipsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_account_relationships._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_account_relationships_rest_flattened(): @@ -2377,16 +2988,16 @@ def test_list_account_relationships_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 = accountrelationships.ListAccountRelationshipsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -2394,9 +3005,11 @@ def test_list_account_relationships_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = accountrelationships.ListAccountRelationshipsResponse.pb(return_value) + return_value = accountrelationships.ListAccountRelationshipsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2406,10 +3019,13 @@ def test_list_account_relationships_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/relationships" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/relationships" % client.transport._host, + args[1], + ) -def test_list_account_relationships_rest_flattened_error(transport: str = 'rest'): +def test_list_account_relationships_rest_flattened_error(transport: str = "rest"): client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2420,20 +3036,20 @@ def test_list_account_relationships_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.list_account_relationships( accountrelationships.ListAccountRelationshipsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_account_relationships_rest_pager(transport: str = 'rest'): +def test_list_account_relationships_rest_pager(transport: str = "rest"): client = AccountRelationshipsServiceClient( 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 = ( accountrelationships.ListAccountRelationshipsResponse( @@ -2442,17 +3058,17 @@ def test_list_account_relationships_rest_pager(transport: str = 'rest'): accountrelationships.AccountRelationship(), accountrelationships.AccountRelationship(), ], - next_page_token='abc', + next_page_token="abc", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[], - next_page_token='def', + next_page_token="def", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ accountrelationships.AccountRelationship(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountrelationships.ListAccountRelationshipsResponse( account_relationships=[ @@ -2465,24 +3081,28 @@ def test_list_account_relationships_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(accountrelationships.ListAccountRelationshipsResponse.to_json(x) for x in response) + response = tuple( + accountrelationships.ListAccountRelationshipsResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_account_relationships(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accountrelationships.AccountRelationship) - for i in results) + assert all( + isinstance(i, accountrelationships.AccountRelationship) for i in results + ) pages = list(client.list_account_relationships(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 @@ -2524,8 +3144,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AccountRelationshipsServiceClient( - 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. @@ -2547,6 +3166,7 @@ def test_transport_instance(): client = AccountRelationshipsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AccountRelationshipsServiceGrpcTransport( @@ -2561,18 +3181,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AccountRelationshipsServiceGrpcTransport, - transports.AccountRelationshipsServiceGrpcAsyncIOTransport, - transports.AccountRelationshipsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + transports.AccountRelationshipsServiceRestTransport, + ], +) 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 = AccountRelationshipsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2582,8 +3207,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2598,8 +3222,8 @@ def test_get_account_relationship_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: call.return_value = accountrelationships.AccountRelationship() client.get_account_relationship(request=None) @@ -2621,8 +3245,8 @@ def test_update_account_relationship_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: call.return_value = accountrelationships.AccountRelationship() client.update_account_relationship(request=None) @@ -2644,8 +3268,8 @@ def test_list_account_relationships_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: call.return_value = accountrelationships.ListAccountRelationshipsResponse() client.list_account_relationships(request=None) @@ -2658,16 +3282,15 @@ def test_list_account_relationships_empty_call_grpc(): def test_transport_kind_grpc_asyncio(): - transport = AccountRelationshipsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = AccountRelationshipsServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = AccountRelationshipsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2683,15 +3306,17 @@ async def test_get_account_relationship_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", + ) + ) await client.get_account_relationship(request=None) # Establish that the underlying stub method was called. @@ -2713,15 +3338,17 @@ async def test_update_account_relationship_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.AccountRelationship( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", + ) + ) await client.update_account_relationship(request=None) # Establish that the underlying stub method was called. @@ -2743,12 +3370,14 @@ async def test_list_account_relationships_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountrelationships.ListAccountRelationshipsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountrelationships.ListAccountRelationshipsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_account_relationships(request=None) # Establish that the underlying stub method was called. @@ -2766,20 +3395,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_account_relationship_rest_bad_request(request_type=accountrelationships.GetAccountRelationshipRequest): +def test_get_account_relationship_rest_bad_request( + request_type=accountrelationships.GetAccountRelationshipRequest, +): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/relationships/sample2'} + request_init = {"name": "accounts/sample1/relationships/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() @@ -2788,28 +3420,30 @@ def test_get_account_relationship_rest_bad_request(request_type=accountrelations client.get_account_relationship(request) -@pytest.mark.parametrize("request_type", [ - accountrelationships.GetAccountRelationshipRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountrelationships.GetAccountRelationshipRequest, + dict, + ], +) def test_get_account_relationship_rest_call_success(request_type): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/relationships/sample2'} + request_init = {"name": "accounts/sample1/relationships/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 = accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", ) # Wrap the value into a proper Response obj @@ -2819,36 +3453,49 @@ def test_get_account_relationship_rest_call_success(request_type): # Convert return value to protobuf type return_value = accountrelationships.AccountRelationship.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_account_relationship(request) # Establish that the response is the type that we expect. assert isinstance(response, accountrelationships.AccountRelationship) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' - assert response.account_id_alias == 'account_id_alias_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" + assert response.account_id_alias == "account_id_alias_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_account_relationship_rest_interceptors(null_interceptor): transport = transports.AccountRelationshipsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountRelationshipsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountRelationshipsServiceRestInterceptor(), + ) client = AccountRelationshipsServiceClient(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.AccountRelationshipsServiceRestInterceptor, "post_get_account_relationship") as post, \ - mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "post_get_account_relationship_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "pre_get_account_relationship") 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.AccountRelationshipsServiceRestInterceptor, + "post_get_account_relationship", + ) as post, mock.patch.object( + transports.AccountRelationshipsServiceRestInterceptor, + "post_get_account_relationship_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountRelationshipsServiceRestInterceptor, + "pre_get_account_relationship", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountrelationships.GetAccountRelationshipRequest.pb(accountrelationships.GetAccountRelationshipRequest()) + pb_message = accountrelationships.GetAccountRelationshipRequest.pb( + accountrelationships.GetAccountRelationshipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2859,39 +3506,55 @@ def test_get_account_relationship_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 = accountrelationships.AccountRelationship.to_json(accountrelationships.AccountRelationship()) + return_value = accountrelationships.AccountRelationship.to_json( + accountrelationships.AccountRelationship() + ) req.return_value.content = return_value request = accountrelationships.GetAccountRelationshipRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = accountrelationships.AccountRelationship() - post_with_metadata.return_value = accountrelationships.AccountRelationship(), metadata + post_with_metadata.return_value = ( + accountrelationships.AccountRelationship(), + metadata, + ) - client.get_account_relationship(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_account_relationship( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_account_relationship_rest_bad_request(request_type=accountrelationships.UpdateAccountRelationshipRequest): +def test_update_account_relationship_rest_bad_request( + request_type=accountrelationships.UpdateAccountRelationshipRequest, +): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'account_relationship': {'name': 'accounts/sample1/relationships/sample2'}} + request_init = { + "account_relationship": {"name": "accounts/sample1/relationships/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() @@ -2900,25 +3563,36 @@ def test_update_account_relationship_rest_bad_request(request_type=accountrelati client.update_account_relationship(request) -@pytest.mark.parametrize("request_type", [ - accountrelationships.UpdateAccountRelationshipRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountrelationships.UpdateAccountRelationshipRequest, + dict, + ], +) def test_update_account_relationship_rest_call_success(request_type): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'account_relationship': {'name': 'accounts/sample1/relationships/sample2'}} - request_init["account_relationship"] = {'name': 'accounts/sample1/relationships/sample2', 'provider': 'provider_value', 'provider_display_name': 'provider_display_name_value', 'account_id_alias': 'account_id_alias_value'} + request_init = { + "account_relationship": {"name": "accounts/sample1/relationships/sample2"} + } + request_init["account_relationship"] = { + "name": "accounts/sample1/relationships/sample2", + "provider": "provider_value", + "provider_display_name": "provider_display_name_value", + "account_id_alias": "account_id_alias_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 = accountrelationships.UpdateAccountRelationshipRequest.meta.fields["account_relationship"] + test_field = accountrelationships.UpdateAccountRelationshipRequest.meta.fields[ + "account_relationship" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2932,7 +3606,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 @@ -2946,7 +3620,9 @@ 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["account_relationship"].items(): # pragma: NO COVER + for field, value in request_init[ + "account_relationship" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2961,12 +3637,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") @@ -2979,13 +3659,13 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accountrelationships.AccountRelationship( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - account_id_alias='account_id_alias_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + account_id_alias="account_id_alias_value", ) # Wrap the value into a proper Response obj @@ -2995,36 +3675,49 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = accountrelationships.AccountRelationship.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_account_relationship(request) # Establish that the response is the type that we expect. assert isinstance(response, accountrelationships.AccountRelationship) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' - assert response.account_id_alias == 'account_id_alias_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" + assert response.account_id_alias == "account_id_alias_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_account_relationship_rest_interceptors(null_interceptor): transport = transports.AccountRelationshipsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountRelationshipsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountRelationshipsServiceRestInterceptor(), + ) client = AccountRelationshipsServiceClient(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.AccountRelationshipsServiceRestInterceptor, "post_update_account_relationship") as post, \ - mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "post_update_account_relationship_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "pre_update_account_relationship") 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.AccountRelationshipsServiceRestInterceptor, + "post_update_account_relationship", + ) as post, mock.patch.object( + transports.AccountRelationshipsServiceRestInterceptor, + "post_update_account_relationship_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountRelationshipsServiceRestInterceptor, + "pre_update_account_relationship", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountrelationships.UpdateAccountRelationshipRequest.pb(accountrelationships.UpdateAccountRelationshipRequest()) + pb_message = accountrelationships.UpdateAccountRelationshipRequest.pb( + accountrelationships.UpdateAccountRelationshipRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3035,39 +3728,53 @@ def test_update_account_relationship_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 = accountrelationships.AccountRelationship.to_json(accountrelationships.AccountRelationship()) + return_value = accountrelationships.AccountRelationship.to_json( + accountrelationships.AccountRelationship() + ) req.return_value.content = return_value request = accountrelationships.UpdateAccountRelationshipRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = accountrelationships.AccountRelationship() - post_with_metadata.return_value = accountrelationships.AccountRelationship(), metadata + post_with_metadata.return_value = ( + accountrelationships.AccountRelationship(), + metadata, + ) - client.update_account_relationship(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_account_relationship( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_account_relationships_rest_bad_request(request_type=accountrelationships.ListAccountRelationshipsRequest): +def test_list_account_relationships_rest_bad_request( + request_type=accountrelationships.ListAccountRelationshipsRequest, +): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3076,25 +3783,27 @@ def test_list_account_relationships_rest_bad_request(request_type=accountrelatio client.list_account_relationships(request) -@pytest.mark.parametrize("request_type", [ - accountrelationships.ListAccountRelationshipsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountrelationships.ListAccountRelationshipsRequest, + dict, + ], +) def test_list_account_relationships_rest_call_success(request_type): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accountrelationships.ListAccountRelationshipsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -3102,35 +3811,50 @@ def test_list_account_relationships_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = accountrelationships.ListAccountRelationshipsResponse.pb(return_value) + return_value = accountrelationships.ListAccountRelationshipsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_account_relationships(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountRelationshipsPager) - 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_account_relationships_rest_interceptors(null_interceptor): transport = transports.AccountRelationshipsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountRelationshipsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountRelationshipsServiceRestInterceptor(), + ) client = AccountRelationshipsServiceClient(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.AccountRelationshipsServiceRestInterceptor, "post_list_account_relationships") as post, \ - mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "post_list_account_relationships_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountRelationshipsServiceRestInterceptor, "pre_list_account_relationships") 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.AccountRelationshipsServiceRestInterceptor, + "post_list_account_relationships", + ) as post, mock.patch.object( + transports.AccountRelationshipsServiceRestInterceptor, + "post_list_account_relationships_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountRelationshipsServiceRestInterceptor, + "pre_list_account_relationships", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountrelationships.ListAccountRelationshipsRequest.pb(accountrelationships.ListAccountRelationshipsRequest()) + pb_message = accountrelationships.ListAccountRelationshipsRequest.pb( + accountrelationships.ListAccountRelationshipsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3141,28 +3865,39 @@ def test_list_account_relationships_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 = accountrelationships.ListAccountRelationshipsResponse.to_json(accountrelationships.ListAccountRelationshipsResponse()) + return_value = accountrelationships.ListAccountRelationshipsResponse.to_json( + accountrelationships.ListAccountRelationshipsResponse() + ) req.return_value.content = return_value request = accountrelationships.ListAccountRelationshipsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = accountrelationships.ListAccountRelationshipsResponse() - post_with_metadata.return_value = accountrelationships.ListAccountRelationshipsResponse(), metadata + post_with_metadata.return_value = ( + accountrelationships.ListAccountRelationshipsResponse(), + metadata, + ) - client.list_account_relationships(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_account_relationships( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = AccountRelationshipsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -3177,8 +3912,8 @@ def test_get_account_relationship_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_account_relationship), - '__call__') as call: + type(client.transport.get_account_relationship), "__call__" + ) as call: client.get_account_relationship(request=None) # Establish that the underlying stub method was called. @@ -3199,8 +3934,8 @@ def test_update_account_relationship_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_account_relationship), - '__call__') as call: + type(client.transport.update_account_relationship), "__call__" + ) as call: client.update_account_relationship(request=None) # Establish that the underlying stub method was called. @@ -3221,8 +3956,8 @@ def test_list_account_relationships_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_relationships), - '__call__') as call: + type(client.transport.list_account_relationships), "__call__" + ) as call: client.list_account_relationships(request=None) # Establish that the underlying stub method was called. @@ -3243,18 +3978,21 @@ def test_transport_grpc_default(): transports.AccountRelationshipsServiceGrpcTransport, ) + def test_account_relationships_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AccountRelationshipsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_account_relationships_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AccountRelationshipsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3263,9 +4001,9 @@ def test_account_relationships_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_account_relationship', - 'update_account_relationship', - 'list_account_relationships', + "get_account_relationship", + "update_account_relationship", + "list_account_relationships", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3276,7 +4014,7 @@ def test_account_relationships_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3285,25 +4023,30 @@ def test_account_relationships_service_base_transport(): def test_account_relationships_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_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport._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_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountRelationshipsServiceTransport( 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_account_relationships_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_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.account_relationships_service.transports.AccountRelationshipsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountRelationshipsServiceTransport() @@ -3312,14 +4055,12 @@ def test_account_relationships_service_base_transport_with_adc(): def test_account_relationships_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) AccountRelationshipsServiceClient() 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, ) @@ -3334,12 +4075,12 @@ def test_account_relationships_service_auth_adc(): def test_account_relationships_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", ) @@ -3353,48 +4094,50 @@ def test_account_relationships_service_transport_auth_adc(transport_class): ], ) def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, grpc_helpers), - (transports.AccountRelationshipsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ( + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), ], ) -def test_account_relationships_service_transport_create_channel(transport_class, grpc_helpers): +def test_account_relationships_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, @@ -3405,9 +4148,15 @@ def test_account_relationships_service_transport_create_channel(transport_class, ) -@pytest.mark.parametrize("transport_class", [transports.AccountRelationshipsServiceGrpcTransport, transports.AccountRelationshipsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + ], +) def test_account_relationships_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -3417,7 +4166,7 @@ def test_account_relationships_service_grpc_transport_client_cert_source_for_mtl 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", @@ -3438,62 +4187,80 @@ def test_account_relationships_service_grpc_transport_client_cert_source_for_mtl 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_account_relationships_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.AccountRelationshipsServiceRestTransport ( - 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.AccountRelationshipsServiceRestTransport( + 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_account_relationships_service_host_no_port(transport_name): client = AccountRelationshipsServiceClient( 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_account_relationships_service_host_with_port(transport_name): client = AccountRelationshipsServiceClient( 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", -]) -def test_account_relationships_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_account_relationships_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = AccountRelationshipsServiceClient( @@ -3513,8 +4280,10 @@ def test_account_relationships_service_client_transport_session_collision(transp session1 = client1.transport.list_account_relationships._session session2 = client2.transport.list_account_relationships._session assert session1 != session2 + + def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport( @@ -3527,7 +4296,7 @@ def test_account_relationships_service_grpc_transport_channel(): def test_account_relationships_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.AccountRelationshipsServiceGrpcAsyncIOTransport( @@ -3541,12 +4310,22 @@ def test_account_relationships_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.AccountRelationshipsServiceGrpcTransport, transports.AccountRelationshipsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + ], +) def test_account_relationships_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 @@ -3555,7 +4334,7 @@ def test_account_relationships_service_transport_channel_mtls_with_client_cert_s 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", @@ -3585,17 +4364,23 @@ def test_account_relationships_service_transport_channel_mtls_with_client_cert_s # 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.AccountRelationshipsServiceGrpcTransport, transports.AccountRelationshipsServiceGrpcAsyncIOTransport]) -def test_account_relationships_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountRelationshipsServiceGrpcTransport, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + ], +) +def test_account_relationships_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() @@ -3625,7 +4410,9 @@ def test_account_relationships_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = AccountRelationshipsServiceClient.account_path(account) assert expected == actual @@ -3640,11 +4427,17 @@ def test_parse_account_path(): actual = AccountRelationshipsServiceClient.parse_account_path(path) assert expected == actual + def test_account_relationship_path(): account = "whelk" relationship = "octopus" - expected = "accounts/{account}/relationships/{relationship}".format(account=account, relationship=relationship, ) - actual = AccountRelationshipsServiceClient.account_relationship_path(account, relationship) + expected = "accounts/{account}/relationships/{relationship}".format( + account=account, + relationship=relationship, + ) + actual = AccountRelationshipsServiceClient.account_relationship_path( + account, relationship + ) assert expected == actual @@ -3659,10 +4452,15 @@ def test_parse_account_relationship_path(): actual = AccountRelationshipsServiceClient.parse_account_relationship_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AccountRelationshipsServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = AccountRelationshipsServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -3676,9 +4474,12 @@ def test_parse_common_billing_account_path(): actual = AccountRelationshipsServiceClient.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 = AccountRelationshipsServiceClient.common_folder_path(folder) assert expected == actual @@ -3693,9 +4494,12 @@ def test_parse_common_folder_path(): actual = AccountRelationshipsServiceClient.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 = AccountRelationshipsServiceClient.common_organization_path(organization) assert expected == actual @@ -3710,9 +4514,12 @@ def test_parse_common_organization_path(): actual = AccountRelationshipsServiceClient.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 = AccountRelationshipsServiceClient.common_project_path(project) assert expected == actual @@ -3727,10 +4534,14 @@ def test_parse_common_project_path(): actual = AccountRelationshipsServiceClient.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 = AccountRelationshipsServiceClient.common_location_path(project, location) assert expected == actual @@ -3750,14 +4561,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.AccountRelationshipsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountRelationshipsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AccountRelationshipsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AccountRelationshipsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountRelationshipsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AccountRelationshipsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3768,10 +4583,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = AccountRelationshipsServiceClient( - 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() @@ -3780,10 +4596,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AccountRelationshipsServiceAsyncClient( - 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() @@ -3791,10 +4608,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AccountRelationshipsServiceClient( - 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() @@ -3802,13 +4620,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AccountRelationshipsServiceClient( - 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: @@ -3817,10 +4634,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AccountRelationshipsServiceClient, transports.AccountRelationshipsServiceGrpcTransport), - (AccountRelationshipsServiceAsyncClient, transports.AccountRelationshipsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + AccountRelationshipsServiceClient, + transports.AccountRelationshipsServiceGrpcTransport, + ), + ( + AccountRelationshipsServiceAsyncClient, + transports.AccountRelationshipsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3835,7 +4662,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py similarity index 69% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py index 362eb49c06b3..26347289f147 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_account_services_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_account_services_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,45 +22,43 @@ 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.shopping.merchant_accounts_v1.services.account_services_service import AccountServicesServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.account_services_service import AccountServicesServiceClient -from google.shopping.merchant_accounts_v1.services.account_services_service import pagers -from google.shopping.merchant_accounts_v1.services.account_services_service import transports -from google.shopping.merchant_accounts_v1.types import accountservices -import google.auth - +from google.shopping.merchant_accounts_v1.services.account_services_service import ( + AccountServicesServiceAsyncClient, + AccountServicesServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import accountservices CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AccountServicesServiceClient._get_default_mtls_endpoint(None) is None - assert AccountServicesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountServicesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountServicesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountServicesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountServicesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AccountServicesServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountServicesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountServicesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountServicesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountServicesServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert AccountServicesServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountServicesServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountServicesServiceClient._read_environment_variables() == (True, "auto", None) + assert AccountServicesServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountServicesServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountServicesServiceClient._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: AccountServicesServiceClient._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 AccountServicesServiceClient._read_environment_variables() == (False, "never", None) + assert AccountServicesServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountServicesServiceClient._read_environment_variables() == (False, "always", None) + assert AccountServicesServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountServicesServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountServicesServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AccountServicesServiceClient._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 AccountServicesServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AccountServicesServiceClient._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 AccountServicesServiceClient._get_client_cert_source(None, False) is None - assert AccountServicesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountServicesServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AccountServicesServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + AccountServicesServiceClient._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 ( + AccountServicesServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AccountServicesServiceClient._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 AccountServicesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountServicesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) -@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) +@mock.patch.object( + AccountServicesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceClient), +) +@mock.patch.object( + AccountServicesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AccountServicesServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert AccountServicesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountServicesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountServicesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountServicesServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountServicesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountServicesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountServicesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AccountServicesServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AccountServicesServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountServicesServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + AccountServicesServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountServicesServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AccountServicesServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountServicesServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + AccountServicesServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AccountServicesServiceClient._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." + AccountServicesServiceClient._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 AccountServicesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountServicesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountServicesServiceClient._get_universe_domain(None, None) == AccountServicesServiceClient._DEFAULT_UNIVERSE + assert ( + AccountServicesServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AccountServicesServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + AccountServicesServiceClient._get_universe_domain(None, None) + == AccountServicesServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AccountServicesServiceClient._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) @@ -215,7 +370,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") @@ -228,14 +384,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", [ - (AccountServicesServiceClient, "grpc"), - (AccountServicesServiceAsyncClient, "grpc_asyncio"), - (AccountServicesServiceClient, "rest"), -]) -def test_account_services_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountServicesServiceClient, "grpc"), + (AccountServicesServiceAsyncClient, "grpc_asyncio"), + (AccountServicesServiceClient, "rest"), + ], +) +def test_account_services_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) @@ -243,52 +407,70 @@ def test_account_services_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.AccountServicesServiceGrpcTransport, "grpc"), - (transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountServicesServiceRestTransport, "rest"), -]) -def test_account_services_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.AccountServicesServiceGrpcTransport, "grpc"), + (transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountServicesServiceRestTransport, "rest"), + ], +) +def test_account_services_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", [ - (AccountServicesServiceClient, "grpc"), - (AccountServicesServiceAsyncClient, "grpc_asyncio"), - (AccountServicesServiceClient, "rest"), -]) -def test_account_services_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountServicesServiceClient, "grpc"), + (AccountServicesServiceAsyncClient, "grpc_asyncio"), + (AccountServicesServiceClient, "rest"), + ], +) +def test_account_services_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" ) @@ -304,30 +486,53 @@ def test_account_services_service_client_get_transport_class(): assert transport == transports.AccountServicesServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc"), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) -@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) -def test_account_services_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AccountServicesServiceClient, + transports.AccountServicesServiceGrpcTransport, + "grpc", + ), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AccountServicesServiceClient, + transports.AccountServicesServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + AccountServicesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceClient), +) +@mock.patch.object( + AccountServicesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceAsyncClient), +) +def test_account_services_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(AccountServicesServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(AccountServicesServiceClient, "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(AccountServicesServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(AccountServicesServiceClient, "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( @@ -345,13 +550,15 @@ def test_account_services_service_client_client_options(client_class, transport_ # 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, @@ -363,7 +570,7 @@ def test_account_services_service_client_client_options(client_class, transport_ # 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( @@ -383,23 +590,33 @@ def test_account_services_service_client_client_options(client_class, transport_ 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", @@ -408,48 +625,102 @@ def test_account_services_service_client_client_options(client_class, transport_ 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", [ - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", "true"), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", "false"), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest", "true"), - (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) -@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AccountServicesServiceClient, + transports.AccountServicesServiceGrpcTransport, + "grpc", + "true", + ), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AccountServicesServiceClient, + transports.AccountServicesServiceGrpcTransport, + "grpc", + "false", + ), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AccountServicesServiceClient, + transports.AccountServicesServiceRestTransport, + "rest", + "true", + ), + ( + AccountServicesServiceClient, + transports.AccountServicesServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AccountServicesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceClient), +) +@mock.patch.object( + AccountServicesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_account_services_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_account_services_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 @@ -468,12 +739,22 @@ def test_account_services_service_client_mtls_env_auto(client_class, transport_c # 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 @@ -494,15 +775,22 @@ def test_account_services_service_client_mtls_env_auto(client_class, transport_c ) # 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, @@ -512,19 +800,33 @@ def test_account_services_service_client_mtls_env_auto(client_class, transport_c ) -@pytest.mark.parametrize("client_class", [ - AccountServicesServiceClient, AccountServicesServiceAsyncClient -]) -@mock.patch.object(AccountServicesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountServicesServiceClient)) -@mock.patch.object(AccountServicesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountServicesServiceAsyncClient)) -def test_account_services_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [AccountServicesServiceClient, AccountServicesServiceAsyncClient] +) +@mock.patch.object( + AccountServicesServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountServicesServiceClient), +) +@mock.patch.object( + AccountServicesServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountServicesServiceAsyncClient), +) +def test_account_services_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 @@ -532,8 +834,12 @@ def test_account_services_service_client_get_mtls_endpoint_and_cert_source(clien 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 @@ -551,16 +857,28 @@ def test_account_services_service_client_get_mtls_endpoint_and_cert_source(clien # 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 @@ -570,34 +888,62 @@ def test_account_services_service_client_get_mtls_endpoint_and_cert_source(clien 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", [ - AccountServicesServiceClient, AccountServicesServiceAsyncClient -]) -@mock.patch.object(AccountServicesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceClient)) -@mock.patch.object(AccountServicesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountServicesServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [AccountServicesServiceClient, AccountServicesServiceAsyncClient] +) +@mock.patch.object( + AccountServicesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceClient), +) +@mock.patch.object( + AccountServicesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountServicesServiceAsyncClient), +) def test_account_services_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AccountServicesServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AccountServicesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountServicesServiceClient._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", @@ -620,11 +966,19 @@ def test_account_services_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. @@ -632,27 +986,48 @@ def test_account_services_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", [ - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc"), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest"), -]) -def test_account_services_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AccountServicesServiceClient, + transports.AccountServicesServiceGrpcTransport, + "grpc", + ), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AccountServicesServiceClient, + transports.AccountServicesServiceRestTransport, + "rest", + ), + ], +) +def test_account_services_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, @@ -661,24 +1036,45 @@ def test_account_services_service_client_client_options_scopes(client_class, tra api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", grpc_helpers), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountServicesServiceClient, transports.AccountServicesServiceRestTransport, "rest", None), -]) -def test_account_services_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", + [ + ( + AccountServicesServiceClient, + transports.AccountServicesServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AccountServicesServiceClient, + transports.AccountServicesServiceRestTransport, + "rest", + None, + ), + ], +) +def test_account_services_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, @@ -687,11 +1083,14 @@ def test_account_services_service_client_client_options_credentials_file(client_ api_audience=None, ) + def test_account_services_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AccountServicesServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1105,38 @@ def test_account_services_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport, "grpc", grpc_helpers), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_account_services_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", + [ + ( + AccountServicesServiceClient, + transports.AccountServicesServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_account_services_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, @@ -749,9 +1163,7 @@ def test_account_services_service_client_create_channel_credentials_file(client_ 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, @@ -762,11 +1174,14 @@ def test_account_services_service_client_create_channel_credentials_file(client_ ) -@pytest.mark.parametrize("request_type", [ - accountservices.GetAccountServiceRequest, - dict, -]) -def test_get_account_service(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountservices.GetAccountServiceRequest, + dict, + ], +) +def test_get_account_service(request_type, transport: str = "grpc"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,15 +1193,15 @@ def test_get_account_service(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', + external_account_id="external_account_id_value", ) response = client.get_account_service(request) @@ -798,11 +1213,11 @@ def test_get_account_service(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" def test_get_account_service_non_empty_request_with_auto_populated_field(): @@ -810,28 +1225,31 @@ def test_get_account_service_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountServicesServiceClient( 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 = accountservices.GetAccountServiceRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_account_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_account_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountservices.GetAccountServiceRequest( - name='name_value', + name="name_value", ) + def test_get_account_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -846,12 +1264,18 @@ def test_get_account_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_account_service in client._transport._wrapped_methods + assert ( + client._transport.get_account_service in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_account_service + ] = mock_rpc request = {} client.get_account_service(request) @@ -864,8 +1288,11 @@ def test_get_account_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_account_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_account_service_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: @@ -879,12 +1306,17 @@ async def test_get_account_service_async_use_cached_wrapped_rpc(transport: str = wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_account_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_account_service + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_account_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_account_service + ] = mock_rpc request = {} await client.get_account_service(request) @@ -898,8 +1330,12 @@ async def test_get_account_service_async_use_cached_wrapped_rpc(transport: str = assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.GetAccountServiceRequest): +async def test_get_account_service_async( + transport: str = "grpc_asyncio", + request_type=accountservices.GetAccountServiceRequest, +): client = AccountServicesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -911,16 +1347,18 @@ async def test_get_account_service_async(transport: str = 'grpc_asyncio', reques # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", + ) + ) response = await client.get_account_service(request) # Establish that the underlying gRPC stub method was called. @@ -931,17 +1369,18 @@ async def test_get_account_service_async(transport: str = 'grpc_asyncio', reques # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" @pytest.mark.asyncio async def test_get_account_service_async_from_dict(): await test_get_account_service_async(request_type=dict) + def test_get_account_service_field_headers(): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -951,12 +1390,12 @@ def test_get_account_service_field_headers(): # a field header. Set these to a non-empty value. request = accountservices.GetAccountServiceRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: call.return_value = accountservices.AccountService() client.get_account_service(request) @@ -968,9 +1407,9 @@ def test_get_account_service_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 @@ -983,13 +1422,15 @@ async def test_get_account_service_field_headers_async(): # a field header. Set these to a non-empty value. request = accountservices.GetAccountServiceRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + type(client.transport.get_account_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService() + ) await client.get_account_service(request) # Establish that the underlying gRPC stub method was called. @@ -1000,9 +1441,9 @@ async def test_get_account_service_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_account_service_flattened(): @@ -1012,14 +1453,14 @@ def test_get_account_service_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_account_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1027,7 +1468,7 @@ def test_get_account_service_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 @@ -1041,9 +1482,10 @@ def test_get_account_service_flattened_error(): with pytest.raises(ValueError): client.get_account_service( accountservices.GetAccountServiceRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_account_service_flattened_async(): client = AccountServicesServiceAsyncClient( @@ -1052,16 +1494,18 @@ async def test_get_account_service_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_account_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1069,9 +1513,10 @@ async def test_get_account_service_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_account_service_flattened_error_async(): client = AccountServicesServiceAsyncClient( @@ -1083,15 +1528,18 @@ async def test_get_account_service_flattened_error_async(): with pytest.raises(ValueError): await client.get_account_service( accountservices.GetAccountServiceRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - accountservices.ListAccountServicesRequest, - dict, -]) -def test_list_account_services(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountservices.ListAccountServicesRequest, + dict, + ], +) +def test_list_account_services(request_type, transport: str = "grpc"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1103,11 +1551,11 @@ def test_list_account_services(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_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.ListAccountServicesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_account_services(request) @@ -1119,7 +1567,7 @@ def test_list_account_services(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountServicesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_account_services_non_empty_request_with_auto_populated_field(): @@ -1127,30 +1575,33 @@ def test_list_account_services_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountServicesServiceClient( 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 = accountservices.ListAccountServicesRequest( - 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_account_services), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_account_services), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_account_services(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountservices.ListAccountServicesRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_account_services_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1165,12 +1616,19 @@ def test_list_account_services_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_account_services in client._transport._wrapped_methods + assert ( + client._transport.list_account_services + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_account_services] = 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_account_services + ] = mock_rpc request = {} client.list_account_services(request) @@ -1183,8 +1641,11 @@ def test_list_account_services_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_account_services_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_account_services_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: @@ -1198,12 +1659,17 @@ async def test_list_account_services_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_account_services in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_account_services + 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_account_services] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_account_services + ] = mock_rpc request = {} await client.list_account_services(request) @@ -1217,8 +1683,12 @@ async def test_list_account_services_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_account_services_async(transport: str = 'grpc_asyncio', request_type=accountservices.ListAccountServicesRequest): +async def test_list_account_services_async( + transport: str = "grpc_asyncio", + request_type=accountservices.ListAccountServicesRequest, +): client = AccountServicesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1230,12 +1700,14 @@ async def test_list_account_services_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.ListAccountServicesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_account_services(request) # Establish that the underlying gRPC stub method was called. @@ -1246,13 +1718,14 @@ async def test_list_account_services_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountServicesAsyncPager) - 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_account_services_async_from_dict(): await test_list_account_services_async(request_type=dict) + def test_list_account_services_field_headers(): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1262,12 +1735,12 @@ def test_list_account_services_field_headers(): # a field header. Set these to a non-empty value. request = accountservices.ListAccountServicesRequest() - 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_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: call.return_value = accountservices.ListAccountServicesResponse() client.list_account_services(request) @@ -1279,9 +1752,9 @@ def test_list_account_services_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 @@ -1294,13 +1767,15 @@ async def test_list_account_services_field_headers_async(): # a field header. Set these to a non-empty value. request = accountservices.ListAccountServicesRequest() - 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_account_services), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse()) + type(client.transport.list_account_services), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.ListAccountServicesResponse() + ) await client.list_account_services(request) # Establish that the underlying gRPC stub method was called. @@ -1311,9 +1786,9 @@ async def test_list_account_services_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_account_services_flattened(): @@ -1323,14 +1798,14 @@ def test_list_account_services_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.ListAccountServicesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_account_services( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1338,7 +1813,7 @@ def test_list_account_services_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 @@ -1352,9 +1827,10 @@ def test_list_account_services_flattened_error(): with pytest.raises(ValueError): client.list_account_services( accountservices.ListAccountServicesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_account_services_flattened_async(): client = AccountServicesServiceAsyncClient( @@ -1363,16 +1839,18 @@ async def test_list_account_services_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.ListAccountServicesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.ListAccountServicesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_account_services( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1380,9 +1858,10 @@ async def test_list_account_services_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_account_services_flattened_error_async(): client = AccountServicesServiceAsyncClient( @@ -1394,7 +1873,7 @@ async def test_list_account_services_flattened_error_async(): with pytest.raises(ValueError): await client.list_account_services( accountservices.ListAccountServicesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1406,8 +1885,8 @@ def test_list_account_services_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_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accountservices.ListAccountServicesResponse( @@ -1416,17 +1895,17 @@ def test_list_account_services_pager(transport_name: str = "grpc"): accountservices.AccountService(), accountservices.AccountService(), ], - next_page_token='abc', + next_page_token="abc", ), accountservices.ListAccountServicesResponse( account_services=[], - next_page_token='def', + next_page_token="def", ), accountservices.ListAccountServicesResponse( account_services=[ accountservices.AccountService(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountservices.ListAccountServicesResponse( account_services=[ @@ -1441,9 +1920,7 @@ def test_list_account_services_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_account_services(request={}, retry=retry, timeout=timeout) @@ -1453,8 +1930,9 @@ def test_list_account_services_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accountservices.AccountService) - for i in results) + assert all(isinstance(i, accountservices.AccountService) for i in results) + + def test_list_account_services_pages(transport_name: str = "grpc"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1463,8 +1941,8 @@ def test_list_account_services_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_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accountservices.ListAccountServicesResponse( @@ -1473,17 +1951,17 @@ def test_list_account_services_pages(transport_name: str = "grpc"): accountservices.AccountService(), accountservices.AccountService(), ], - next_page_token='abc', + next_page_token="abc", ), accountservices.ListAccountServicesResponse( account_services=[], - next_page_token='def', + next_page_token="def", ), accountservices.ListAccountServicesResponse( account_services=[ accountservices.AccountService(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountservices.ListAccountServicesResponse( account_services=[ @@ -1494,9 +1972,10 @@ def test_list_account_services_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_account_services(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_account_services_async_pager(): client = AccountServicesServiceAsyncClient( @@ -1505,8 +1984,10 @@ async def test_list_account_services_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_account_services), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accountservices.ListAccountServicesResponse( @@ -1515,17 +1996,17 @@ async def test_list_account_services_async_pager(): accountservices.AccountService(), accountservices.AccountService(), ], - next_page_token='abc', + next_page_token="abc", ), accountservices.ListAccountServicesResponse( account_services=[], - next_page_token='def', + next_page_token="def", ), accountservices.ListAccountServicesResponse( account_services=[ accountservices.AccountService(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountservices.ListAccountServicesResponse( account_services=[ @@ -1535,15 +2016,16 @@ async def test_list_account_services_async_pager(): ), RuntimeError, ) - async_pager = await client.list_account_services(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_account_services( + 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, accountservices.AccountService) - for i in responses) + assert all(isinstance(i, accountservices.AccountService) for i in responses) @pytest.mark.asyncio @@ -1554,8 +2036,10 @@ async def test_list_account_services_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_account_services), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accountservices.ListAccountServicesResponse( @@ -1564,17 +2048,17 @@ async def test_list_account_services_async_pages(): accountservices.AccountService(), accountservices.AccountService(), ], - next_page_token='abc', + next_page_token="abc", ), accountservices.ListAccountServicesResponse( account_services=[], - next_page_token='def', + next_page_token="def", ), accountservices.ListAccountServicesResponse( account_services=[ accountservices.AccountService(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountservices.ListAccountServicesResponse( account_services=[ @@ -1587,18 +2071,22 @@ async def test_list_account_services_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_account_services(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", [ - accountservices.ProposeAccountServiceRequest, - dict, -]) -def test_propose_account_service(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + accountservices.ProposeAccountServiceRequest, + dict, + ], +) +def test_propose_account_service(request_type, transport: str = "grpc"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1610,15 +2098,15 @@ def test_propose_account_service(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', + external_account_id="external_account_id_value", ) response = client.propose_account_service(request) @@ -1630,11 +2118,11 @@ def test_propose_account_service(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" def test_propose_account_service_non_empty_request_with_auto_populated_field(): @@ -1642,30 +2130,33 @@ def test_propose_account_service_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountServicesServiceClient( 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 = accountservices.ProposeAccountServiceRequest( - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.propose_account_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.propose_account_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountservices.ProposeAccountServiceRequest( - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", ) + def test_propose_account_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1680,12 +2171,19 @@ def test_propose_account_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.propose_account_service in client._transport._wrapped_methods + assert ( + client._transport.propose_account_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.propose_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.propose_account_service + ] = mock_rpc request = {} client.propose_account_service(request) @@ -1698,8 +2196,11 @@ def test_propose_account_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_propose_account_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_propose_account_service_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: @@ -1713,12 +2214,17 @@ async def test_propose_account_service_async_use_cached_wrapped_rpc(transport: s wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.propose_account_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.propose_account_service + 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.propose_account_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.propose_account_service + ] = mock_rpc request = {} await client.propose_account_service(request) @@ -1732,8 +2238,12 @@ async def test_propose_account_service_async_use_cached_wrapped_rpc(transport: s assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_propose_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.ProposeAccountServiceRequest): +async def test_propose_account_service_async( + transport: str = "grpc_asyncio", + request_type=accountservices.ProposeAccountServiceRequest, +): client = AccountServicesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1745,16 +2255,18 @@ async def test_propose_account_service_async(transport: str = 'grpc_asyncio', re # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", + ) + ) response = await client.propose_account_service(request) # Establish that the underlying gRPC stub method was called. @@ -1765,17 +2277,18 @@ async def test_propose_account_service_async(transport: str = 'grpc_asyncio', re # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" @pytest.mark.asyncio async def test_propose_account_service_async_from_dict(): await test_propose_account_service_async(request_type=dict) + def test_propose_account_service_field_headers(): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1785,12 +2298,12 @@ def test_propose_account_service_field_headers(): # a field header. Set these to a non-empty value. request = accountservices.ProposeAccountServiceRequest() - 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.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: call.return_value = accountservices.AccountService() client.propose_account_service(request) @@ -1802,9 +2315,9 @@ def test_propose_account_service_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 @@ -1817,13 +2330,15 @@ async def test_propose_account_service_field_headers_async(): # a field header. Set these to a non-empty value. request = accountservices.ProposeAccountServiceRequest() - 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.propose_account_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + type(client.transport.propose_account_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService() + ) await client.propose_account_service(request) # Establish that the underlying gRPC stub method was called. @@ -1834,9 +2349,9 @@ async def test_propose_account_service_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_propose_account_service_flattened(): @@ -1846,15 +2361,15 @@ def test_propose_account_service_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.propose_account_service( - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", account_service=accountservices.AccountService(products_management=None), ) @@ -1863,10 +2378,10 @@ def test_propose_account_service_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].provider - mock_val = 'provider_value' + mock_val = "provider_value" assert arg == mock_val arg = args[0].account_service mock_val = accountservices.AccountService(products_management=None) @@ -1883,11 +2398,12 @@ def test_propose_account_service_flattened_error(): with pytest.raises(ValueError): client.propose_account_service( accountservices.ProposeAccountServiceRequest(), - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", account_service=accountservices.AccountService(products_management=None), ) + @pytest.mark.asyncio async def test_propose_account_service_flattened_async(): client = AccountServicesServiceAsyncClient( @@ -1896,17 +2412,19 @@ async def test_propose_account_service_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.propose_account_service( - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", account_service=accountservices.AccountService(products_management=None), ) @@ -1915,15 +2433,16 @@ async def test_propose_account_service_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].provider - mock_val = 'provider_value' + mock_val = "provider_value" assert arg == mock_val arg = args[0].account_service mock_val = accountservices.AccountService(products_management=None) assert arg == mock_val + @pytest.mark.asyncio async def test_propose_account_service_flattened_error_async(): client = AccountServicesServiceAsyncClient( @@ -1935,17 +2454,20 @@ async def test_propose_account_service_flattened_error_async(): with pytest.raises(ValueError): await client.propose_account_service( accountservices.ProposeAccountServiceRequest(), - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", account_service=accountservices.AccountService(products_management=None), ) -@pytest.mark.parametrize("request_type", [ - accountservices.ApproveAccountServiceRequest, - dict, -]) -def test_approve_account_service(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountservices.ApproveAccountServiceRequest, + dict, + ], +) +def test_approve_account_service(request_type, transport: str = "grpc"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1957,15 +2479,15 @@ def test_approve_account_service(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', + external_account_id="external_account_id_value", ) response = client.approve_account_service(request) @@ -1977,11 +2499,11 @@ def test_approve_account_service(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" def test_approve_account_service_non_empty_request_with_auto_populated_field(): @@ -1989,28 +2511,31 @@ def test_approve_account_service_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountServicesServiceClient( 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 = accountservices.ApproveAccountServiceRequest( - 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.approve_account_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.approve_account_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.approve_account_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountservices.ApproveAccountServiceRequest( - name='name_value', + name="name_value", ) + def test_approve_account_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2025,12 +2550,19 @@ def test_approve_account_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.approve_account_service in client._transport._wrapped_methods + assert ( + client._transport.approve_account_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.approve_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.approve_account_service + ] = mock_rpc request = {} client.approve_account_service(request) @@ -2043,8 +2575,11 @@ def test_approve_account_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_approve_account_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_approve_account_service_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: @@ -2058,12 +2593,17 @@ async def test_approve_account_service_async_use_cached_wrapped_rpc(transport: s wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.approve_account_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.approve_account_service + 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.approve_account_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.approve_account_service + ] = mock_rpc request = {} await client.approve_account_service(request) @@ -2077,8 +2617,12 @@ async def test_approve_account_service_async_use_cached_wrapped_rpc(transport: s assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_approve_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.ApproveAccountServiceRequest): +async def test_approve_account_service_async( + transport: str = "grpc_asyncio", + request_type=accountservices.ApproveAccountServiceRequest, +): client = AccountServicesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2090,16 +2634,18 @@ async def test_approve_account_service_async(transport: str = 'grpc_asyncio', re # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", + ) + ) response = await client.approve_account_service(request) # Establish that the underlying gRPC stub method was called. @@ -2110,17 +2656,18 @@ async def test_approve_account_service_async(transport: str = 'grpc_asyncio', re # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" @pytest.mark.asyncio async def test_approve_account_service_async_from_dict(): await test_approve_account_service_async(request_type=dict) + def test_approve_account_service_field_headers(): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2130,12 +2677,12 @@ def test_approve_account_service_field_headers(): # a field header. Set these to a non-empty value. request = accountservices.ApproveAccountServiceRequest() - 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.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: call.return_value = accountservices.AccountService() client.approve_account_service(request) @@ -2147,9 +2694,9 @@ def test_approve_account_service_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 @@ -2162,13 +2709,15 @@ async def test_approve_account_service_field_headers_async(): # a field header. Set these to a non-empty value. request = accountservices.ApproveAccountServiceRequest() - 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.approve_account_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + type(client.transport.approve_account_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService() + ) await client.approve_account_service(request) # Establish that the underlying gRPC stub method was called. @@ -2179,9 +2728,9 @@ async def test_approve_account_service_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_approve_account_service_flattened(): @@ -2191,14 +2740,14 @@ def test_approve_account_service_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.approve_account_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2206,7 +2755,7 @@ def test_approve_account_service_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 @@ -2220,9 +2769,10 @@ def test_approve_account_service_flattened_error(): with pytest.raises(ValueError): client.approve_account_service( accountservices.ApproveAccountServiceRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_approve_account_service_flattened_async(): client = AccountServicesServiceAsyncClient( @@ -2231,16 +2781,18 @@ async def test_approve_account_service_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accountservices.AccountService() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.approve_account_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2248,9 +2800,10 @@ async def test_approve_account_service_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_approve_account_service_flattened_error_async(): client = AccountServicesServiceAsyncClient( @@ -2262,15 +2815,18 @@ async def test_approve_account_service_flattened_error_async(): with pytest.raises(ValueError): await client.approve_account_service( accountservices.ApproveAccountServiceRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - accountservices.RejectAccountServiceRequest, - dict, -]) -def test_reject_account_service(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accountservices.RejectAccountServiceRequest, + dict, + ], +) +def test_reject_account_service(request_type, transport: str = "grpc"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2282,8 +2838,8 @@ def test_reject_account_service(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None response = client.reject_account_service(request) @@ -2303,28 +2859,31 @@ def test_reject_account_service_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountServicesServiceClient( 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 = accountservices.RejectAccountServiceRequest( - 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.reject_account_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.reject_account_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.reject_account_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accountservices.RejectAccountServiceRequest( - name='name_value', + name="name_value", ) + def test_reject_account_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2339,12 +2898,19 @@ def test_reject_account_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.reject_account_service in client._transport._wrapped_methods + assert ( + client._transport.reject_account_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.reject_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.reject_account_service + ] = mock_rpc request = {} client.reject_account_service(request) @@ -2357,8 +2923,11 @@ def test_reject_account_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_reject_account_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_reject_account_service_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: @@ -2372,12 +2941,17 @@ async def test_reject_account_service_async_use_cached_wrapped_rpc(transport: st wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.reject_account_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.reject_account_service + 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.reject_account_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.reject_account_service + ] = mock_rpc request = {} await client.reject_account_service(request) @@ -2391,8 +2965,12 @@ async def test_reject_account_service_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_reject_account_service_async(transport: str = 'grpc_asyncio', request_type=accountservices.RejectAccountServiceRequest): +async def test_reject_account_service_async( + transport: str = "grpc_asyncio", + request_type=accountservices.RejectAccountServiceRequest, +): client = AccountServicesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2404,8 +2982,8 @@ async def test_reject_account_service_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.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.reject_account_service(request) @@ -2424,6 +3002,7 @@ async def test_reject_account_service_async(transport: str = 'grpc_asyncio', req async def test_reject_account_service_async_from_dict(): await test_reject_account_service_async(request_type=dict) + def test_reject_account_service_field_headers(): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2433,12 +3012,12 @@ def test_reject_account_service_field_headers(): # a field header. Set these to a non-empty value. request = accountservices.RejectAccountServiceRequest() - 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.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: call.return_value = None client.reject_account_service(request) @@ -2450,9 +3029,9 @@ def test_reject_account_service_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 @@ -2465,12 +3044,12 @@ async def test_reject_account_service_field_headers_async(): # a field header. Set these to a non-empty value. request = accountservices.RejectAccountServiceRequest() - 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.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.reject_account_service(request) @@ -2482,9 +3061,9 @@ async def test_reject_account_service_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_reject_account_service_flattened(): @@ -2494,14 +3073,14 @@ def test_reject_account_service_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__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.reject_account_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2509,7 +3088,7 @@ def test_reject_account_service_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 @@ -2523,9 +3102,10 @@ def test_reject_account_service_flattened_error(): with pytest.raises(ValueError): client.reject_account_service( accountservices.RejectAccountServiceRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_reject_account_service_flattened_async(): client = AccountServicesServiceAsyncClient( @@ -2534,8 +3114,8 @@ async def test_reject_account_service_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -2543,7 +3123,7 @@ async def test_reject_account_service_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.reject_account_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2551,9 +3131,10 @@ async def test_reject_account_service_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_reject_account_service_flattened_error_async(): client = AccountServicesServiceAsyncClient( @@ -2565,7 +3146,7 @@ async def test_reject_account_service_flattened_error_async(): with pytest.raises(ValueError): await client.reject_account_service( accountservices.RejectAccountServiceRequest(), - name='name_value', + name="name_value", ) @@ -2583,12 +3164,18 @@ def test_get_account_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_account_service in client._transport._wrapped_methods + assert ( + client._transport.get_account_service in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_account_service + ] = mock_rpc request = {} client.get_account_service(request) @@ -2603,55 +3190,60 @@ def test_get_account_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_account_service_rest_required_fields(request_type=accountservices.GetAccountServiceRequest): +def test_get_account_service_rest_required_fields( + request_type=accountservices.GetAccountServiceRequest, +): transport_class = transports.AccountServicesServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account_service._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account_service._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 = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountservices.AccountService() # Mock the http request 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 @@ -2662,24 +3254,24 @@ def test_get_account_service_rest_required_fields(request_type=accountservices.G return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_account_service(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_account_service_rest_unset_required_fields(): - transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_account_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_account_service_rest_flattened(): @@ -2689,16 +3281,16 @@ def test_get_account_service_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 = accountservices.AccountService() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/services/sample2'} + sample_request = {"name": "accounts/sample1/services/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2708,7 +3300,7 @@ def test_get_account_service_rest_flattened(): # Convert return value to protobuf type return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2718,10 +3310,13 @@ def test_get_account_service_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/services/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/services/*}" % client.transport._host, + args[1], + ) -def test_get_account_service_rest_flattened_error(transport: str = 'rest'): +def test_get_account_service_rest_flattened_error(transport: str = "rest"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2732,7 +3327,7 @@ def test_get_account_service_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_account_service( accountservices.GetAccountServiceRequest(), - name='name_value', + name="name_value", ) @@ -2750,12 +3345,19 @@ def test_list_account_services_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_account_services in client._transport._wrapped_methods + assert ( + client._transport.list_account_services + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_account_services] = 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_account_services + ] = mock_rpc request = {} client.list_account_services(request) @@ -2770,57 +3372,67 @@ def test_list_account_services_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_account_services_rest_required_fields(request_type=accountservices.ListAccountServicesRequest): +def test_list_account_services_rest_required_fields( + request_type=accountservices.ListAccountServicesRequest, +): transport_class = transports.AccountServicesServiceRestTransport 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_account_services._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_account_services._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_account_services._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_account_services._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 = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountservices.ListAccountServicesResponse() # Mock the http request 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 @@ -2831,24 +3443,32 @@ def test_list_account_services_rest_required_fields(request_type=accountservices return_value = accountservices.ListAccountServicesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_account_services(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_account_services_rest_unset_required_fields(): - transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_account_services._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_account_services_rest_flattened(): @@ -2858,16 +3478,16 @@ def test_list_account_services_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 = accountservices.ListAccountServicesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -2877,7 +3497,7 @@ def test_list_account_services_rest_flattened(): # Convert return value to protobuf type return_value = accountservices.ListAccountServicesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2887,10 +3507,13 @@ def test_list_account_services_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/services" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/services" % client.transport._host, + args[1], + ) -def test_list_account_services_rest_flattened_error(transport: str = 'rest'): +def test_list_account_services_rest_flattened_error(transport: str = "rest"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2901,20 +3524,20 @@ def test_list_account_services_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_account_services( accountservices.ListAccountServicesRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_account_services_rest_pager(transport: str = 'rest'): +def test_list_account_services_rest_pager(transport: str = "rest"): client = AccountServicesServiceClient( 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 = ( accountservices.ListAccountServicesResponse( @@ -2923,17 +3546,17 @@ def test_list_account_services_rest_pager(transport: str = 'rest'): accountservices.AccountService(), accountservices.AccountService(), ], - next_page_token='abc', + next_page_token="abc", ), accountservices.ListAccountServicesResponse( account_services=[], - next_page_token='def', + next_page_token="def", ), accountservices.ListAccountServicesResponse( account_services=[ accountservices.AccountService(), ], - next_page_token='ghi', + next_page_token="ghi", ), accountservices.ListAccountServicesResponse( account_services=[ @@ -2946,24 +3569,25 @@ def test_list_account_services_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(accountservices.ListAccountServicesResponse.to_json(x) for x in response) + response = tuple( + accountservices.ListAccountServicesResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_account_services(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accountservices.AccountService) - for i in results) + assert all(isinstance(i, accountservices.AccountService) for i in results) pages = list(client.list_account_services(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 @@ -2981,12 +3605,19 @@ def test_propose_account_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.propose_account_service in client._transport._wrapped_methods + assert ( + client._transport.propose_account_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.propose_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.propose_account_service + ] = mock_rpc request = {} client.propose_account_service(request) @@ -3001,7 +3632,9 @@ def test_propose_account_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_propose_account_service_rest_required_fields(request_type=accountservices.ProposeAccountServiceRequest): +def test_propose_account_service_rest_required_fields( + request_type=accountservices.ProposeAccountServiceRequest, +): transport_class = transports.AccountServicesServiceRestTransport request_init = {} @@ -3009,53 +3642,56 @@ def test_propose_account_service_rest_required_fields(request_type=accountservic request_init["provider"] = "" 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()).propose_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).propose_account_service._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["provider"] = 'provider_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["provider"] = "provider_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).propose_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).propose_account_service._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" assert "provider" in jsonified_request - assert jsonified_request["provider"] == 'provider_value' + assert jsonified_request["provider"] == "provider_value" client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountservices.AccountService() # Mock the http request 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() @@ -3065,24 +3701,33 @@ def test_propose_account_service_rest_required_fields(request_type=accountservic return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.propose_account_service(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_propose_account_service_rest_unset_required_fields(): - transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.propose_account_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "provider", "accountService", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "provider", + "accountService", + ) + ) + ) def test_propose_account_service_rest_flattened(): @@ -3092,17 +3737,17 @@ def test_propose_account_service_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 = accountservices.AccountService() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", account_service=accountservices.AccountService(products_management=None), ) mock_args.update(sample_request) @@ -3113,7 +3758,7 @@ def test_propose_account_service_rest_flattened(): # Convert return value to protobuf type return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3123,10 +3768,14 @@ def test_propose_account_service_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/services:propose" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/services:propose" + % client.transport._host, + args[1], + ) -def test_propose_account_service_rest_flattened_error(transport: str = 'rest'): +def test_propose_account_service_rest_flattened_error(transport: str = "rest"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3137,8 +3786,8 @@ def test_propose_account_service_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.propose_account_service( accountservices.ProposeAccountServiceRequest(), - parent='parent_value', - provider='provider_value', + parent="parent_value", + provider="provider_value", account_service=accountservices.AccountService(products_management=None), ) @@ -3157,12 +3806,19 @@ def test_approve_account_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.approve_account_service in client._transport._wrapped_methods + assert ( + client._transport.approve_account_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.approve_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.approve_account_service + ] = mock_rpc request = {} client.approve_account_service(request) @@ -3177,57 +3833,62 @@ def test_approve_account_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_approve_account_service_rest_required_fields(request_type=accountservices.ApproveAccountServiceRequest): +def test_approve_account_service_rest_required_fields( + request_type=accountservices.ApproveAccountServiceRequest, +): transport_class = transports.AccountServicesServiceRestTransport 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()).approve_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).approve_account_service._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()).approve_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).approve_account_service._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 = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accountservices.AccountService() # Mock the http request 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() @@ -3237,24 +3898,24 @@ def test_approve_account_service_rest_required_fields(request_type=accountservic return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.approve_account_service(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_approve_account_service_rest_unset_required_fields(): - transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.approve_account_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_approve_account_service_rest_flattened(): @@ -3264,16 +3925,16 @@ def test_approve_account_service_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 = accountservices.AccountService() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/services/sample2'} + sample_request = {"name": "accounts/sample1/services/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -3283,7 +3944,7 @@ def test_approve_account_service_rest_flattened(): # Convert return value to protobuf type return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3293,10 +3954,14 @@ def test_approve_account_service_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/services/*}:approve" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/services/*}:approve" + % client.transport._host, + args[1], + ) -def test_approve_account_service_rest_flattened_error(transport: str = 'rest'): +def test_approve_account_service_rest_flattened_error(transport: str = "rest"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3307,7 +3972,7 @@ def test_approve_account_service_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.approve_account_service( accountservices.ApproveAccountServiceRequest(), - name='name_value', + name="name_value", ) @@ -3325,12 +3990,19 @@ def test_reject_account_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.reject_account_service in client._transport._wrapped_methods + assert ( + client._transport.reject_account_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.reject_account_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.reject_account_service + ] = mock_rpc request = {} client.reject_account_service(request) @@ -3345,81 +4017,86 @@ def test_reject_account_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_reject_account_service_rest_required_fields(request_type=accountservices.RejectAccountServiceRequest): +def test_reject_account_service_rest_required_fields( + request_type=accountservices.RejectAccountServiceRequest, +): transport_class = transports.AccountServicesServiceRestTransport 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()).reject_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reject_account_service._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()).reject_account_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reject_account_service._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 = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = '' + json_return_value = "" - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.reject_account_service(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_reject_account_service_rest_unset_required_fields(): - transport = transports.AccountServicesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountServicesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.reject_account_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_reject_account_service_rest_flattened(): @@ -3429,24 +4106,24 @@ def test_reject_account_service_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/services/sample2'} + sample_request = {"name": "accounts/sample1/services/sample2"} # 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"} @@ -3456,10 +4133,14 @@ def test_reject_account_service_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/services/*}:reject" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/services/*}:reject" + % client.transport._host, + args[1], + ) -def test_reject_account_service_rest_flattened_error(transport: str = 'rest'): +def test_reject_account_service_rest_flattened_error(transport: str = "rest"): client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3470,7 +4151,7 @@ def test_reject_account_service_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.reject_account_service( accountservices.RejectAccountServiceRequest(), - name='name_value', + name="name_value", ) @@ -3512,8 +4193,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AccountServicesServiceClient( - 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. @@ -3535,6 +4215,7 @@ def test_transport_instance(): client = AccountServicesServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AccountServicesServiceGrpcTransport( @@ -3549,18 +4230,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AccountServicesServiceGrpcTransport, - transports.AccountServicesServiceGrpcAsyncIOTransport, - transports.AccountServicesServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + transports.AccountServicesServiceRestTransport, + ], +) 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 = AccountServicesServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3570,8 +4256,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3586,8 +4271,8 @@ def test_get_account_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: call.return_value = accountservices.AccountService() client.get_account_service(request=None) @@ -3609,8 +4294,8 @@ def test_list_account_services_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: call.return_value = accountservices.ListAccountServicesResponse() client.list_account_services(request=None) @@ -3632,8 +4317,8 @@ def test_propose_account_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: call.return_value = accountservices.AccountService() client.propose_account_service(request=None) @@ -3655,8 +4340,8 @@ def test_approve_account_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: call.return_value = accountservices.AccountService() client.approve_account_service(request=None) @@ -3678,8 +4363,8 @@ def test_reject_account_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: call.return_value = None client.reject_account_service(request=None) @@ -3700,8 +4385,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = AccountServicesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3717,16 +4401,18 @@ async def test_get_account_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", + ) + ) await client.get_account_service(request=None) # Establish that the underlying stub method was called. @@ -3748,12 +4434,14 @@ async def test_list_account_services_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.ListAccountServicesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.ListAccountServicesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_account_services(request=None) # Establish that the underlying stub method was called. @@ -3775,16 +4463,18 @@ async def test_propose_account_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", + ) + ) await client.propose_account_service(request=None) # Establish that the underlying stub method was called. @@ -3806,16 +4496,18 @@ async def test_approve_account_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accountservices.AccountService( + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", + ) + ) await client.approve_account_service(request=None) # Establish that the underlying stub method was called. @@ -3837,8 +4529,8 @@ async def test_reject_account_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.reject_account_service(request=None) @@ -3858,20 +4550,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_account_service_rest_bad_request(request_type=accountservices.GetAccountServiceRequest): +def test_get_account_service_rest_bad_request( + request_type=accountservices.GetAccountServiceRequest, +): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/services/sample2'} + request_init = {"name": "accounts/sample1/services/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() @@ -3880,29 +4575,31 @@ def test_get_account_service_rest_bad_request(request_type=accountservices.GetAc client.get_account_service(request) -@pytest.mark.parametrize("request_type", [ - accountservices.GetAccountServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountservices.GetAccountServiceRequest, + dict, + ], +) def test_get_account_service_rest_call_success(request_type): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/services/sample2'} + request_init = {"name": "accounts/sample1/services/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 = accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", ) # Wrap the value into a proper Response obj @@ -3912,37 +4609,48 @@ def test_get_account_service_rest_call_success(request_type): # Convert return value to protobuf type return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_account_service(request) # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_account_service_rest_interceptors(null_interceptor): transport = transports.AccountServicesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountServicesServiceRestInterceptor(), + ) client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_get_account_service") as post, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_get_account_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_get_account_service") 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.AccountServicesServiceRestInterceptor, "post_get_account_service" + ) as post, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, + "post_get_account_service_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, "pre_get_account_service" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountservices.GetAccountServiceRequest.pb(accountservices.GetAccountServiceRequest()) + pb_message = accountservices.GetAccountServiceRequest.pb( + accountservices.GetAccountServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3953,11 +4661,13 @@ def test_get_account_service_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 = accountservices.AccountService.to_json(accountservices.AccountService()) + return_value = accountservices.AccountService.to_json( + accountservices.AccountService() + ) req.return_value.content = return_value request = accountservices.GetAccountServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3965,27 +4675,36 @@ def test_get_account_service_rest_interceptors(null_interceptor): post.return_value = accountservices.AccountService() post_with_metadata.return_value = accountservices.AccountService(), metadata - client.get_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_account_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_account_services_rest_bad_request(request_type=accountservices.ListAccountServicesRequest): +def test_list_account_services_rest_bad_request( + request_type=accountservices.ListAccountServicesRequest, +): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3994,25 +4713,27 @@ def test_list_account_services_rest_bad_request(request_type=accountservices.Lis client.list_account_services(request) -@pytest.mark.parametrize("request_type", [ - accountservices.ListAccountServicesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountservices.ListAccountServicesRequest, + dict, + ], +) def test_list_account_services_rest_call_success(request_type): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accountservices.ListAccountServicesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -4022,33 +4743,44 @@ def test_list_account_services_rest_call_success(request_type): # Convert return value to protobuf type return_value = accountservices.ListAccountServicesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_account_services(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountServicesPager) - 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_account_services_rest_interceptors(null_interceptor): transport = transports.AccountServicesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountServicesServiceRestInterceptor(), + ) client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_list_account_services") as post, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_list_account_services_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_list_account_services") 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.AccountServicesServiceRestInterceptor, "post_list_account_services" + ) as post, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, + "post_list_account_services_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, "pre_list_account_services" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountservices.ListAccountServicesRequest.pb(accountservices.ListAccountServicesRequest()) + pb_message = accountservices.ListAccountServicesRequest.pb( + accountservices.ListAccountServicesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4059,39 +4791,53 @@ def test_list_account_services_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 = accountservices.ListAccountServicesResponse.to_json(accountservices.ListAccountServicesResponse()) + return_value = accountservices.ListAccountServicesResponse.to_json( + accountservices.ListAccountServicesResponse() + ) req.return_value.content = return_value request = accountservices.ListAccountServicesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = accountservices.ListAccountServicesResponse() - post_with_metadata.return_value = accountservices.ListAccountServicesResponse(), metadata + post_with_metadata.return_value = ( + accountservices.ListAccountServicesResponse(), + metadata, + ) - client.list_account_services(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_account_services( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_propose_account_service_rest_bad_request(request_type=accountservices.ProposeAccountServiceRequest): +def test_propose_account_service_rest_bad_request( + request_type=accountservices.ProposeAccountServiceRequest, +): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -4100,29 +4846,31 @@ def test_propose_account_service_rest_bad_request(request_type=accountservices.P client.propose_account_service(request) -@pytest.mark.parametrize("request_type", [ - accountservices.ProposeAccountServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountservices.ProposeAccountServiceRequest, + dict, + ], +) def test_propose_account_service_rest_call_success(request_type): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", ) # Wrap the value into a proper Response obj @@ -4132,37 +4880,48 @@ def test_propose_account_service_rest_call_success(request_type): # Convert return value to protobuf type return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.propose_account_service(request) # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_propose_account_service_rest_interceptors(null_interceptor): transport = transports.AccountServicesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountServicesServiceRestInterceptor(), + ) client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_propose_account_service") as post, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_propose_account_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_propose_account_service") 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.AccountServicesServiceRestInterceptor, "post_propose_account_service" + ) as post, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, + "post_propose_account_service_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, "pre_propose_account_service" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountservices.ProposeAccountServiceRequest.pb(accountservices.ProposeAccountServiceRequest()) + pb_message = accountservices.ProposeAccountServiceRequest.pb( + accountservices.ProposeAccountServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4173,11 +4932,13 @@ def test_propose_account_service_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 = accountservices.AccountService.to_json(accountservices.AccountService()) + return_value = accountservices.AccountService.to_json( + accountservices.AccountService() + ) req.return_value.content = return_value request = accountservices.ProposeAccountServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4185,27 +4946,36 @@ def test_propose_account_service_rest_interceptors(null_interceptor): post.return_value = accountservices.AccountService() post_with_metadata.return_value = accountservices.AccountService(), metadata - client.propose_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.propose_account_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_approve_account_service_rest_bad_request(request_type=accountservices.ApproveAccountServiceRequest): +def test_approve_account_service_rest_bad_request( + request_type=accountservices.ApproveAccountServiceRequest, +): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/services/sample2'} + request_init = {"name": "accounts/sample1/services/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() @@ -4214,29 +4984,31 @@ def test_approve_account_service_rest_bad_request(request_type=accountservices.A client.approve_account_service(request) -@pytest.mark.parametrize("request_type", [ - accountservices.ApproveAccountServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountservices.ApproveAccountServiceRequest, + dict, + ], +) def test_approve_account_service_rest_call_success(request_type): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/services/sample2'} + request_init = {"name": "accounts/sample1/services/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 = accountservices.AccountService( - name='name_value', - provider='provider_value', - provider_display_name='provider_display_name_value', - mutability=accountservices.AccountService.Mutability.MUTABLE, - external_account_id='external_account_id_value', + name="name_value", + provider="provider_value", + provider_display_name="provider_display_name_value", + mutability=accountservices.AccountService.Mutability.MUTABLE, + external_account_id="external_account_id_value", ) # Wrap the value into a proper Response obj @@ -4246,37 +5018,48 @@ def test_approve_account_service_rest_call_success(request_type): # Convert return value to protobuf type return_value = accountservices.AccountService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.approve_account_service(request) # Establish that the response is the type that we expect. assert isinstance(response, accountservices.AccountService) - assert response.name == 'name_value' - assert response.provider == 'provider_value' - assert response.provider_display_name == 'provider_display_name_value' + assert response.name == "name_value" + assert response.provider == "provider_value" + assert response.provider_display_name == "provider_display_name_value" assert response.mutability == accountservices.AccountService.Mutability.MUTABLE - assert response.external_account_id == 'external_account_id_value' + assert response.external_account_id == "external_account_id_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_approve_account_service_rest_interceptors(null_interceptor): transport = transports.AccountServicesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountServicesServiceRestInterceptor(), + ) client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "post_approve_account_service") as post, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "post_approve_account_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountServicesServiceRestInterceptor, "pre_approve_account_service") 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.AccountServicesServiceRestInterceptor, "post_approve_account_service" + ) as post, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, + "post_approve_account_service_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountServicesServiceRestInterceptor, "pre_approve_account_service" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accountservices.ApproveAccountServiceRequest.pb(accountservices.ApproveAccountServiceRequest()) + pb_message = accountservices.ApproveAccountServiceRequest.pb( + accountservices.ApproveAccountServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4287,11 +5070,13 @@ def test_approve_account_service_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 = accountservices.AccountService.to_json(accountservices.AccountService()) + return_value = accountservices.AccountService.to_json( + accountservices.AccountService() + ) req.return_value.content = return_value request = accountservices.ApproveAccountServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4299,27 +5084,36 @@ def test_approve_account_service_rest_interceptors(null_interceptor): post.return_value = accountservices.AccountService() post_with_metadata.return_value = accountservices.AccountService(), metadata - client.approve_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.approve_account_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_reject_account_service_rest_bad_request(request_type=accountservices.RejectAccountServiceRequest): +def test_reject_account_service_rest_bad_request( + request_type=accountservices.RejectAccountServiceRequest, +): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/services/sample2'} + request_init = {"name": "accounts/sample1/services/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() @@ -4328,30 +5122,32 @@ def test_reject_account_service_rest_bad_request(request_type=accountservices.Re client.reject_account_service(request) -@pytest.mark.parametrize("request_type", [ - accountservices.RejectAccountServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accountservices.RejectAccountServiceRequest, + dict, + ], +) def test_reject_account_service_rest_call_success(request_type): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/services/sample2'} + request_init = {"name": "accounts/sample1/services/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 = 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.reject_account_service(request) @@ -4364,15 +5160,23 @@ def test_reject_account_service_rest_call_success(request_type): def test_reject_account_service_rest_interceptors(null_interceptor): transport = transports.AccountServicesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountServicesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountServicesServiceRestInterceptor(), + ) client = AccountServicesServiceClient(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.AccountServicesServiceRestInterceptor, "pre_reject_account_service") 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.AccountServicesServiceRestInterceptor, "pre_reject_account_service" + ) as pre: pre.assert_not_called() - pb_message = accountservices.RejectAccountServiceRequest.pb(accountservices.RejectAccountServiceRequest()) + pb_message = accountservices.RejectAccountServiceRequest.pb( + accountservices.RejectAccountServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4385,20 +5189,26 @@ def test_reject_account_service_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = accountservices.RejectAccountServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.reject_account_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.reject_account_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() + def test_initialize_client_w_rest(): client = AccountServicesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -4413,8 +5223,8 @@ def test_get_account_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_account_service), - '__call__') as call: + type(client.transport.get_account_service), "__call__" + ) as call: client.get_account_service(request=None) # Establish that the underlying stub method was called. @@ -4435,8 +5245,8 @@ def test_list_account_services_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_account_services), - '__call__') as call: + type(client.transport.list_account_services), "__call__" + ) as call: client.list_account_services(request=None) # Establish that the underlying stub method was called. @@ -4457,8 +5267,8 @@ def test_propose_account_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.propose_account_service), - '__call__') as call: + type(client.transport.propose_account_service), "__call__" + ) as call: client.propose_account_service(request=None) # Establish that the underlying stub method was called. @@ -4479,8 +5289,8 @@ def test_approve_account_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.approve_account_service), - '__call__') as call: + type(client.transport.approve_account_service), "__call__" + ) as call: client.approve_account_service(request=None) # Establish that the underlying stub method was called. @@ -4501,8 +5311,8 @@ def test_reject_account_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.reject_account_service), - '__call__') as call: + type(client.transport.reject_account_service), "__call__" + ) as call: client.reject_account_service(request=None) # Establish that the underlying stub method was called. @@ -4523,18 +5333,21 @@ def test_transport_grpc_default(): transports.AccountServicesServiceGrpcTransport, ) + def test_account_services_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AccountServicesServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_account_services_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AccountServicesServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4543,11 +5356,11 @@ def test_account_services_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_account_service', - 'list_account_services', - 'propose_account_service', - 'approve_account_service', - 'reject_account_service', + "get_account_service", + "list_account_services", + "propose_account_service", + "approve_account_service", + "reject_account_service", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4558,7 +5371,7 @@ def test_account_services_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4567,25 +5380,30 @@ def test_account_services_service_base_transport(): def test_account_services_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_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport._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_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountServicesServiceTransport( 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_account_services_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_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.account_services_service.transports.AccountServicesServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountServicesServiceTransport() @@ -4594,14 +5412,12 @@ def test_account_services_service_base_transport_with_adc(): def test_account_services_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) AccountServicesServiceClient() 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, ) @@ -4616,12 +5432,12 @@ def test_account_services_service_auth_adc(): def test_account_services_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", ) @@ -4635,48 +5451,47 @@ def test_account_services_service_transport_auth_adc(transport_class): ], ) def test_account_services_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.AccountServicesServiceGrpcTransport, grpc_helpers), - (transports.AccountServicesServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.AccountServicesServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_account_services_service_transport_create_channel(transport_class, grpc_helpers): +def test_account_services_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, @@ -4687,9 +5502,15 @@ def test_account_services_service_transport_create_channel(transport_class, grpc ) -@pytest.mark.parametrize("transport_class", [transports.AccountServicesServiceGrpcTransport, transports.AccountServicesServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + ], +) def test_account_services_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -4699,7 +5520,7 @@ def test_account_services_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", @@ -4720,61 +5541,77 @@ def test_account_services_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_account_services_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.AccountServicesServiceRestTransport ( - 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.AccountServicesServiceRestTransport( + 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_account_services_service_host_no_port(transport_name): client = AccountServicesServiceClient( 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_account_services_service_host_with_port(transport_name): client = AccountServicesServiceClient( 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_account_services_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4801,8 +5638,10 @@ def test_account_services_service_client_transport_session_collision(transport_n session1 = client1.transport.reject_account_service._session session2 = client2.transport.reject_account_service._session assert session1 != session2 + + def test_account_services_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.AccountServicesServiceGrpcTransport( @@ -4815,7 +5654,7 @@ def test_account_services_service_grpc_transport_channel(): def test_account_services_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.AccountServicesServiceGrpcAsyncIOTransport( @@ -4829,12 +5668,22 @@ def test_account_services_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.AccountServicesServiceGrpcTransport, transports.AccountServicesServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + ], +) def test_account_services_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 @@ -4843,7 +5692,7 @@ def test_account_services_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", @@ -4873,17 +5722,23 @@ def test_account_services_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.AccountServicesServiceGrpcTransport, transports.AccountServicesServiceGrpcAsyncIOTransport]) -def test_account_services_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountServicesServiceGrpcTransport, + transports.AccountServicesServiceGrpcAsyncIOTransport, + ], +) +def test_account_services_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() @@ -4913,7 +5768,9 @@ def test_account_services_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = AccountServicesServiceClient.account_path(account) assert expected == actual @@ -4928,10 +5785,14 @@ def test_parse_account_path(): actual = AccountServicesServiceClient.parse_account_path(path) assert expected == actual + def test_account_service_path(): account = "whelk" service = "octopus" - expected = "accounts/{account}/services/{service}".format(account=account, service=service, ) + expected = "accounts/{account}/services/{service}".format( + account=account, + service=service, + ) actual = AccountServicesServiceClient.account_service_path(account, service) assert expected == actual @@ -4947,9 +5808,12 @@ def test_parse_account_service_path(): actual = AccountServicesServiceClient.parse_account_service_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 = AccountServicesServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -4964,9 +5828,12 @@ def test_parse_common_billing_account_path(): actual = AccountServicesServiceClient.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 = AccountServicesServiceClient.common_folder_path(folder) assert expected == actual @@ -4981,9 +5848,12 @@ def test_parse_common_folder_path(): actual = AccountServicesServiceClient.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 = AccountServicesServiceClient.common_organization_path(organization) assert expected == actual @@ -4998,9 +5868,12 @@ def test_parse_common_organization_path(): actual = AccountServicesServiceClient.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 = AccountServicesServiceClient.common_project_path(project) assert expected == actual @@ -5015,10 +5888,14 @@ def test_parse_common_project_path(): actual = AccountServicesServiceClient.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 = AccountServicesServiceClient.common_location_path(project, location) assert expected == actual @@ -5038,14 +5915,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.AccountServicesServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountServicesServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AccountServicesServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AccountServicesServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountServicesServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AccountServicesServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5056,10 +5937,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = AccountServicesServiceClient( - 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() @@ -5068,10 +5950,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AccountServicesServiceAsyncClient( - 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() @@ -5079,10 +5962,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AccountServicesServiceClient( - 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() @@ -5090,13 +5974,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AccountServicesServiceClient( - 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: @@ -5105,10 +5988,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport), - (AccountServicesServiceAsyncClient, transports.AccountServicesServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (AccountServicesServiceClient, transports.AccountServicesServiceGrpcTransport), + ( + AccountServicesServiceAsyncClient, + transports.AccountServicesServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5123,7 +6013,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py similarity index 70% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py index 28c58a938938..30f63c0dda15 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_accounts_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_accounts_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,50 +22,50 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.accounts_service import AccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.accounts_service import AccountsServiceClient -from google.shopping.merchant_accounts_v1.services.accounts_service import pagers -from google.shopping.merchant_accounts_v1.services.accounts_service import transports -from google.shopping.merchant_accounts_v1.types import accessright -from google.shopping.merchant_accounts_v1.types import accounts -from google.shopping.merchant_accounts_v1.types import accountservices -from google.shopping.merchant_accounts_v1.types import user from google.type import datetime_pb2 # type: ignore -import google.auth - +from google.shopping.merchant_accounts_v1.services.accounts_service import ( + AccountsServiceAsyncClient, + AccountsServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import ( + accessright, + accounts, + accountservices, + user, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -79,9 +80,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(): @@ -89,17 +92,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(): @@ -110,101 +123,228 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AccountsServiceClient._get_default_mtls_endpoint(None) is None - assert AccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AccountsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + def test__read_environment_variables(): assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AccountsServiceClient._read_environment_variables() == (True, "auto", None) + assert AccountsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountsServiceClient._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: AccountsServiceClient._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 AccountsServiceClient._read_environment_variables() == (False, "never", None) + assert AccountsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AccountsServiceClient._read_environment_variables() == (False, "always", None) + assert AccountsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AccountsServiceClient._read_environment_variables() == (False, "auto", None) + assert AccountsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AccountsServiceClient._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 AccountsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, False) is None - assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + AccountsServiceClient._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 ( + AccountsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AccountsServiceClient._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 AccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) +@mock.patch.object( + AccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceClient), +) +@mock.patch.object( + AccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert AccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AccountsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AccountsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + AccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") + == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AccountsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + AccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AccountsServiceClient._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." + AccountsServiceClient._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 AccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AccountsServiceClient._get_universe_domain(None, None) == AccountsServiceClient._DEFAULT_UNIVERSE + assert ( + AccountsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AccountsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + AccountsServiceClient._get_universe_domain(None, None) + == AccountsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AccountsServiceClient._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) @@ -220,7 +360,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") @@ -233,14 +374,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", [ - (AccountsServiceClient, "grpc"), - (AccountsServiceAsyncClient, "grpc_asyncio"), - (AccountsServiceClient, "rest"), -]) -def test_accounts_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountsServiceClient, "grpc"), + (AccountsServiceAsyncClient, "grpc_asyncio"), + (AccountsServiceClient, "rest"), + ], +) +def test_accounts_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) @@ -248,52 +397,70 @@ def test_accounts_service_client_from_service_account_info(client_class, transpo 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.AccountsServiceGrpcTransport, "grpc"), - (transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AccountsServiceRestTransport, "rest"), -]) -def test_accounts_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.AccountsServiceGrpcTransport, "grpc"), + (transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AccountsServiceRestTransport, "rest"), + ], +) +def test_accounts_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", [ - (AccountsServiceClient, "grpc"), - (AccountsServiceAsyncClient, "grpc_asyncio"), - (AccountsServiceClient, "rest"), -]) -def test_accounts_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AccountsServiceClient, "grpc"), + (AccountsServiceAsyncClient, "grpc_asyncio"), + (AccountsServiceClient, "rest"), + ], +) +def test_accounts_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" ) @@ -309,30 +476,45 @@ def test_accounts_service_client_get_transport_class(): assert transport == transports.AccountsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), -]) -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) -def test_accounts_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + ( + AccountsServiceAsyncClient, + transports.AccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + AccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceClient), +) +@mock.patch.object( + AccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceAsyncClient), +) +def test_accounts_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(AccountsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(AccountsServiceClient, "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(AccountsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(AccountsServiceClient, "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( @@ -350,13 +532,15 @@ def test_accounts_service_client_client_options(client_class, transport_class, t # 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, @@ -368,7 +552,7 @@ def test_accounts_service_client_client_options(client_class, transport_class, t # 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( @@ -388,23 +572,33 @@ def test_accounts_service_client_client_options(client_class, transport_class, t 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", @@ -413,48 +607,102 @@ def test_accounts_service_client_client_options(client_class, transport_class, t 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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "true"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", "false"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "true"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AccountsServiceClient, + transports.AccountsServiceGrpcTransport, + "grpc", + "true", + ), + ( + AccountsServiceAsyncClient, + transports.AccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AccountsServiceClient, + transports.AccountsServiceGrpcTransport, + "grpc", + "false", + ), + ( + AccountsServiceAsyncClient, + transports.AccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AccountsServiceClient, + transports.AccountsServiceRestTransport, + "rest", + "true", + ), + ( + AccountsServiceClient, + transports.AccountsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceClient), +) +@mock.patch.object( + AccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_accounts_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_accounts_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 @@ -473,12 +721,22 @@ def test_accounts_service_client_mtls_env_auto(client_class, transport_class, tr # 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 @@ -499,15 +757,22 @@ def test_accounts_service_client_mtls_env_auto(client_class, transport_class, tr ) # 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, @@ -517,19 +782,31 @@ def test_accounts_service_client_mtls_env_auto(client_class, transport_class, tr ) -@pytest.mark.parametrize("client_class", [ - AccountsServiceClient, AccountsServiceAsyncClient -]) -@mock.patch.object(AccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AccountsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [AccountsServiceClient, AccountsServiceAsyncClient] +) +@mock.patch.object( + AccountsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountsServiceClient), +) +@mock.patch.object( + AccountsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AccountsServiceAsyncClient), +) def test_accounts_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 @@ -537,8 +814,12 @@ def test_accounts_service_client_get_mtls_endpoint_and_cert_source(client_class) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -556,16 +837,28 @@ def test_accounts_service_client_get_mtls_endpoint_and_cert_source(client_class) # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -575,34 +868,62 @@ def test_accounts_service_client_get_mtls_endpoint_and_cert_source(client_class) with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # 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", [ - AccountsServiceClient, AccountsServiceAsyncClient -]) -@mock.patch.object(AccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceClient)) -@mock.patch.object(AccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AccountsServiceAsyncClient)) + +@pytest.mark.parametrize( + "client_class", [AccountsServiceClient, AccountsServiceAsyncClient] +) +@mock.patch.object( + AccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceClient), +) +@mock.patch.object( + AccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AccountsServiceAsyncClient), +) def test_accounts_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AccountsServiceClient._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", @@ -625,11 +946,19 @@ def test_accounts_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. @@ -637,27 +966,40 @@ def test_accounts_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", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), -]) -def test_accounts_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc"), + ( + AccountsServiceAsyncClient, + transports.AccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest"), + ], +) +def test_accounts_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, @@ -666,24 +1008,40 @@ def test_accounts_service_client_client_options_scopes(client_class, transport_c api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", None), -]) -def test_accounts_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", + [ + ( + AccountsServiceClient, + transports.AccountsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountsServiceAsyncClient, + transports.AccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (AccountsServiceClient, transports.AccountsServiceRestTransport, "rest", None), + ], +) +def test_accounts_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, @@ -692,11 +1050,14 @@ def test_accounts_service_client_client_options_credentials_file(client_class, t api_audience=None, ) + def test_accounts_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AccountsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -711,23 +1072,38 @@ def test_accounts_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport, "grpc", grpc_helpers), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_accounts_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", + [ + ( + AccountsServiceClient, + transports.AccountsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AccountsServiceAsyncClient, + transports.AccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_accounts_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, @@ -754,9 +1130,7 @@ def test_accounts_service_client_create_channel_credentials_file(client_class, t 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, @@ -767,11 +1141,14 @@ def test_accounts_service_client_create_channel_credentials_file(client_class, t ) -@pytest.mark.parametrize("request_type", [ - accounts.GetAccountRequest, - dict, -]) -def test_get_account(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accounts.GetAccountRequest, + dict, + ], +) +def test_get_account(request_type, transport: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -782,17 +1159,15 @@ def test_get_account(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account( - name='name_value', + name="name_value", account_id=1049, - account_name='account_name_value', + account_name="account_name_value", adult_content=True, test_account=True, - language_code='language_code_value', + language_code="language_code_value", ) response = client.get_account(request) @@ -804,12 +1179,12 @@ def test_get_account(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" def test_get_account_non_empty_request_with_auto_populated_field(): @@ -817,28 +1192,29 @@ def test_get_account_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountsServiceClient( 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 = accounts.GetAccountRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.get_account), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_account(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accounts.GetAccountRequest( - name='name_value', + name="name_value", ) + def test_get_account_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -857,7 +1233,9 @@ def test_get_account_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_account] = mock_rpc request = {} client.get_account(request) @@ -871,8 +1249,11 @@ def test_get_account_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_account_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: @@ -886,12 +1267,17 @@ async def test_get_account_async_use_cached_wrapped_rpc(transport: str = "grpc_a wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_account in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_account + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_account] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_account + ] = mock_rpc request = {} await client.get_account(request) @@ -905,8 +1291,11 @@ async def test_get_account_async_use_cached_wrapped_rpc(transport: str = "grpc_a assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_account_async(transport: str = 'grpc_asyncio', request_type=accounts.GetAccountRequest): +async def test_get_account_async( + transport: str = "grpc_asyncio", request_type=accounts.GetAccountRequest +): client = AccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -917,18 +1306,18 @@ async def test_get_account_async(transport: str = 'grpc_asyncio', request_type=a request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.Account( + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", + ) + ) response = await client.get_account(request) # Establish that the underlying gRPC stub method was called. @@ -939,18 +1328,19 @@ async def test_get_account_async(transport: str = 'grpc_asyncio', request_type=a # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" @pytest.mark.asyncio async def test_get_account_async_from_dict(): await test_get_account_async(request_type=dict) + def test_get_account_field_headers(): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -960,12 +1350,10 @@ def test_get_account_field_headers(): # a field header. Set these to a non-empty value. request = accounts.GetAccountRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: call.return_value = accounts.Account() client.get_account(request) @@ -977,9 +1365,9 @@ def test_get_account_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 @@ -992,12 +1380,10 @@ async def test_get_account_field_headers_async(): # a field header. Set these to a non-empty value. request = accounts.GetAccountRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) await client.get_account(request) @@ -1009,9 +1395,9 @@ async def test_get_account_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_account_flattened(): @@ -1020,15 +1406,13 @@ def test_get_account_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_account( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1036,7 +1420,7 @@ def test_get_account_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 @@ -1050,9 +1434,10 @@ def test_get_account_flattened_error(): with pytest.raises(ValueError): client.get_account( accounts.GetAccountRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_account_flattened_async(): client = AccountsServiceAsyncClient( @@ -1060,9 +1445,7 @@ async def test_get_account_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account() @@ -1070,7 +1453,7 @@ async def test_get_account_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_account( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1078,9 +1461,10 @@ async def test_get_account_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_account_flattened_error_async(): client = AccountsServiceAsyncClient( @@ -1092,15 +1476,18 @@ async def test_get_account_flattened_error_async(): with pytest.raises(ValueError): await client.get_account( accounts.GetAccountRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - accounts.CreateAndConfigureAccountRequest, - dict, -]) -def test_create_and_configure_account(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accounts.CreateAndConfigureAccountRequest, + dict, + ], +) +def test_create_and_configure_account(request_type, transport: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1112,16 +1499,16 @@ def test_create_and_configure_account(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: + type(client.transport.create_and_configure_account), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account( - name='name_value', + name="name_value", account_id=1049, - account_name='account_name_value', + account_name="account_name_value", adult_content=True, test_account=True, - language_code='language_code_value', + language_code="language_code_value", ) response = client.create_and_configure_account(request) @@ -1133,12 +1520,12 @@ def test_create_and_configure_account(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" def test_create_and_configure_account_non_empty_request_with_auto_populated_field(): @@ -1146,25 +1533,26 @@ def test_create_and_configure_account_non_empty_request_with_auto_populated_fiel # automatically populated, according to AIP-4235, with non-empty requests. client = AccountsServiceClient( 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 = accounts.CreateAndConfigureAccountRequest( - ) + request = accounts.CreateAndConfigureAccountRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.create_and_configure_account), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_and_configure_account(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == accounts.CreateAndConfigureAccountRequest( - ) + assert args[0] == accounts.CreateAndConfigureAccountRequest() + def test_create_and_configure_account_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1180,12 +1568,19 @@ def test_create_and_configure_account_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_and_configure_account in client._transport._wrapped_methods + assert ( + client._transport.create_and_configure_account + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_and_configure_account + ] = mock_rpc request = {} client.create_and_configure_account(request) @@ -1198,8 +1593,11 @@ def test_create_and_configure_account_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_and_configure_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_and_configure_account_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: @@ -1213,12 +1611,17 @@ async def test_create_and_configure_account_async_use_cached_wrapped_rpc(transpo wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_and_configure_account in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_and_configure_account + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_and_configure_account] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_and_configure_account + ] = mock_rpc request = {} await client.create_and_configure_account(request) @@ -1232,8 +1635,12 @@ async def test_create_and_configure_account_async_use_cached_wrapped_rpc(transpo assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_and_configure_account_async(transport: str = 'grpc_asyncio', request_type=accounts.CreateAndConfigureAccountRequest): +async def test_create_and_configure_account_async( + transport: str = "grpc_asyncio", + request_type=accounts.CreateAndConfigureAccountRequest, +): client = AccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1245,17 +1652,19 @@ async def test_create_and_configure_account_async(transport: str = 'grpc_asyncio # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: + type(client.transport.create_and_configure_account), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.Account( + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", + ) + ) response = await client.create_and_configure_account(request) # Establish that the underlying gRPC stub method was called. @@ -1266,12 +1675,12 @@ async def test_create_and_configure_account_async(transport: str = 'grpc_asyncio # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" @pytest.mark.asyncio @@ -1279,11 +1688,14 @@ async def test_create_and_configure_account_async_from_dict(): await test_create_and_configure_account_async(request_type=dict) -@pytest.mark.parametrize("request_type", [ - accounts.DeleteAccountRequest, - dict, -]) -def test_delete_account(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accounts.DeleteAccountRequest, + dict, + ], +) +def test_delete_account(request_type, transport: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1294,9 +1706,7 @@ def test_delete_account(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_account(request) @@ -1316,28 +1726,29 @@ def test_delete_account_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountsServiceClient( 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 = accounts.DeleteAccountRequest( - 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_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_account(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accounts.DeleteAccountRequest( - name='name_value', + name="name_value", ) + def test_delete_account_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1356,7 +1767,9 @@ def test_delete_account_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc request = {} client.delete_account(request) @@ -1370,8 +1783,11 @@ def test_delete_account_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_account_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: @@ -1385,12 +1801,17 @@ async def test_delete_account_async_use_cached_wrapped_rpc(transport: str = "grp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_account in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_account + 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_account] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_account + ] = mock_rpc request = {} await client.delete_account(request) @@ -1404,8 +1825,11 @@ async def test_delete_account_async_use_cached_wrapped_rpc(transport: str = "grp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_account_async(transport: str = 'grpc_asyncio', request_type=accounts.DeleteAccountRequest): +async def test_delete_account_async( + transport: str = "grpc_asyncio", request_type=accounts.DeleteAccountRequest +): client = AccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1416,9 +1840,7 @@ async def test_delete_account_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_account(request) @@ -1437,6 +1859,7 @@ async def test_delete_account_async(transport: str = 'grpc_asyncio', request_typ async def test_delete_account_async_from_dict(): await test_delete_account_async(request_type=dict) + def test_delete_account_field_headers(): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1446,12 +1869,10 @@ def test_delete_account_field_headers(): # a field header. Set these to a non-empty value. request = accounts.DeleteAccountRequest() - 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_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: call.return_value = None client.delete_account(request) @@ -1463,9 +1884,9 @@ def test_delete_account_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 @@ -1478,12 +1899,10 @@ async def test_delete_account_field_headers_async(): # a field header. Set these to a non-empty value. request = accounts.DeleteAccountRequest() - 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_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_account(request) @@ -1495,9 +1914,9 @@ async def test_delete_account_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_account_flattened(): @@ -1506,15 +1925,13 @@ def test_delete_account_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__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_account( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1522,7 +1939,7 @@ def test_delete_account_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 @@ -1536,9 +1953,10 @@ def test_delete_account_flattened_error(): with pytest.raises(ValueError): client.delete_account( accounts.DeleteAccountRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_account_flattened_async(): client = AccountsServiceAsyncClient( @@ -1546,9 +1964,7 @@ async def test_delete_account_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1556,7 +1972,7 @@ async def test_delete_account_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_account( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1564,9 +1980,10 @@ async def test_delete_account_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_account_flattened_error_async(): client = AccountsServiceAsyncClient( @@ -1578,15 +1995,18 @@ async def test_delete_account_flattened_error_async(): with pytest.raises(ValueError): await client.delete_account( accounts.DeleteAccountRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - accounts.UpdateAccountRequest, - dict, -]) -def test_update_account(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accounts.UpdateAccountRequest, + dict, + ], +) +def test_update_account(request_type, transport: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1597,17 +2017,15 @@ def test_update_account(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account( - name='name_value', + name="name_value", account_id=1049, - account_name='account_name_value', + account_name="account_name_value", adult_content=True, test_account=True, - language_code='language_code_value', + language_code="language_code_value", ) response = client.update_account(request) @@ -1619,12 +2037,12 @@ def test_update_account(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" def test_update_account_non_empty_request_with_auto_populated_field(): @@ -1632,25 +2050,24 @@ def test_update_account_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountsServiceClient( 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 = accounts.UpdateAccountRequest( - ) + request = accounts.UpdateAccountRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.update_account), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_account(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == accounts.UpdateAccountRequest( - ) + assert args[0] == accounts.UpdateAccountRequest() + def test_update_account_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1670,7 +2087,9 @@ def test_update_account_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_account] = mock_rpc request = {} client.update_account(request) @@ -1684,8 +2103,11 @@ def test_update_account_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_account_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: @@ -1699,12 +2121,17 @@ async def test_update_account_async_use_cached_wrapped_rpc(transport: str = "grp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_account in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_account + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_account] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_account + ] = mock_rpc request = {} await client.update_account(request) @@ -1718,8 +2145,11 @@ async def test_update_account_async_use_cached_wrapped_rpc(transport: str = "grp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_account_async(transport: str = 'grpc_asyncio', request_type=accounts.UpdateAccountRequest): +async def test_update_account_async( + transport: str = "grpc_asyncio", request_type=accounts.UpdateAccountRequest +): client = AccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1730,18 +2160,18 @@ async def test_update_account_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.Account( + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", + ) + ) response = await client.update_account(request) # Establish that the underlying gRPC stub method was called. @@ -1752,18 +2182,19 @@ async def test_update_account_async(transport: str = 'grpc_asyncio', request_typ # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" @pytest.mark.asyncio async def test_update_account_async_from_dict(): await test_update_account_async(request_type=dict) + def test_update_account_field_headers(): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1773,12 +2204,10 @@ def test_update_account_field_headers(): # a field header. Set these to a non-empty value. request = accounts.UpdateAccountRequest() - request.account.name = 'name_value' + request.account.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: call.return_value = accounts.Account() client.update_account(request) @@ -1790,9 +2219,9 @@ def test_update_account_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'account.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "account.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1805,12 +2234,10 @@ async def test_update_account_field_headers_async(): # a field header. Set these to a non-empty value. request = accounts.UpdateAccountRequest() - request.account.name = 'name_value' + request.account.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account()) await client.update_account(request) @@ -1822,9 +2249,9 @@ async def test_update_account_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'account.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "account.name=name_value", + ) in kw["metadata"] def test_update_account_flattened(): @@ -1833,16 +2260,14 @@ def test_update_account_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_account( - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account=accounts.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1850,10 +2275,10 @@ def test_update_account_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].account - mock_val = accounts.Account(name='name_value') + mock_val = accounts.Account(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1867,10 +2292,11 @@ def test_update_account_flattened_error(): with pytest.raises(ValueError): client.update_account( accounts.UpdateAccountRequest(), - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account=accounts.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_account_flattened_async(): client = AccountsServiceAsyncClient( @@ -1878,9 +2304,7 @@ async def test_update_account_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.Account() @@ -1888,8 +2312,8 @@ async def test_update_account_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_account( - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account=accounts.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1897,12 +2321,13 @@ async def test_update_account_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].account - mock_val = accounts.Account(name='name_value') + mock_val = accounts.Account(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_account_flattened_error_async(): client = AccountsServiceAsyncClient( @@ -1914,16 +2339,19 @@ async def test_update_account_flattened_error_async(): with pytest.raises(ValueError): await client.update_account( accounts.UpdateAccountRequest(), - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account=accounts.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - accounts.ListAccountsRequest, - dict, -]) -def test_list_accounts(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + accounts.ListAccountsRequest, + dict, + ], +) +def test_list_accounts(request_type, transport: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1934,12 +2362,10 @@ def test_list_accounts(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = accounts.ListAccountsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_accounts(request) @@ -1951,7 +2377,7 @@ def test_list_accounts(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_accounts_non_empty_request_with_auto_populated_field(): @@ -1959,30 +2385,31 @@ def test_list_accounts_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountsServiceClient( 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 = accounts.ListAccountsRequest( - page_token='page_token_value', - filter='filter_value', + page_token="page_token_value", + filter="filter_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_accounts(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accounts.ListAccountsRequest( - page_token='page_token_value', - filter='filter_value', + page_token="page_token_value", + filter="filter_value", ) + def test_list_accounts_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2001,7 +2428,9 @@ def test_list_accounts_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc request = {} client.list_accounts(request) @@ -2015,8 +2444,11 @@ def test_list_accounts_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_accounts_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: @@ -2030,12 +2462,17 @@ async def test_list_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_accounts in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_accounts + 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_accounts] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_accounts + ] = mock_rpc request = {} await client.list_accounts(request) @@ -2049,8 +2486,11 @@ async def test_list_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListAccountsRequest): +async def test_list_accounts_async( + transport: str = "grpc_asyncio", request_type=accounts.ListAccountsRequest +): client = AccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2061,13 +2501,13 @@ async def test_list_accounts_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.ListAccountsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_accounts(request) # Establish that the underlying gRPC stub method was called. @@ -2078,7 +2518,7 @@ async def test_list_accounts_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountsAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio @@ -2093,9 +2533,7 @@ def test_list_accounts_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_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListAccountsResponse( @@ -2104,17 +2542,17 @@ def test_list_accounts_pager(transport_name: str = "grpc"): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListAccountsResponse( accounts=[ @@ -2136,8 +2574,9 @@ def test_list_accounts_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accounts.Account) - for i in results) + assert all(isinstance(i, accounts.Account) for i in results) + + def test_list_accounts_pages(transport_name: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2145,9 +2584,7 @@ def test_list_accounts_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_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListAccountsResponse( @@ -2156,17 +2593,17 @@ def test_list_accounts_pages(transport_name: str = "grpc"): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListAccountsResponse( accounts=[ @@ -2177,9 +2614,10 @@ def test_list_accounts_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_accounts(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_accounts_async_pager(): client = AccountsServiceAsyncClient( @@ -2188,8 +2626,8 @@ async def test_list_accounts_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accounts), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_accounts), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListAccountsResponse( @@ -2198,17 +2636,17 @@ async def test_list_accounts_async_pager(): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListAccountsResponse( accounts=[ @@ -2218,15 +2656,16 @@ async def test_list_accounts_async_pager(): ), RuntimeError, ) - async_pager = await client.list_accounts(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_accounts( + 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, accounts.Account) - for i in responses) + assert all(isinstance(i, accounts.Account) for i in responses) @pytest.mark.asyncio @@ -2237,8 +2676,8 @@ async def test_list_accounts_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_accounts), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_accounts), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListAccountsResponse( @@ -2247,17 +2686,17 @@ async def test_list_accounts_async_pages(): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListAccountsResponse( accounts=[ @@ -2270,18 +2709,22 @@ async def test_list_accounts_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_accounts(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", [ - accounts.ListSubAccountsRequest, - dict, -]) -def test_list_sub_accounts(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + accounts.ListSubAccountsRequest, + dict, + ], +) +def test_list_sub_accounts(request_type, transport: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2293,11 +2736,11 @@ def test_list_sub_accounts(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_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_sub_accounts(request) @@ -2309,7 +2752,7 @@ def test_list_sub_accounts(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSubAccountsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_sub_accounts_non_empty_request_with_auto_populated_field(): @@ -2317,30 +2760,33 @@ def test_list_sub_accounts_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AccountsServiceClient( 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 = accounts.ListSubAccountsRequest( - provider='provider_value', - page_token='page_token_value', + provider="provider_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_sub_accounts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_sub_accounts), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_sub_accounts(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == accounts.ListSubAccountsRequest( - provider='provider_value', - page_token='page_token_value', + provider="provider_value", + page_token="page_token_value", ) + def test_list_sub_accounts_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2359,8 +2805,12 @@ def test_list_sub_accounts_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_sub_accounts] = 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_sub_accounts + ] = mock_rpc request = {} client.list_sub_accounts(request) @@ -2373,8 +2823,11 @@ def test_list_sub_accounts_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_sub_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_sub_accounts_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: @@ -2388,12 +2841,17 @@ async def test_list_sub_accounts_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_sub_accounts in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_sub_accounts + 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_sub_accounts] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_sub_accounts + ] = mock_rpc request = {} await client.list_sub_accounts(request) @@ -2407,8 +2865,11 @@ async def test_list_sub_accounts_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_sub_accounts_async(transport: str = 'grpc_asyncio', request_type=accounts.ListSubAccountsRequest): +async def test_list_sub_accounts_async( + transport: str = "grpc_asyncio", request_type=accounts.ListSubAccountsRequest +): client = AccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2420,12 +2881,14 @@ async def test_list_sub_accounts_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.ListSubAccountsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_sub_accounts(request) # Establish that the underlying gRPC stub method was called. @@ -2436,13 +2899,14 @@ async def test_list_sub_accounts_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSubAccountsAsyncPager) - 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_sub_accounts_async_from_dict(): await test_list_sub_accounts_async(request_type=dict) + def test_list_sub_accounts_field_headers(): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2452,12 +2916,12 @@ def test_list_sub_accounts_field_headers(): # a field header. Set these to a non-empty value. request = accounts.ListSubAccountsRequest() - request.provider = 'provider_value' + request.provider = "provider_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: call.return_value = accounts.ListSubAccountsResponse() client.list_sub_accounts(request) @@ -2469,9 +2933,9 @@ def test_list_sub_accounts_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'provider=provider_value', - ) in kw['metadata'] + "x-goog-request-params", + "provider=provider_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2484,13 +2948,15 @@ async def test_list_sub_accounts_field_headers_async(): # a field header. Set these to a non-empty value. request = accounts.ListSubAccountsRequest() - request.provider = 'provider_value' + request.provider = "provider_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) + type(client.transport.list_sub_accounts), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.ListSubAccountsResponse() + ) await client.list_sub_accounts(request) # Establish that the underlying gRPC stub method was called. @@ -2501,9 +2967,9 @@ async def test_list_sub_accounts_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'provider=provider_value', - ) in kw['metadata'] + "x-goog-request-params", + "provider=provider_value", + ) in kw["metadata"] def test_list_sub_accounts_flattened(): @@ -2513,14 +2979,14 @@ def test_list_sub_accounts_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accounts.ListSubAccountsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_sub_accounts( - provider='provider_value', + provider="provider_value", ) # Establish that the underlying call was made with the expected @@ -2528,7 +2994,7 @@ def test_list_sub_accounts_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].provider - mock_val = 'provider_value' + mock_val = "provider_value" assert arg == mock_val @@ -2542,9 +3008,10 @@ def test_list_sub_accounts_flattened_error(): with pytest.raises(ValueError): client.list_sub_accounts( accounts.ListSubAccountsRequest(), - provider='provider_value', + provider="provider_value", ) + @pytest.mark.asyncio async def test_list_sub_accounts_flattened_async(): client = AccountsServiceAsyncClient( @@ -2553,16 +3020,18 @@ async def test_list_sub_accounts_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = accounts.ListSubAccountsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.ListSubAccountsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_sub_accounts( - provider='provider_value', + provider="provider_value", ) # Establish that the underlying call was made with the expected @@ -2570,9 +3039,10 @@ async def test_list_sub_accounts_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].provider - mock_val = 'provider_value' + mock_val = "provider_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_sub_accounts_flattened_error_async(): client = AccountsServiceAsyncClient( @@ -2584,7 +3054,7 @@ async def test_list_sub_accounts_flattened_error_async(): with pytest.raises(ValueError): await client.list_sub_accounts( accounts.ListSubAccountsRequest(), - provider='provider_value', + provider="provider_value", ) @@ -2596,8 +3066,8 @@ def test_list_sub_accounts_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_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListSubAccountsResponse( @@ -2606,17 +3076,17 @@ def test_list_sub_accounts_pager(transport_name: str = "grpc"): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListSubAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListSubAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListSubAccountsResponse( accounts=[ @@ -2631,9 +3101,7 @@ def test_list_sub_accounts_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('provider', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("provider", ""),)), ) pager = client.list_sub_accounts(request={}, retry=retry, timeout=timeout) @@ -2643,8 +3111,9 @@ def test_list_sub_accounts_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accounts.Account) - for i in results) + assert all(isinstance(i, accounts.Account) for i in results) + + def test_list_sub_accounts_pages(transport_name: str = "grpc"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2653,8 +3122,8 @@ def test_list_sub_accounts_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_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListSubAccountsResponse( @@ -2663,17 +3132,17 @@ def test_list_sub_accounts_pages(transport_name: str = "grpc"): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListSubAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListSubAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListSubAccountsResponse( accounts=[ @@ -2684,9 +3153,10 @@ def test_list_sub_accounts_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_sub_accounts(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_sub_accounts_async_pager(): client = AccountsServiceAsyncClient( @@ -2695,8 +3165,10 @@ async def test_list_sub_accounts_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_sub_accounts), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListSubAccountsResponse( @@ -2705,17 +3177,17 @@ async def test_list_sub_accounts_async_pager(): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListSubAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListSubAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListSubAccountsResponse( accounts=[ @@ -2725,15 +3197,16 @@ async def test_list_sub_accounts_async_pager(): ), RuntimeError, ) - async_pager = await client.list_sub_accounts(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_sub_accounts( + 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, accounts.Account) - for i in responses) + assert all(isinstance(i, accounts.Account) for i in responses) @pytest.mark.asyncio @@ -2744,8 +3217,10 @@ async def test_list_sub_accounts_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_sub_accounts), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( accounts.ListSubAccountsResponse( @@ -2754,17 +3229,17 @@ async def test_list_sub_accounts_async_pages(): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListSubAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListSubAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListSubAccountsResponse( accounts=[ @@ -2777,11 +3252,11 @@ async def test_list_sub_accounts_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_sub_accounts(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 @@ -2803,7 +3278,9 @@ def test_get_account_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_account] = mock_rpc request = {} @@ -2826,48 +3303,51 @@ def test_get_account_rest_required_fields(request_type=accounts.GetAccountReques request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_account._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 = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accounts.Account() # Mock the http request 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 @@ -2878,24 +3358,24 @@ def test_get_account_rest_required_fields(request_type=accounts.GetAccountReques return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_account(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_account_rest_flattened(): @@ -2905,16 +3385,16 @@ def test_get_account_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 = accounts.Account() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1'} + sample_request = {"name": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2924,7 +3404,7 @@ def test_get_account_rest_flattened(): # Convert return value to protobuf type return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2934,10 +3414,12 @@ def test_get_account_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*}" % client.transport._host, args[1] + ) -def test_get_account_rest_flattened_error(transport: str = 'rest'): +def test_get_account_rest_flattened_error(transport: str = "rest"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2948,7 +3430,7 @@ def test_get_account_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_account( accounts.GetAccountRequest(), - name='name_value', + name="name_value", ) @@ -2966,12 +3448,19 @@ def test_create_and_configure_account_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_and_configure_account in client._transport._wrapped_methods + assert ( + client._transport.create_and_configure_account + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_and_configure_account] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_and_configure_account + ] = mock_rpc request = {} client.create_and_configure_account(request) @@ -2986,52 +3475,57 @@ def test_create_and_configure_account_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_and_configure_account_rest_required_fields(request_type=accounts.CreateAndConfigureAccountRequest): +def test_create_and_configure_account_rest_required_fields( + request_type=accounts.CreateAndConfigureAccountRequest, +): transport_class = transports.AccountsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_and_configure_account._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_and_configure_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_and_configure_account._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accounts.Account() # Mock the http request 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() @@ -3041,24 +3535,32 @@ def test_create_and_configure_account_rest_required_fields(request_type=accounts return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_and_configure_account(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_and_configure_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_and_configure_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("account", "service", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "account", + "service", + ) + ) + ) def test_delete_account_rest_use_cached_wrapped_rpc(): @@ -3079,7 +3581,9 @@ def test_delete_account_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc request = {} @@ -3095,82 +3599,87 @@ def test_delete_account_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_account_rest_required_fields(request_type=accounts.DeleteAccountRequest): +def test_delete_account_rest_required_fields( + request_type=accounts.DeleteAccountRequest, +): transport_class = transports.AccountsServiceRestTransport 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_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_account._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_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_account._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) + assert not set(unset_fields) - set(("force",)) 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 = AccountsServiceClient( 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_account(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_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) + assert set(unset_fields) == (set(("force",)) & set(("name",))) def test_delete_account_rest_flattened(): @@ -3180,24 +3689,24 @@ def test_delete_account_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'} + sample_request = {"name": "accounts/sample1"} # 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"} @@ -3207,10 +3716,12 @@ def test_delete_account_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*}" % client.transport._host, args[1] + ) -def test_delete_account_rest_flattened_error(transport: str = 'rest'): +def test_delete_account_rest_flattened_error(transport: str = "rest"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3221,7 +3732,7 @@ def test_delete_account_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_account( accounts.DeleteAccountRequest(), - name='name_value', + name="name_value", ) @@ -3243,7 +3754,9 @@ def test_update_account_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_account] = mock_rpc request = {} @@ -3259,54 +3772,59 @@ def test_update_account_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_account_rest_required_fields(request_type=accounts.UpdateAccountRequest): +def test_update_account_rest_required_fields( + request_type=accounts.UpdateAccountRequest, +): transport_class = transports.AccountsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_account._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_account._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accounts.Account() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3316,24 +3834,24 @@ def test_update_account_rest_required_fields(request_type=accounts.UpdateAccount return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_account(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_account_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("account", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("account",))) def test_update_account_rest_flattened(): @@ -3343,17 +3861,17 @@ def test_update_account_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 = accounts.Account() # get arguments that satisfy an http rule for this method - sample_request = {'account': {'name': 'accounts/sample1'}} + sample_request = {"account": {"name": "accounts/sample1"}} # get truthy value for each flattened field mock_args = dict( - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account=accounts.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -3363,7 +3881,7 @@ def test_update_account_rest_flattened(): # Convert return value to protobuf type return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3373,10 +3891,12 @@ def test_update_account_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{account.name=accounts/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{account.name=accounts/*}" % client.transport._host, args[1] + ) -def test_update_account_rest_flattened_error(transport: str = 'rest'): +def test_update_account_rest_flattened_error(transport: str = "rest"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3387,8 +3907,8 @@ def test_update_account_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_account( accounts.UpdateAccountRequest(), - account=accounts.Account(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + account=accounts.Account(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -3410,7 +3930,9 @@ def test_list_accounts_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc request = {} @@ -3426,16 +3948,16 @@ def test_list_accounts_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_accounts_rest_pager(transport: str = 'rest'): +def test_list_accounts_rest_pager(transport: str = "rest"): client = AccountsServiceClient( 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 = ( accounts.ListAccountsResponse( @@ -3444,17 +3966,17 @@ def test_list_accounts_rest_pager(transport: str = 'rest'): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListAccountsResponse( accounts=[ @@ -3470,7 +3992,7 @@ def test_list_accounts_rest_pager(transport: str = 'rest'): response = tuple(accounts.ListAccountsResponse.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 @@ -3480,11 +4002,10 @@ def test_list_accounts_rest_pager(transport: str = 'rest'): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accounts.Account) - for i in results) + assert all(isinstance(i, accounts.Account) for i in results) pages = list(client.list_accounts(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 @@ -3506,8 +4027,12 @@ def test_list_sub_accounts_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_sub_accounts] = 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_sub_accounts + ] = mock_rpc request = {} client.list_sub_accounts(request) @@ -3522,57 +4047,67 @@ def test_list_sub_accounts_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_sub_accounts_rest_required_fields(request_type=accounts.ListSubAccountsRequest): +def test_list_sub_accounts_rest_required_fields( + request_type=accounts.ListSubAccountsRequest, +): transport_class = transports.AccountsServiceRestTransport request_init = {} request_init["provider"] = "" 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_sub_accounts._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sub_accounts._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["provider"] = 'provider_value' + jsonified_request["provider"] = "provider_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_sub_accounts._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_sub_accounts._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 "provider" in jsonified_request - assert jsonified_request["provider"] == 'provider_value' + assert jsonified_request["provider"] == "provider_value" client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = accounts.ListSubAccountsResponse() # Mock the http request 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 @@ -3583,24 +4118,32 @@ def test_list_sub_accounts_rest_required_fields(request_type=accounts.ListSubAcc return_value = accounts.ListSubAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_sub_accounts(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_sub_accounts_rest_unset_required_fields(): - transport = transports.AccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_sub_accounts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("provider", ))) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("provider",)) + ) def test_list_sub_accounts_rest_flattened(): @@ -3610,16 +4153,16 @@ def test_list_sub_accounts_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 = accounts.ListSubAccountsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'provider': 'accounts/sample1'} + sample_request = {"provider": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - provider='provider_value', + provider="provider_value", ) mock_args.update(sample_request) @@ -3629,7 +4172,7 @@ def test_list_sub_accounts_rest_flattened(): # Convert return value to protobuf type return_value = accounts.ListSubAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3639,10 +4182,14 @@ def test_list_sub_accounts_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{provider=accounts/*}:listSubaccounts" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{provider=accounts/*}:listSubaccounts" + % client.transport._host, + args[1], + ) -def test_list_sub_accounts_rest_flattened_error(transport: str = 'rest'): +def test_list_sub_accounts_rest_flattened_error(transport: str = "rest"): client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3653,20 +4200,20 @@ def test_list_sub_accounts_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_sub_accounts( accounts.ListSubAccountsRequest(), - provider='provider_value', + provider="provider_value", ) -def test_list_sub_accounts_rest_pager(transport: str = 'rest'): +def test_list_sub_accounts_rest_pager(transport: str = "rest"): client = AccountsServiceClient( 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 = ( accounts.ListSubAccountsResponse( @@ -3675,17 +4222,17 @@ def test_list_sub_accounts_rest_pager(transport: str = 'rest'): accounts.Account(), accounts.Account(), ], - next_page_token='abc', + next_page_token="abc", ), accounts.ListSubAccountsResponse( accounts=[], - next_page_token='def', + next_page_token="def", ), accounts.ListSubAccountsResponse( accounts=[ accounts.Account(), ], - next_page_token='ghi', + next_page_token="ghi", ), accounts.ListSubAccountsResponse( accounts=[ @@ -3701,21 +4248,20 @@ def test_list_sub_accounts_rest_pager(transport: str = 'rest'): response = tuple(accounts.ListSubAccountsResponse.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 = {'provider': 'accounts/sample1'} + sample_request = {"provider": "accounts/sample1"} pager = client.list_sub_accounts(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, accounts.Account) - for i in results) + assert all(isinstance(i, accounts.Account) for i in results) pages = list(client.list_sub_accounts(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 @@ -3757,8 +4303,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AccountsServiceClient( - 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. @@ -3780,6 +4325,7 @@ def test_transport_instance(): client = AccountsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AccountsServiceGrpcTransport( @@ -3794,18 +4340,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AccountsServiceGrpcTransport, - transports.AccountsServiceGrpcAsyncIOTransport, - transports.AccountsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + transports.AccountsServiceRestTransport, + ], +) 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 = AccountsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3815,8 +4366,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3830,9 +4380,7 @@ def test_get_account_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: call.return_value = accounts.Account() client.get_account(request=None) @@ -3854,8 +4402,8 @@ def test_create_and_configure_account_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: + type(client.transport.create_and_configure_account), "__call__" + ) as call: call.return_value = accounts.Account() client.create_and_configure_account(request=None) @@ -3876,9 +4424,7 @@ def test_delete_account_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: call.return_value = None client.delete_account(request=None) @@ -3899,9 +4445,7 @@ def test_update_account_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: call.return_value = accounts.Account() client.update_account(request=None) @@ -3922,9 +4466,7 @@ def test_list_accounts_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: call.return_value = accounts.ListAccountsResponse() client.list_accounts(request=None) @@ -3946,8 +4488,8 @@ def test_list_sub_accounts_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: call.return_value = accounts.ListSubAccountsResponse() client.list_sub_accounts(request=None) @@ -3968,8 +4510,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = AccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3984,18 +4525,18 @@ async def test_get_account_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.Account( + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", + ) + ) await client.get_account(request=None) # Establish that the underlying stub method was called. @@ -4017,17 +4558,19 @@ async def test_create_and_configure_account_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: + type(client.transport.create_and_configure_account), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.Account( + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", + ) + ) await client.create_and_configure_account(request=None) # Establish that the underlying stub method was called. @@ -4048,9 +4591,7 @@ async def test_delete_account_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_account(request=None) @@ -4073,18 +4614,18 @@ async def test_update_account_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.Account( + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", + ) + ) await client.update_account(request=None) # Establish that the underlying stub method was called. @@ -4105,13 +4646,13 @@ async def test_list_accounts_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListAccountsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.ListAccountsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_accounts(request=None) # Establish that the underlying stub method was called. @@ -4133,12 +4674,14 @@ async def test_list_sub_accounts_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + accounts.ListSubAccountsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_sub_accounts(request=None) # Establish that the underlying stub method was called. @@ -4158,18 +4701,19 @@ def test_transport_kind_rest(): def test_get_account_rest_bad_request(request_type=accounts.GetAccountRequest): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} + request_init = {"name": "accounts/sample1"} 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() @@ -4178,30 +4722,32 @@ def test_get_account_rest_bad_request(request_type=accounts.GetAccountRequest): client.get_account(request) -@pytest.mark.parametrize("request_type", [ - accounts.GetAccountRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accounts.GetAccountRequest, + dict, + ], +) def test_get_account_rest_call_success(request_type): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} + request_init = {"name": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", ) # Wrap the value into a proper Response obj @@ -4211,34 +4757,42 @@ def test_get_account_rest_call_success(request_type): # Convert return value to protobuf type return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_account(request) # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_account_rest_interceptors(null_interceptor): transport = transports.AccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountsServiceRestInterceptor(), + ) client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_get_account") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_get_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_get_account") 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.AccountsServiceRestInterceptor, "post_get_account" + ) as post, mock.patch.object( + transports.AccountsServiceRestInterceptor, "post_get_account_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AccountsServiceRestInterceptor, "pre_get_account" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4257,7 +4811,7 @@ def test_get_account_rest_interceptors(null_interceptor): req.return_value.content = return_value request = accounts.GetAccountRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4265,27 +4819,36 @@ def test_get_account_rest_interceptors(null_interceptor): post.return_value = accounts.Account() post_with_metadata.return_value = accounts.Account(), metadata - client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_create_and_configure_account_rest_bad_request(request_type=accounts.CreateAndConfigureAccountRequest): +def test_create_and_configure_account_rest_bad_request( + request_type=accounts.CreateAndConfigureAccountRequest, +): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4294,14 +4857,16 @@ def test_create_and_configure_account_rest_bad_request(request_type=accounts.Cre client.create_and_configure_account(request) -@pytest.mark.parametrize("request_type", [ - accounts.CreateAndConfigureAccountRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accounts.CreateAndConfigureAccountRequest, + dict, + ], +) def test_create_and_configure_account_rest_call_success(request_type): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -4309,15 +4874,15 @@ def test_create_and_configure_account_rest_call_success(request_type): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", ) # Wrap the value into a proper Response obj @@ -4327,38 +4892,49 @@ def test_create_and_configure_account_rest_call_success(request_type): # Convert return value to protobuf type return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_and_configure_account(request) # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_and_configure_account_rest_interceptors(null_interceptor): transport = transports.AccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountsServiceRestInterceptor(), + ) client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_create_and_configure_account") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_create_and_configure_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_create_and_configure_account") 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.AccountsServiceRestInterceptor, "post_create_and_configure_account" + ) as post, mock.patch.object( + transports.AccountsServiceRestInterceptor, + "post_create_and_configure_account_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountsServiceRestInterceptor, "pre_create_and_configure_account" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accounts.CreateAndConfigureAccountRequest.pb(accounts.CreateAndConfigureAccountRequest()) + pb_message = accounts.CreateAndConfigureAccountRequest.pb( + accounts.CreateAndConfigureAccountRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4373,7 +4949,7 @@ def test_create_and_configure_account_rest_interceptors(null_interceptor): req.return_value.content = return_value request = accounts.CreateAndConfigureAccountRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4381,7 +4957,13 @@ def test_create_and_configure_account_rest_interceptors(null_interceptor): post.return_value = accounts.Account() post_with_metadata.return_value = accounts.Account(), metadata - client.create_and_configure_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_and_configure_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -4390,18 +4972,19 @@ def test_create_and_configure_account_rest_interceptors(null_interceptor): def test_delete_account_rest_bad_request(request_type=accounts.DeleteAccountRequest): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} + request_init = {"name": "accounts/sample1"} 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() @@ -4410,30 +4993,32 @@ def test_delete_account_rest_bad_request(request_type=accounts.DeleteAccountRequ client.delete_account(request) -@pytest.mark.parametrize("request_type", [ - accounts.DeleteAccountRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accounts.DeleteAccountRequest, + dict, + ], +) def test_delete_account_rest_call_success(request_type): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1'} + request_init = {"name": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + 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_account(request) @@ -4446,13 +5031,19 @@ def test_delete_account_rest_call_success(request_type): def test_delete_account_rest_interceptors(null_interceptor): transport = transports.AccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountsServiceRestInterceptor(), + ) client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "pre_delete_account") 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.AccountsServiceRestInterceptor, "pre_delete_account" + ) as pre: pre.assert_not_called() pb_message = accounts.DeleteAccountRequest.pb(accounts.DeleteAccountRequest()) transcode.return_value = { @@ -4467,31 +5058,38 @@ def test_delete_account_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = accounts.DeleteAccountRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() def test_update_account_rest_bad_request(request_type=accounts.UpdateAccountRequest): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'account': {'name': 'accounts/sample1'}} + request_init = {"account": {"name": "accounts/sample1"}} 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() @@ -4500,19 +5098,29 @@ def test_update_account_rest_bad_request(request_type=accounts.UpdateAccountRequ client.update_account(request) -@pytest.mark.parametrize("request_type", [ - accounts.UpdateAccountRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accounts.UpdateAccountRequest, + dict, + ], +) def test_update_account_rest_call_success(request_type): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'account': {'name': 'accounts/sample1'}} - request_init["account"] = {'name': 'accounts/sample1', 'account_id': 1049, 'account_name': 'account_name_value', 'adult_content': True, 'test_account': True, 'time_zone': {'id': 'id_value', 'version': 'version_value'}, 'language_code': 'language_code_value'} + request_init = {"account": {"name": "accounts/sample1"}} + request_init["account"] = { + "name": "accounts/sample1", + "account_id": 1049, + "account_name": "account_name_value", + "adult_content": True, + "test_account": True, + "time_zone": {"id": "id_value", "version": "version_value"}, + "language_code": "language_code_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 @@ -4532,7 +5140,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 @@ -4546,7 +5154,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["account"].items(): # pragma: NO COVER + for field, value in request_init["account"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4561,12 +5169,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") @@ -4579,15 +5191,15 @@ 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 = accounts.Account( - name='name_value', - account_id=1049, - account_name='account_name_value', - adult_content=True, - test_account=True, - language_code='language_code_value', + name="name_value", + account_id=1049, + account_name="account_name_value", + adult_content=True, + test_account=True, + language_code="language_code_value", ) # Wrap the value into a proper Response obj @@ -4597,34 +5209,42 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = accounts.Account.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_account(request) # Establish that the response is the type that we expect. assert isinstance(response, accounts.Account) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.account_id == 1049 - assert response.account_name == 'account_name_value' + assert response.account_name == "account_name_value" assert response.adult_content is True assert response.test_account is True - assert response.language_code == 'language_code_value' + assert response.language_code == "language_code_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_account_rest_interceptors(null_interceptor): transport = transports.AccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountsServiceRestInterceptor(), + ) client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_update_account") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_update_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_update_account") 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.AccountsServiceRestInterceptor, "post_update_account" + ) as post, mock.patch.object( + transports.AccountsServiceRestInterceptor, "post_update_account_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AccountsServiceRestInterceptor, "pre_update_account" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4643,7 +5263,7 @@ def test_update_account_rest_interceptors(null_interceptor): req.return_value.content = return_value request = accounts.UpdateAccountRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4651,7 +5271,13 @@ def test_update_account_rest_interceptors(null_interceptor): post.return_value = accounts.Account() post_with_metadata.return_value = accounts.Account(), metadata - client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -4660,18 +5286,19 @@ def test_update_account_rest_interceptors(null_interceptor): def test_list_accounts_rest_bad_request(request_type=accounts.ListAccountsRequest): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -4680,14 +5307,16 @@ def test_list_accounts_rest_bad_request(request_type=accounts.ListAccountsReques client.list_accounts(request) -@pytest.mark.parametrize("request_type", [ - accounts.ListAccountsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accounts.ListAccountsRequest, + dict, + ], +) def test_list_accounts_rest_call_success(request_type): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -4695,10 +5324,10 @@ def test_list_accounts_rest_call_success(request_type): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accounts.ListAccountsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -4708,29 +5337,37 @@ def test_list_accounts_rest_call_success(request_type): # Convert return value to protobuf type return_value = accounts.ListAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_accounts(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAccountsPager) - 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_accounts_rest_interceptors(null_interceptor): transport = transports.AccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountsServiceRestInterceptor(), + ) client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_accounts") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_accounts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_accounts") 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.AccountsServiceRestInterceptor, "post_list_accounts" + ) as post, mock.patch.object( + transports.AccountsServiceRestInterceptor, "post_list_accounts_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AccountsServiceRestInterceptor, "pre_list_accounts" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4745,11 +5382,13 @@ def test_list_accounts_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 = accounts.ListAccountsResponse.to_json(accounts.ListAccountsResponse()) + return_value = accounts.ListAccountsResponse.to_json( + accounts.ListAccountsResponse() + ) req.return_value.content = return_value request = accounts.ListAccountsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4757,27 +5396,36 @@ def test_list_accounts_rest_interceptors(null_interceptor): post.return_value = accounts.ListAccountsResponse() post_with_metadata.return_value = accounts.ListAccountsResponse(), metadata - client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_accounts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_sub_accounts_rest_bad_request(request_type=accounts.ListSubAccountsRequest): +def test_list_sub_accounts_rest_bad_request( + request_type=accounts.ListSubAccountsRequest, +): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'provider': 'accounts/sample1'} + request_init = {"provider": "accounts/sample1"} 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() @@ -4786,25 +5434,27 @@ def test_list_sub_accounts_rest_bad_request(request_type=accounts.ListSubAccount client.list_sub_accounts(request) -@pytest.mark.parametrize("request_type", [ - accounts.ListSubAccountsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + accounts.ListSubAccountsRequest, + dict, + ], +) def test_list_sub_accounts_rest_call_success(request_type): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'provider': 'accounts/sample1'} + request_init = {"provider": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = accounts.ListSubAccountsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -4814,33 +5464,44 @@ def test_list_sub_accounts_rest_call_success(request_type): # Convert return value to protobuf type return_value = accounts.ListSubAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_sub_accounts(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSubAccountsPager) - 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_sub_accounts_rest_interceptors(null_interceptor): transport = transports.AccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AccountsServiceRestInterceptor(), + ) client = AccountsServiceClient(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.AccountsServiceRestInterceptor, "post_list_sub_accounts") as post, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "post_list_sub_accounts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AccountsServiceRestInterceptor, "pre_list_sub_accounts") 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.AccountsServiceRestInterceptor, "post_list_sub_accounts" + ) as post, mock.patch.object( + transports.AccountsServiceRestInterceptor, + "post_list_sub_accounts_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AccountsServiceRestInterceptor, "pre_list_sub_accounts" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = accounts.ListSubAccountsRequest.pb(accounts.ListSubAccountsRequest()) + pb_message = accounts.ListSubAccountsRequest.pb( + accounts.ListSubAccountsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4851,11 +5512,13 @@ def test_list_sub_accounts_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 = accounts.ListSubAccountsResponse.to_json(accounts.ListSubAccountsResponse()) + return_value = accounts.ListSubAccountsResponse.to_json( + accounts.ListSubAccountsResponse() + ) req.return_value.content = return_value request = accounts.ListSubAccountsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4863,16 +5526,22 @@ def test_list_sub_accounts_rest_interceptors(null_interceptor): post.return_value = accounts.ListSubAccountsResponse() post_with_metadata.return_value = accounts.ListSubAccountsResponse(), metadata - client.list_sub_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_sub_accounts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = AccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -4886,9 +5555,7 @@ def test_get_account_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account), - '__call__') as call: + with mock.patch.object(type(client.transport.get_account), "__call__") as call: client.get_account(request=None) # Establish that the underlying stub method was called. @@ -4909,8 +5576,8 @@ def test_create_and_configure_account_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_and_configure_account), - '__call__') as call: + type(client.transport.create_and_configure_account), "__call__" + ) as call: client.create_and_configure_account(request=None) # Establish that the underlying stub method was called. @@ -4930,9 +5597,7 @@ def test_delete_account_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_account), "__call__") as call: client.delete_account(request=None) # Establish that the underlying stub method was called. @@ -4952,9 +5617,7 @@ def test_update_account_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account), - '__call__') as call: + with mock.patch.object(type(client.transport.update_account), "__call__") as call: client.update_account(request=None) # Establish that the underlying stub method was called. @@ -4974,9 +5637,7 @@ def test_list_accounts_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_accounts), - '__call__') as call: + with mock.patch.object(type(client.transport.list_accounts), "__call__") as call: client.list_accounts(request=None) # Establish that the underlying stub method was called. @@ -4997,8 +5658,8 @@ def test_list_sub_accounts_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_sub_accounts), - '__call__') as call: + type(client.transport.list_sub_accounts), "__call__" + ) as call: client.list_sub_accounts(request=None) # Establish that the underlying stub method was called. @@ -5019,18 +5680,21 @@ def test_transport_grpc_default(): transports.AccountsServiceGrpcTransport, ) + def test_accounts_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AccountsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_accounts_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AccountsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -5039,12 +5703,12 @@ def test_accounts_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_account', - 'create_and_configure_account', - 'delete_account', - 'update_account', - 'list_accounts', - 'list_sub_accounts', + "get_account", + "create_and_configure_account", + "delete_account", + "update_account", + "list_accounts", + "list_sub_accounts", ) for method in methods: with pytest.raises(NotImplementedError): @@ -5055,7 +5719,7 @@ def test_accounts_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -5064,25 +5728,30 @@ def test_accounts_service_base_transport(): def test_accounts_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_accounts_v1.services.accounts_service.transports.AccountsServiceTransport._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_accounts_v1.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountsServiceTransport( 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_accounts_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_accounts_v1.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.accounts_service.transports.AccountsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AccountsServiceTransport() @@ -5091,14 +5760,12 @@ def test_accounts_service_base_transport_with_adc(): def test_accounts_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) AccountsServiceClient() 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, ) @@ -5113,12 +5780,12 @@ def test_accounts_service_auth_adc(): def test_accounts_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", ) @@ -5132,48 +5799,45 @@ def test_accounts_service_transport_auth_adc(transport_class): ], ) def test_accounts_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.AccountsServiceGrpcTransport, grpc_helpers), - (transports.AccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.AccountsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_accounts_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, @@ -5184,10 +5848,14 @@ def test_accounts_service_transport_create_channel(transport_class, grpc_helpers ) -@pytest.mark.parametrize("transport_class", [transports.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) -def test_accounts_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + ], +) +def test_accounts_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -5196,7 +5864,7 @@ def test_accounts_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", @@ -5217,61 +5885,77 @@ def test_accounts_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_accounts_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.AccountsServiceRestTransport ( - 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.AccountsServiceRestTransport( + 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_accounts_service_host_no_port(transport_name): client = AccountsServiceClient( 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_accounts_service_host_with_port(transport_name): client = AccountsServiceClient( 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_accounts_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -5301,8 +5985,10 @@ def test_accounts_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_sub_accounts._session session2 = client2.transport.list_sub_accounts._session assert session1 != session2 + + def test_accounts_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.AccountsServiceGrpcTransport( @@ -5315,7 +6001,7 @@ def test_accounts_service_grpc_transport_channel(): def test_accounts_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.AccountsServiceGrpcAsyncIOTransport( @@ -5329,12 +6015,22 @@ def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + ], +) def test_accounts_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 @@ -5343,7 +6039,7 @@ def test_accounts_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", @@ -5373,17 +6069,23 @@ def test_accounts_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.AccountsServiceGrpcTransport, transports.AccountsServiceGrpcAsyncIOTransport]) -def test_accounts_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AccountsServiceGrpcTransport, + transports.AccountsServiceGrpcAsyncIOTransport, + ], +) +def test_accounts_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() @@ -5413,7 +6115,9 @@ def test_accounts_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = AccountsServiceClient.account_path(account) assert expected == actual @@ -5428,10 +6132,14 @@ def test_parse_account_path(): actual = AccountsServiceClient.parse_account_path(path) assert expected == actual + def test_user_path(): account = "whelk" email = "octopus" - expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) + expected = "accounts/{account}/users/{email}".format( + account=account, + email=email, + ) actual = AccountsServiceClient.user_path(account, email) assert expected == actual @@ -5447,9 +6155,12 @@ def test_parse_user_path(): actual = AccountsServiceClient.parse_user_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 = AccountsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -5464,9 +6175,12 @@ def test_parse_common_billing_account_path(): actual = AccountsServiceClient.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 = AccountsServiceClient.common_folder_path(folder) assert expected == actual @@ -5481,9 +6195,12 @@ def test_parse_common_folder_path(): actual = AccountsServiceClient.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 = AccountsServiceClient.common_organization_path(organization) assert expected == actual @@ -5498,9 +6215,12 @@ def test_parse_common_organization_path(): actual = AccountsServiceClient.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 = AccountsServiceClient.common_project_path(project) assert expected == actual @@ -5515,10 +6235,14 @@ def test_parse_common_project_path(): actual = AccountsServiceClient.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 = AccountsServiceClient.common_location_path(project, location) assert expected == actual @@ -5538,14 +6262,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.AccountsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AccountsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AccountsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AccountsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5556,10 +6284,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = AccountsServiceClient( - 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() @@ -5568,10 +6297,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AccountsServiceAsyncClient( - 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() @@ -5579,10 +6309,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AccountsServiceClient( - 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() @@ -5590,13 +6321,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AccountsServiceClient( - 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: @@ -5605,10 +6335,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AccountsServiceClient, transports.AccountsServiceGrpcTransport), - (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (AccountsServiceClient, transports.AccountsServiceGrpcTransport), + (AccountsServiceAsyncClient, transports.AccountsServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5623,7 +6357,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py index bc40953915c2..deb12b6545ee 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_autofeed_settings_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,45 +22,43 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import AutofeedSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import AutofeedSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import transports -from google.shopping.merchant_accounts_v1.types import autofeedsettings -import google.auth - +from google.shopping.merchant_accounts_v1.services.autofeed_settings_service import ( + AutofeedSettingsServiceAsyncClient, + AutofeedSettingsServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import autofeedsettings CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AutofeedSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AutofeedSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AutofeedSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AutofeedSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert AutofeedSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (True, "auto", None) + assert AutofeedSettingsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert AutofeedSettingsServiceClient._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: AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._read_environment_variables() == (False, "never", None) + assert AutofeedSettingsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "always", None) + assert AutofeedSettingsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert AutofeedSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, False) is None - assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AutofeedSettingsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + AutofeedSettingsServiceClient._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 ( + AutofeedSettingsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AutofeedSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) +@mock.patch.object( + AutofeedSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceClient), +) +@mock.patch.object( + AutofeedSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert AutofeedSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutofeedSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AutofeedSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AutofeedSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + AutofeedSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AutofeedSettingsServiceClient._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." + AutofeedSettingsServiceClient._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 AutofeedSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AutofeedSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AutofeedSettingsServiceClient._get_universe_domain(None, None) == AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + assert ( + AutofeedSettingsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AutofeedSettingsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + AutofeedSettingsServiceClient._get_universe_domain(None, None) + == AutofeedSettingsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AutofeedSettingsServiceClient._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) @@ -215,7 +370,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") @@ -228,14 +384,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", [ - (AutofeedSettingsServiceClient, "grpc"), - (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), - (AutofeedSettingsServiceClient, "rest"), -]) -def test_autofeed_settings_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AutofeedSettingsServiceClient, "grpc"), + (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), + (AutofeedSettingsServiceClient, "rest"), + ], +) +def test_autofeed_settings_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) @@ -243,52 +407,70 @@ def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, "grpc"), - (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, "grpc"), + (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutofeedSettingsServiceRestTransport, "rest"), + ], +) +def test_autofeed_settings_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", [ - (AutofeedSettingsServiceClient, "grpc"), - (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), - (AutofeedSettingsServiceClient, "rest"), -]) -def test_autofeed_settings_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AutofeedSettingsServiceClient, "grpc"), + (AutofeedSettingsServiceAsyncClient, "grpc_asyncio"), + (AutofeedSettingsServiceClient, "rest"), + ], +) +def test_autofeed_settings_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" ) @@ -304,30 +486,53 @@ def test_autofeed_settings_service_client_get_transport_class(): assert transport == transports.AutofeedSettingsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) -def test_autofeed_settings_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + "grpc", + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + AutofeedSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceClient), +) +@mock.patch.object( + AutofeedSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient), +) +def test_autofeed_settings_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(AutofeedSettingsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(AutofeedSettingsServiceClient, "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(AutofeedSettingsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(AutofeedSettingsServiceClient, "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( @@ -345,13 +550,15 @@ def test_autofeed_settings_service_client_client_options(client_class, transport # 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, @@ -363,7 +570,7 @@ def test_autofeed_settings_service_client_client_options(client_class, transport # 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( @@ -383,23 +590,33 @@ def test_autofeed_settings_service_client_client_options(client_class, transport 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", @@ -408,48 +625,102 @@ def test_autofeed_settings_service_client_client_options(client_class, transport 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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "true"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", "false"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "true"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + "grpc", + "true", + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + "grpc", + "false", + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceRestTransport, + "rest", + "true", + ), + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AutofeedSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceClient), +) +@mock.patch.object( + AutofeedSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_autofeed_settings_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_autofeed_settings_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 @@ -468,12 +739,22 @@ def test_autofeed_settings_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 @@ -494,15 +775,22 @@ def test_autofeed_settings_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, @@ -512,19 +800,33 @@ def test_autofeed_settings_service_client_mtls_env_auto(client_class, transport_ ) -@pytest.mark.parametrize("client_class", [ - AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient -]) -@mock.patch.object(AutofeedSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutofeedSettingsServiceAsyncClient)) -def test_autofeed_settings_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient] +) +@mock.patch.object( + AutofeedSettingsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AutofeedSettingsServiceClient), +) +@mock.patch.object( + AutofeedSettingsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AutofeedSettingsServiceAsyncClient), +) +def test_autofeed_settings_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 @@ -532,8 +834,12 @@ def test_autofeed_settings_service_client_get_mtls_endpoint_and_cert_source(clie 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 @@ -551,16 +857,28 @@ def test_autofeed_settings_service_client_get_mtls_endpoint_and_cert_source(clie # 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 @@ -570,34 +888,62 @@ def test_autofeed_settings_service_client_get_mtls_endpoint_and_cert_source(clie 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", [ - AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient -]) -@mock.patch.object(AutofeedSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceClient)) -@mock.patch.object(AutofeedSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient)) + +@pytest.mark.parametrize( + "client_class", [AutofeedSettingsServiceClient, AutofeedSettingsServiceAsyncClient] +) +@mock.patch.object( + AutofeedSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceClient), +) +@mock.patch.object( + AutofeedSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutofeedSettingsServiceAsyncClient), +) def test_autofeed_settings_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AutofeedSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = AutofeedSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = AutofeedSettingsServiceClient._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", @@ -620,11 +966,19 @@ def test_autofeed_settings_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. @@ -632,27 +986,48 @@ def test_autofeed_settings_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", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc"), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest"), -]) -def test_autofeed_settings_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + "grpc", + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceRestTransport, + "rest", + ), + ], +) +def test_autofeed_settings_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, @@ -661,24 +1036,45 @@ def test_autofeed_settings_service_client_client_options_scopes(client_class, tr api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceRestTransport, "rest", None), -]) -def test_autofeed_settings_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", + [ + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_autofeed_settings_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, @@ -687,11 +1083,14 @@ def test_autofeed_settings_service_client_client_options_credentials_file(client api_audience=None, ) + def test_autofeed_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AutofeedSettingsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1105,38 @@ def test_autofeed_settings_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_autofeed_settings_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", + [ + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_autofeed_settings_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, @@ -749,9 +1163,7 @@ def test_autofeed_settings_service_client_create_channel_credentials_file(client 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, @@ -762,11 +1174,14 @@ def test_autofeed_settings_service_client_create_channel_credentials_file(client ) -@pytest.mark.parametrize("request_type", [ - autofeedsettings.GetAutofeedSettingsRequest, - dict, -]) -def test_get_autofeed_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + autofeedsettings.GetAutofeedSettingsRequest, + dict, + ], +) +def test_get_autofeed_settings(request_type, transport: str = "grpc"): client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,11 +1193,11 @@ def test_get_autofeed_settings(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = autofeedsettings.AutofeedSettings( - name='name_value', + name="name_value", enable_products=True, eligible=True, ) @@ -796,7 +1211,7 @@ def test_get_autofeed_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.enable_products is True assert response.eligible is True @@ -806,28 +1221,31 @@ def test_get_autofeed_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AutofeedSettingsServiceClient( 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 = autofeedsettings.GetAutofeedSettingsRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_autofeed_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_autofeed_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == autofeedsettings.GetAutofeedSettingsRequest( - name='name_value', + name="name_value", ) + def test_get_autofeed_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -842,12 +1260,19 @@ def test_get_autofeed_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_autofeed_settings in client._transport._wrapped_methods + assert ( + client._transport.get_autofeed_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_autofeed_settings + ] = mock_rpc request = {} client.get_autofeed_settings(request) @@ -860,8 +1285,11 @@ def test_get_autofeed_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_autofeed_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_autofeed_settings_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: @@ -875,12 +1303,17 @@ async def test_get_autofeed_settings_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_autofeed_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_autofeed_settings + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_autofeed_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_autofeed_settings + ] = mock_rpc request = {} await client.get_autofeed_settings(request) @@ -894,8 +1327,12 @@ async def test_get_autofeed_settings_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.GetAutofeedSettingsRequest): +async def test_get_autofeed_settings_async( + transport: str = "grpc_asyncio", + request_type=autofeedsettings.GetAutofeedSettingsRequest, +): client = AutofeedSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -907,14 +1344,16 @@ async def test_get_autofeed_settings_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings( + name="name_value", + enable_products=True, + eligible=True, + ) + ) response = await client.get_autofeed_settings(request) # Establish that the underlying gRPC stub method was called. @@ -925,7 +1364,7 @@ async def test_get_autofeed_settings_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.enable_products is True assert response.eligible is True @@ -934,6 +1373,7 @@ async def test_get_autofeed_settings_async(transport: str = 'grpc_asyncio', requ async def test_get_autofeed_settings_async_from_dict(): await test_get_autofeed_settings_async(request_type=dict) + def test_get_autofeed_settings_field_headers(): client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -943,12 +1383,12 @@ def test_get_autofeed_settings_field_headers(): # a field header. Set these to a non-empty value. request = autofeedsettings.GetAutofeedSettingsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: call.return_value = autofeedsettings.AutofeedSettings() client.get_autofeed_settings(request) @@ -960,9 +1400,9 @@ def test_get_autofeed_settings_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 @@ -975,13 +1415,15 @@ async def test_get_autofeed_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = autofeedsettings.GetAutofeedSettingsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + type(client.transport.get_autofeed_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings() + ) await client.get_autofeed_settings(request) # Establish that the underlying gRPC stub method was called. @@ -992,9 +1434,9 @@ async def test_get_autofeed_settings_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_autofeed_settings_flattened(): @@ -1004,14 +1446,14 @@ def test_get_autofeed_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = autofeedsettings.AutofeedSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_autofeed_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1019,7 +1461,7 @@ def test_get_autofeed_settings_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 @@ -1033,9 +1475,10 @@ def test_get_autofeed_settings_flattened_error(): with pytest.raises(ValueError): client.get_autofeed_settings( autofeedsettings.GetAutofeedSettingsRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_autofeed_settings_flattened_async(): client = AutofeedSettingsServiceAsyncClient( @@ -1044,16 +1487,18 @@ async def test_get_autofeed_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = autofeedsettings.AutofeedSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_autofeed_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1061,9 +1506,10 @@ async def test_get_autofeed_settings_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_autofeed_settings_flattened_error_async(): client = AutofeedSettingsServiceAsyncClient( @@ -1075,15 +1521,18 @@ async def test_get_autofeed_settings_flattened_error_async(): with pytest.raises(ValueError): await client.get_autofeed_settings( autofeedsettings.GetAutofeedSettingsRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - autofeedsettings.UpdateAutofeedSettingsRequest, - dict, -]) -def test_update_autofeed_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + autofeedsettings.UpdateAutofeedSettingsRequest, + dict, + ], +) +def test_update_autofeed_settings(request_type, transport: str = "grpc"): client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1095,11 +1544,11 @@ def test_update_autofeed_settings(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = autofeedsettings.AutofeedSettings( - name='name_value', + name="name_value", enable_products=True, eligible=True, ) @@ -1113,7 +1562,7 @@ def test_update_autofeed_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.enable_products is True assert response.eligible is True @@ -1123,25 +1572,26 @@ def test_update_autofeed_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = AutofeedSettingsServiceClient( 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 = autofeedsettings.UpdateAutofeedSettingsRequest( - ) + request = autofeedsettings.UpdateAutofeedSettingsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_autofeed_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_autofeed_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == autofeedsettings.UpdateAutofeedSettingsRequest( - ) + assert args[0] == autofeedsettings.UpdateAutofeedSettingsRequest() + def test_update_autofeed_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1157,12 +1607,19 @@ def test_update_autofeed_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_autofeed_settings in client._transport._wrapped_methods + assert ( + client._transport.update_autofeed_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_autofeed_settings + ] = mock_rpc request = {} client.update_autofeed_settings(request) @@ -1175,8 +1632,11 @@ def test_update_autofeed_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_autofeed_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_autofeed_settings_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: @@ -1190,12 +1650,17 @@ async def test_update_autofeed_settings_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_autofeed_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_autofeed_settings + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_autofeed_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_autofeed_settings + ] = mock_rpc request = {} await client.update_autofeed_settings(request) @@ -1209,8 +1674,12 @@ async def test_update_autofeed_settings_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_autofeed_settings_async(transport: str = 'grpc_asyncio', request_type=autofeedsettings.UpdateAutofeedSettingsRequest): +async def test_update_autofeed_settings_async( + transport: str = "grpc_asyncio", + request_type=autofeedsettings.UpdateAutofeedSettingsRequest, +): client = AutofeedSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1222,14 +1691,16 @@ async def test_update_autofeed_settings_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings( + name="name_value", + enable_products=True, + eligible=True, + ) + ) response = await client.update_autofeed_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1240,7 +1711,7 @@ async def test_update_autofeed_settings_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.enable_products is True assert response.eligible is True @@ -1249,6 +1720,7 @@ async def test_update_autofeed_settings_async(transport: str = 'grpc_asyncio', r async def test_update_autofeed_settings_async_from_dict(): await test_update_autofeed_settings_async(request_type=dict) + def test_update_autofeed_settings_field_headers(): client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1258,12 +1730,12 @@ def test_update_autofeed_settings_field_headers(): # a field header. Set these to a non-empty value. request = autofeedsettings.UpdateAutofeedSettingsRequest() - request.autofeed_settings.name = 'name_value' + request.autofeed_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: call.return_value = autofeedsettings.AutofeedSettings() client.update_autofeed_settings(request) @@ -1275,9 +1747,9 @@ def test_update_autofeed_settings_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'autofeed_settings.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "autofeed_settings.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1290,13 +1762,15 @@ async def test_update_autofeed_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = autofeedsettings.UpdateAutofeedSettingsRequest() - request.autofeed_settings.name = 'name_value' + request.autofeed_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + type(client.transport.update_autofeed_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings() + ) await client.update_autofeed_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1307,9 +1781,9 @@ async def test_update_autofeed_settings_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'autofeed_settings.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "autofeed_settings.name=name_value", + ) in kw["metadata"] def test_update_autofeed_settings_flattened(): @@ -1319,15 +1793,15 @@ def test_update_autofeed_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = autofeedsettings.AutofeedSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_autofeed_settings( - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + autofeed_settings=autofeedsettings.AutofeedSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1335,10 +1809,10 @@ def test_update_autofeed_settings_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].autofeed_settings - mock_val = autofeedsettings.AutofeedSettings(name='name_value') + mock_val = autofeedsettings.AutofeedSettings(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1352,10 +1826,11 @@ def test_update_autofeed_settings_flattened_error(): with pytest.raises(ValueError): client.update_autofeed_settings( autofeedsettings.UpdateAutofeedSettingsRequest(), - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + autofeed_settings=autofeedsettings.AutofeedSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_autofeed_settings_flattened_async(): client = AutofeedSettingsServiceAsyncClient( @@ -1364,17 +1839,19 @@ async def test_update_autofeed_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = autofeedsettings.AutofeedSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_autofeed_settings( - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + autofeed_settings=autofeedsettings.AutofeedSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1382,12 +1859,13 @@ async def test_update_autofeed_settings_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].autofeed_settings - mock_val = autofeedsettings.AutofeedSettings(name='name_value') + mock_val = autofeedsettings.AutofeedSettings(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_autofeed_settings_flattened_error_async(): client = AutofeedSettingsServiceAsyncClient( @@ -1399,8 +1877,8 @@ async def test_update_autofeed_settings_flattened_error_async(): with pytest.raises(ValueError): await client.update_autofeed_settings( autofeedsettings.UpdateAutofeedSettingsRequest(), - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + autofeed_settings=autofeedsettings.AutofeedSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1418,12 +1896,19 @@ def test_get_autofeed_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_autofeed_settings in client._transport._wrapped_methods + assert ( + client._transport.get_autofeed_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_autofeed_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_autofeed_settings + ] = mock_rpc request = {} client.get_autofeed_settings(request) @@ -1438,55 +1923,60 @@ def test_get_autofeed_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_autofeed_settings_rest_required_fields(request_type=autofeedsettings.GetAutofeedSettingsRequest): +def test_get_autofeed_settings_rest_required_fields( + request_type=autofeedsettings.GetAutofeedSettingsRequest, +): transport_class = transports.AutofeedSettingsServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autofeed_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_autofeed_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autofeed_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_autofeed_settings._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 = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = autofeedsettings.AutofeedSettings() # Mock the http request 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 @@ -1497,24 +1987,24 @@ def test_get_autofeed_settings_rest_required_fields(request_type=autofeedsetting return_value = autofeedsettings.AutofeedSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_autofeed_settings(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_autofeed_settings_rest_unset_required_fields(): - transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AutofeedSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_autofeed_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_autofeed_settings_rest_flattened(): @@ -1524,16 +2014,16 @@ def test_get_autofeed_settings_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 = autofeedsettings.AutofeedSettings() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/autofeedSettings'} + sample_request = {"name": "accounts/sample1/autofeedSettings"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1543,7 +2033,7 @@ def test_get_autofeed_settings_rest_flattened(): # Convert return value to protobuf type return_value = autofeedsettings.AutofeedSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1553,10 +2043,14 @@ def test_get_autofeed_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/autofeedSettings}" + % client.transport._host, + args[1], + ) -def test_get_autofeed_settings_rest_flattened_error(transport: str = 'rest'): +def test_get_autofeed_settings_rest_flattened_error(transport: str = "rest"): client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1567,7 +2061,7 @@ def test_get_autofeed_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_autofeed_settings( autofeedsettings.GetAutofeedSettingsRequest(), - name='name_value', + name="name_value", ) @@ -1585,12 +2079,19 @@ def test_update_autofeed_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_autofeed_settings in client._transport._wrapped_methods + assert ( + client._transport.update_autofeed_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_autofeed_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_autofeed_settings + ] = mock_rpc request = {} client.update_autofeed_settings(request) @@ -1605,54 +2106,59 @@ def test_update_autofeed_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_autofeed_settings_rest_required_fields(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): +def test_update_autofeed_settings_rest_required_fields( + request_type=autofeedsettings.UpdateAutofeedSettingsRequest, +): transport_class = transports.AutofeedSettingsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_autofeed_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autofeed_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_autofeed_settings._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = autofeedsettings.AutofeedSettings() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -1662,24 +2168,32 @@ def test_update_autofeed_settings_rest_required_fields(request_type=autofeedsett return_value = autofeedsettings.AutofeedSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_autofeed_settings(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_autofeed_settings_rest_unset_required_fields(): - transport = transports.AutofeedSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AutofeedSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_autofeed_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("autofeedSettings", "updateMask", ))) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "autofeedSettings", + "updateMask", + ) + ) + ) def test_update_autofeed_settings_rest_flattened(): @@ -1689,17 +2203,19 @@ def test_update_autofeed_settings_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 = autofeedsettings.AutofeedSettings() # get arguments that satisfy an http rule for this method - sample_request = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + sample_request = { + "autofeed_settings": {"name": "accounts/sample1/autofeedSettings"} + } # get truthy value for each flattened field mock_args = dict( - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + autofeed_settings=autofeedsettings.AutofeedSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -1709,7 +2225,7 @@ def test_update_autofeed_settings_rest_flattened(): # Convert return value to protobuf type return_value = autofeedsettings.AutofeedSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1719,10 +2235,14 @@ def test_update_autofeed_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{autofeed_settings.name=accounts/*/autofeedSettings}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{autofeed_settings.name=accounts/*/autofeedSettings}" + % client.transport._host, + args[1], + ) -def test_update_autofeed_settings_rest_flattened_error(transport: str = 'rest'): +def test_update_autofeed_settings_rest_flattened_error(transport: str = "rest"): client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1733,8 +2253,8 @@ def test_update_autofeed_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_autofeed_settings( autofeedsettings.UpdateAutofeedSettingsRequest(), - autofeed_settings=autofeedsettings.AutofeedSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + autofeed_settings=autofeedsettings.AutofeedSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1776,8 +2296,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AutofeedSettingsServiceClient( - 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. @@ -1799,6 +2318,7 @@ def test_transport_instance(): client = AutofeedSettingsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AutofeedSettingsServiceGrpcTransport( @@ -1813,18 +2333,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AutofeedSettingsServiceGrpcTransport, - transports.AutofeedSettingsServiceGrpcAsyncIOTransport, - transports.AutofeedSettingsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + transports.AutofeedSettingsServiceRestTransport, + ], +) 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 = AutofeedSettingsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1834,8 +2359,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1850,8 +2374,8 @@ def test_get_autofeed_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: call.return_value = autofeedsettings.AutofeedSettings() client.get_autofeed_settings(request=None) @@ -1873,8 +2397,8 @@ def test_update_autofeed_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: call.return_value = autofeedsettings.AutofeedSettings() client.update_autofeed_settings(request=None) @@ -1895,8 +2419,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = AutofeedSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1912,14 +2435,16 @@ async def test_get_autofeed_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings( + name="name_value", + enable_products=True, + eligible=True, + ) + ) await client.get_autofeed_settings(request=None) # Establish that the underlying stub method was called. @@ -1941,14 +2466,16 @@ async def test_update_autofeed_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autofeedsettings.AutofeedSettings( + name="name_value", + enable_products=True, + eligible=True, + ) + ) await client.update_autofeed_settings(request=None) # Establish that the underlying stub method was called. @@ -1966,20 +2493,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_autofeed_settings_rest_bad_request(request_type=autofeedsettings.GetAutofeedSettingsRequest): +def test_get_autofeed_settings_rest_bad_request( + request_type=autofeedsettings.GetAutofeedSettingsRequest, +): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/autofeedSettings'} + request_init = {"name": "accounts/sample1/autofeedSettings"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -1988,27 +2518,29 @@ def test_get_autofeed_settings_rest_bad_request(request_type=autofeedsettings.Ge client.get_autofeed_settings(request) -@pytest.mark.parametrize("request_type", [ - autofeedsettings.GetAutofeedSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + autofeedsettings.GetAutofeedSettingsRequest, + dict, + ], +) def test_get_autofeed_settings_rest_call_success(request_type): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/autofeedSettings'} + request_init = {"name": "accounts/sample1/autofeedSettings"} request = request_type(**request_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 = autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, + name="name_value", + enable_products=True, + eligible=True, ) # Wrap the value into a proper Response obj @@ -2018,14 +2550,14 @@ def test_get_autofeed_settings_rest_call_success(request_type): # Convert return value to protobuf type return_value = autofeedsettings.AutofeedSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_autofeed_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.enable_products is True assert response.eligible is True @@ -2034,19 +2566,30 @@ def test_get_autofeed_settings_rest_call_success(request_type): def test_get_autofeed_settings_rest_interceptors(null_interceptor): transport = transports.AutofeedSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AutofeedSettingsServiceRestInterceptor(), + ) client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings") as post, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_get_autofeed_settings") 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.AutofeedSettingsServiceRestInterceptor, "post_get_autofeed_settings" + ) as post, mock.patch.object( + transports.AutofeedSettingsServiceRestInterceptor, + "post_get_autofeed_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AutofeedSettingsServiceRestInterceptor, "pre_get_autofeed_settings" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = autofeedsettings.GetAutofeedSettingsRequest.pb(autofeedsettings.GetAutofeedSettingsRequest()) + pb_message = autofeedsettings.GetAutofeedSettingsRequest.pb( + autofeedsettings.GetAutofeedSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2057,11 +2600,13 @@ def test_get_autofeed_settings_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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) + return_value = autofeedsettings.AutofeedSettings.to_json( + autofeedsettings.AutofeedSettings() + ) req.return_value.content = return_value request = autofeedsettings.GetAutofeedSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2069,27 +2614,36 @@ def test_get_autofeed_settings_rest_interceptors(null_interceptor): post.return_value = autofeedsettings.AutofeedSettings() post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata - client.get_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_autofeed_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_autofeed_settings_rest_bad_request(request_type=autofeedsettings.UpdateAutofeedSettingsRequest): +def test_update_autofeed_settings_rest_bad_request( + request_type=autofeedsettings.UpdateAutofeedSettingsRequest, +): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} + request_init = {"autofeed_settings": {"name": "accounts/sample1/autofeedSettings"}} 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() @@ -2098,25 +2652,33 @@ def test_update_autofeed_settings_rest_bad_request(request_type=autofeedsettings client.update_autofeed_settings(request) -@pytest.mark.parametrize("request_type", [ - autofeedsettings.UpdateAutofeedSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + autofeedsettings.UpdateAutofeedSettingsRequest, + dict, + ], +) def test_update_autofeed_settings_rest_call_success(request_type): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'autofeed_settings': {'name': 'accounts/sample1/autofeedSettings'}} - request_init["autofeed_settings"] = {'name': 'accounts/sample1/autofeedSettings', 'enable_products': True, 'eligible': True} + request_init = {"autofeed_settings": {"name": "accounts/sample1/autofeedSettings"}} + request_init["autofeed_settings"] = { + "name": "accounts/sample1/autofeedSettings", + "enable_products": True, + "eligible": True, + } # 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 = autofeedsettings.UpdateAutofeedSettingsRequest.meta.fields["autofeed_settings"] + test_field = autofeedsettings.UpdateAutofeedSettingsRequest.meta.fields[ + "autofeed_settings" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2130,7 +2692,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 @@ -2144,7 +2706,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["autofeed_settings"].items(): # pragma: NO COVER + for field, value in request_init["autofeed_settings"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2159,12 +2721,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") @@ -2177,12 +2743,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 = autofeedsettings.AutofeedSettings( - name='name_value', - enable_products=True, - eligible=True, + name="name_value", + enable_products=True, + eligible=True, ) # Wrap the value into a proper Response obj @@ -2192,14 +2758,14 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = autofeedsettings.AutofeedSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_autofeed_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, autofeedsettings.AutofeedSettings) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.enable_products is True assert response.eligible is True @@ -2208,19 +2774,32 @@ def get_message_fields(field): def test_update_autofeed_settings_rest_interceptors(null_interceptor): transport = transports.AutofeedSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutofeedSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AutofeedSettingsServiceRestInterceptor(), + ) client = AutofeedSettingsServiceClient(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.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings") as post, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "post_update_autofeed_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutofeedSettingsServiceRestInterceptor, "pre_update_autofeed_settings") 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.AutofeedSettingsServiceRestInterceptor, + "post_update_autofeed_settings", + ) as post, mock.patch.object( + transports.AutofeedSettingsServiceRestInterceptor, + "post_update_autofeed_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AutofeedSettingsServiceRestInterceptor, + "pre_update_autofeed_settings", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = autofeedsettings.UpdateAutofeedSettingsRequest.pb(autofeedsettings.UpdateAutofeedSettingsRequest()) + pb_message = autofeedsettings.UpdateAutofeedSettingsRequest.pb( + autofeedsettings.UpdateAutofeedSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2231,11 +2810,13 @@ def test_update_autofeed_settings_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 = autofeedsettings.AutofeedSettings.to_json(autofeedsettings.AutofeedSettings()) + return_value = autofeedsettings.AutofeedSettings.to_json( + autofeedsettings.AutofeedSettings() + ) req.return_value.content = return_value request = autofeedsettings.UpdateAutofeedSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2243,16 +2824,22 @@ def test_update_autofeed_settings_rest_interceptors(null_interceptor): post.return_value = autofeedsettings.AutofeedSettings() post_with_metadata.return_value = autofeedsettings.AutofeedSettings(), metadata - client.update_autofeed_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_autofeed_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2267,8 +2854,8 @@ def test_get_autofeed_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_autofeed_settings), - '__call__') as call: + type(client.transport.get_autofeed_settings), "__call__" + ) as call: client.get_autofeed_settings(request=None) # Establish that the underlying stub method was called. @@ -2289,8 +2876,8 @@ def test_update_autofeed_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_autofeed_settings), - '__call__') as call: + type(client.transport.update_autofeed_settings), "__call__" + ) as call: client.update_autofeed_settings(request=None) # Establish that the underlying stub method was called. @@ -2311,18 +2898,21 @@ def test_transport_grpc_default(): transports.AutofeedSettingsServiceGrpcTransport, ) + def test_autofeed_settings_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AutofeedSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_autofeed_settings_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AutofeedSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2331,8 +2921,8 @@ def test_autofeed_settings_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_autofeed_settings', - 'update_autofeed_settings', + "get_autofeed_settings", + "update_autofeed_settings", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2343,7 +2933,7 @@ def test_autofeed_settings_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2352,25 +2942,30 @@ def test_autofeed_settings_service_base_transport(): def test_autofeed_settings_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_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._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_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutofeedSettingsServiceTransport( 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_autofeed_settings_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_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.autofeed_settings_service.transports.AutofeedSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutofeedSettingsServiceTransport() @@ -2379,14 +2974,12 @@ def test_autofeed_settings_service_base_transport_with_adc(): def test_autofeed_settings_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) AutofeedSettingsServiceClient() 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, ) @@ -2401,12 +2994,12 @@ def test_autofeed_settings_service_auth_adc(): def test_autofeed_settings_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", ) @@ -2420,48 +3013,47 @@ def test_autofeed_settings_service_transport_auth_adc(transport_class): ], ) def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, grpc_helpers), - (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.AutofeedSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_autofeed_settings_service_transport_create_channel(transport_class, grpc_helpers): +def test_autofeed_settings_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, @@ -2472,9 +3064,15 @@ def test_autofeed_settings_service_transport_create_channel(transport_class, grp ) -@pytest.mark.parametrize("transport_class", [transports.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + ], +) def test_autofeed_settings_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2484,7 +3082,7 @@ def test_autofeed_settings_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", @@ -2505,61 +3103,77 @@ def test_autofeed_settings_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_autofeed_settings_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.AutofeedSettingsServiceRestTransport ( - 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.AutofeedSettingsServiceRestTransport( + 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_autofeed_settings_service_host_no_port(transport_name): client = AutofeedSettingsServiceClient( 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_autofeed_settings_service_host_with_port(transport_name): client = AutofeedSettingsServiceClient( 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_autofeed_settings_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2577,8 +3191,10 @@ def test_autofeed_settings_service_client_transport_session_collision(transport_ session1 = client1.transport.update_autofeed_settings._session session2 = client2.transport.update_autofeed_settings._session assert session1 != session2 + + def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport( @@ -2591,7 +3207,7 @@ def test_autofeed_settings_service_grpc_transport_channel(): def test_autofeed_settings_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.AutofeedSettingsServiceGrpcAsyncIOTransport( @@ -2605,12 +3221,22 @@ def test_autofeed_settings_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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + ], +) def test_autofeed_settings_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 @@ -2619,7 +3245,7 @@ def test_autofeed_settings_service_transport_channel_mtls_with_client_cert_sourc 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", @@ -2649,17 +3275,23 @@ def test_autofeed_settings_service_transport_channel_mtls_with_client_cert_sourc # 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.AutofeedSettingsServiceGrpcTransport, transports.AutofeedSettingsServiceGrpcAsyncIOTransport]) -def test_autofeed_settings_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutofeedSettingsServiceGrpcTransport, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_autofeed_settings_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() @@ -2689,7 +3321,9 @@ def test_autofeed_settings_service_transport_channel_mtls_with_adc( def test_autofeed_settings_path(): account = "squid" - expected = "accounts/{account}/autofeedSettings".format(account=account, ) + expected = "accounts/{account}/autofeedSettings".format( + account=account, + ) actual = AutofeedSettingsServiceClient.autofeed_settings_path(account) assert expected == actual @@ -2704,9 +3338,12 @@ def test_parse_autofeed_settings_path(): actual = AutofeedSettingsServiceClient.parse_autofeed_settings_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = AutofeedSettingsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2721,9 +3358,12 @@ def test_parse_common_billing_account_path(): actual = AutofeedSettingsServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = AutofeedSettingsServiceClient.common_folder_path(folder) assert expected == actual @@ -2738,9 +3378,12 @@ def test_parse_common_folder_path(): actual = AutofeedSettingsServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = AutofeedSettingsServiceClient.common_organization_path(organization) assert expected == actual @@ -2755,9 +3398,12 @@ def test_parse_common_organization_path(): actual = AutofeedSettingsServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = AutofeedSettingsServiceClient.common_project_path(project) assert expected == actual @@ -2772,10 +3418,14 @@ def test_parse_common_project_path(): actual = AutofeedSettingsServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = AutofeedSettingsServiceClient.common_location_path(project, location) assert expected == actual @@ -2795,14 +3445,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.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AutofeedSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AutofeedSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AutofeedSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AutofeedSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AutofeedSettingsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2813,10 +3467,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -2825,10 +3480,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AutofeedSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() @@ -2836,10 +3492,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -2847,13 +3504,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AutofeedSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -2862,10 +3518,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AutofeedSettingsServiceClient, transports.AutofeedSettingsServiceGrpcTransport), - (AutofeedSettingsServiceAsyncClient, transports.AutofeedSettingsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + AutofeedSettingsServiceClient, + transports.AutofeedSettingsServiceGrpcTransport, + ), + ( + AutofeedSettingsServiceAsyncClient, + transports.AutofeedSettingsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2880,7 +3546,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py index e2dd6637a920..909977336288 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_automatic_improvements_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,45 +22,43 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import AutomaticImprovementsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import AutomaticImprovementsServiceClient -from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import transports -from google.shopping.merchant_accounts_v1.types import automaticimprovements -import google.auth - +from google.shopping.merchant_accounts_v1.services.automatic_improvements_service import ( + AutomaticImprovementsServiceAsyncClient, + AutomaticImprovementsServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import automaticimprovements CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,255 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(None) is None - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AutomaticImprovementsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + AutomaticImprovementsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AutomaticImprovementsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AutomaticImprovementsServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + AutomaticImprovementsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + assert AutomaticImprovementsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (True, "auto", None) + assert AutomaticImprovementsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + assert AutomaticImprovementsServiceClient._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: AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._read_environment_variables() == (False, "never", None) + assert AutomaticImprovementsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "always", None) + assert AutomaticImprovementsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", None) + assert AutomaticImprovementsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, False) is None - assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + AutomaticImprovementsServiceClient._get_client_cert_source(None, False) is None + ) + assert ( + AutomaticImprovementsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + AutomaticImprovementsServiceClient._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 ( + AutomaticImprovementsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AutomaticImprovementsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +@mock.patch.object( + AutomaticImprovementsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceClient), +) +@mock.patch.object( + AutomaticImprovementsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) - assert AutomaticImprovementsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AutomaticImprovementsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AutomaticImprovementsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + AutomaticImprovementsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - AutomaticImprovementsServiceClient._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." + AutomaticImprovementsServiceClient._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 AutomaticImprovementsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AutomaticImprovementsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AutomaticImprovementsServiceClient._get_universe_domain(None, None) == AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + assert ( + AutomaticImprovementsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AutomaticImprovementsServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + AutomaticImprovementsServiceClient._get_universe_domain(None, None) + == AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: AutomaticImprovementsServiceClient._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) @@ -215,7 +380,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") @@ -228,14 +394,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", [ - (AutomaticImprovementsServiceClient, "grpc"), - (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, "rest"), -]) -def test_automatic_improvements_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AutomaticImprovementsServiceClient, "grpc"), + (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, "rest"), + ], +) +def test_automatic_improvements_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) @@ -243,52 +417,70 @@ def test_automatic_improvements_service_client_from_service_account_info(client_ 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.AutomaticImprovementsServiceGrpcTransport, "grpc"), - (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AutomaticImprovementsServiceRestTransport, "rest"), -]) -def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, "grpc"), + (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutomaticImprovementsServiceRestTransport, "rest"), + ], +) +def test_automatic_improvements_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", [ - (AutomaticImprovementsServiceClient, "grpc"), - (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, "rest"), -]) -def test_automatic_improvements_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AutomaticImprovementsServiceClient, "grpc"), + (AutomaticImprovementsServiceAsyncClient, "grpc_asyncio"), + (AutomaticImprovementsServiceClient, "rest"), + ], +) +def test_automatic_improvements_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" ) @@ -304,30 +496,57 @@ def test_automatic_improvements_service_client_get_transport_class(): assert transport == transports.AutomaticImprovementsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) -def test_automatic_improvements_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + "grpc", + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + AutomaticImprovementsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceClient), +) +@mock.patch.object( + AutomaticImprovementsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient), +) +def test_automatic_improvements_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(AutomaticImprovementsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + AutomaticImprovementsServiceClient, "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(AutomaticImprovementsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + AutomaticImprovementsServiceClient, "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( @@ -345,13 +564,15 @@ def test_automatic_improvements_service_client_client_options(client_class, tran # 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, @@ -363,7 +584,7 @@ def test_automatic_improvements_service_client_client_options(client_class, tran # 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( @@ -383,23 +604,33 @@ def test_automatic_improvements_service_client_client_options(client_class, tran 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", @@ -408,48 +639,102 @@ def test_automatic_improvements_service_client_client_options(client_class, tran 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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "true"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", "false"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "true"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + "grpc", + "true", + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + "grpc", + "false", + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceRestTransport, + "rest", + "true", + ), + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + AutomaticImprovementsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceClient), +) +@mock.patch.object( + AutomaticImprovementsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_automatic_improvements_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_automatic_improvements_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 @@ -468,12 +753,22 @@ def test_automatic_improvements_service_client_mtls_env_auto(client_class, trans # 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 @@ -494,15 +789,22 @@ def test_automatic_improvements_service_client_mtls_env_auto(client_class, trans ) # 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, @@ -512,19 +814,34 @@ def test_automatic_improvements_service_client_mtls_env_auto(client_class, trans ) -@pytest.mark.parametrize("client_class", [ - AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutomaticImprovementsServiceAsyncClient)) -def test_automatic_improvements_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient], +) +@mock.patch.object( + AutomaticImprovementsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AutomaticImprovementsServiceClient), +) +@mock.patch.object( + AutomaticImprovementsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AutomaticImprovementsServiceAsyncClient), +) +def test_automatic_improvements_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 @@ -532,8 +849,12 @@ def test_automatic_improvements_service_client_get_mtls_endpoint_and_cert_source 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 @@ -551,16 +872,28 @@ def test_automatic_improvements_service_client_get_mtls_endpoint_and_cert_source # 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 @@ -570,34 +903,67 @@ def test_automatic_improvements_service_client_get_mtls_endpoint_and_cert_source 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", [ - AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient -]) -@mock.patch.object(AutomaticImprovementsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceClient)) -@mock.patch.object(AutomaticImprovementsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [AutomaticImprovementsServiceClient, AutomaticImprovementsServiceAsyncClient], +) +@mock.patch.object( + AutomaticImprovementsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceClient), +) +@mock.patch.object( + AutomaticImprovementsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AutomaticImprovementsServiceAsyncClient), +) def test_automatic_improvements_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = AutomaticImprovementsServiceClient._DEFAULT_UNIVERSE - default_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = AutomaticImprovementsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + AutomaticImprovementsServiceClient._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", @@ -620,11 +986,19 @@ def test_automatic_improvements_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. @@ -632,27 +1006,48 @@ def test_automatic_improvements_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", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc"), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest"), -]) -def test_automatic_improvements_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + "grpc", + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceRestTransport, + "rest", + ), + ], +) +def test_automatic_improvements_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, @@ -661,24 +1056,45 @@ def test_automatic_improvements_service_client_client_options_scopes(client_clas api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceRestTransport, "rest", None), -]) -def test_automatic_improvements_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", + [ + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_automatic_improvements_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, @@ -687,11 +1103,14 @@ def test_automatic_improvements_service_client_client_options_credentials_file(c api_audience=None, ) + def test_automatic_improvements_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = AutomaticImprovementsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1125,38 @@ def test_automatic_improvements_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport, "grpc", grpc_helpers), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_automatic_improvements_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", + [ + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_automatic_improvements_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, @@ -749,9 +1183,7 @@ def test_automatic_improvements_service_client_create_channel_credentials_file(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, @@ -762,11 +1194,14 @@ def test_automatic_improvements_service_client_create_channel_credentials_file(c ) -@pytest.mark.parametrize("request_type", [ - automaticimprovements.GetAutomaticImprovementsRequest, - dict, -]) -def test_get_automatic_improvements(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + automaticimprovements.GetAutomaticImprovementsRequest, + dict, + ], +) +def test_get_automatic_improvements(request_type, transport: str = "grpc"): client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,11 +1213,11 @@ def test_get_automatic_improvements(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = automaticimprovements.AutomaticImprovements( - name='name_value', + name="name_value", ) response = client.get_automatic_improvements(request) @@ -794,7 +1229,7 @@ def test_get_automatic_improvements(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' + assert response.name == "name_value" def test_get_automatic_improvements_non_empty_request_with_auto_populated_field(): @@ -802,28 +1237,31 @@ def test_get_automatic_improvements_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = AutomaticImprovementsServiceClient( 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 = automaticimprovements.GetAutomaticImprovementsRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_automatic_improvements), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_automatic_improvements(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == automaticimprovements.GetAutomaticImprovementsRequest( - name='name_value', + name="name_value", ) + def test_get_automatic_improvements_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -838,12 +1276,19 @@ def test_get_automatic_improvements_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_automatic_improvements in client._transport._wrapped_methods + assert ( + client._transport.get_automatic_improvements + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_automatic_improvements + ] = mock_rpc request = {} client.get_automatic_improvements(request) @@ -856,8 +1301,11 @@ def test_get_automatic_improvements_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_automatic_improvements_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_automatic_improvements_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: @@ -871,12 +1319,17 @@ async def test_get_automatic_improvements_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_automatic_improvements in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_automatic_improvements + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_automatic_improvements] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_automatic_improvements + ] = mock_rpc request = {} await client.get_automatic_improvements(request) @@ -890,8 +1343,12 @@ async def test_get_automatic_improvements_async_use_cached_wrapped_rpc(transport assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.GetAutomaticImprovementsRequest): +async def test_get_automatic_improvements_async( + transport: str = "grpc_asyncio", + request_type=automaticimprovements.GetAutomaticImprovementsRequest, +): client = AutomaticImprovementsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -903,12 +1360,14 @@ async def test_get_automatic_improvements_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements( + name="name_value", + ) + ) response = await client.get_automatic_improvements(request) # Establish that the underlying gRPC stub method was called. @@ -919,13 +1378,14 @@ async def test_get_automatic_improvements_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' + assert response.name == "name_value" @pytest.mark.asyncio async def test_get_automatic_improvements_async_from_dict(): await test_get_automatic_improvements_async(request_type=dict) + def test_get_automatic_improvements_field_headers(): client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -935,12 +1395,12 @@ def test_get_automatic_improvements_field_headers(): # a field header. Set these to a non-empty value. request = automaticimprovements.GetAutomaticImprovementsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: call.return_value = automaticimprovements.AutomaticImprovements() client.get_automatic_improvements(request) @@ -952,9 +1412,9 @@ def test_get_automatic_improvements_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 @@ -967,13 +1427,15 @@ async def test_get_automatic_improvements_field_headers_async(): # a field header. Set these to a non-empty value. request = automaticimprovements.GetAutomaticImprovementsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + type(client.transport.get_automatic_improvements), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements() + ) await client.get_automatic_improvements(request) # Establish that the underlying gRPC stub method was called. @@ -984,9 +1446,9 @@ async def test_get_automatic_improvements_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_automatic_improvements_flattened(): @@ -996,14 +1458,14 @@ def test_get_automatic_improvements_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = automaticimprovements.AutomaticImprovements() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_automatic_improvements( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1011,7 +1473,7 @@ def test_get_automatic_improvements_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 @@ -1025,9 +1487,10 @@ def test_get_automatic_improvements_flattened_error(): with pytest.raises(ValueError): client.get_automatic_improvements( automaticimprovements.GetAutomaticImprovementsRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_automatic_improvements_flattened_async(): client = AutomaticImprovementsServiceAsyncClient( @@ -1036,16 +1499,18 @@ async def test_get_automatic_improvements_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = automaticimprovements.AutomaticImprovements() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_automatic_improvements( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1053,9 +1518,10 @@ async def test_get_automatic_improvements_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_automatic_improvements_flattened_error_async(): client = AutomaticImprovementsServiceAsyncClient( @@ -1067,15 +1533,18 @@ async def test_get_automatic_improvements_flattened_error_async(): with pytest.raises(ValueError): await client.get_automatic_improvements( automaticimprovements.GetAutomaticImprovementsRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - automaticimprovements.UpdateAutomaticImprovementsRequest, - dict, -]) -def test_update_automatic_improvements(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + automaticimprovements.UpdateAutomaticImprovementsRequest, + dict, + ], +) +def test_update_automatic_improvements(request_type, transport: str = "grpc"): client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1087,11 +1556,11 @@ def test_update_automatic_improvements(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = automaticimprovements.AutomaticImprovements( - name='name_value', + name="name_value", ) response = client.update_automatic_improvements(request) @@ -1103,7 +1572,7 @@ def test_update_automatic_improvements(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' + assert response.name == "name_value" def test_update_automatic_improvements_non_empty_request_with_auto_populated_field(): @@ -1111,25 +1580,26 @@ def test_update_automatic_improvements_non_empty_request_with_auto_populated_fie # automatically populated, according to AIP-4235, with non-empty requests. client = AutomaticImprovementsServiceClient( 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 = automaticimprovements.UpdateAutomaticImprovementsRequest( - ) + request = automaticimprovements.UpdateAutomaticImprovementsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_automatic_improvements), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_automatic_improvements(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == automaticimprovements.UpdateAutomaticImprovementsRequest( - ) + assert args[0] == automaticimprovements.UpdateAutomaticImprovementsRequest() + def test_update_automatic_improvements_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1145,12 +1615,19 @@ def test_update_automatic_improvements_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_automatic_improvements in client._transport._wrapped_methods + assert ( + client._transport.update_automatic_improvements + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_automatic_improvements + ] = mock_rpc request = {} client.update_automatic_improvements(request) @@ -1163,8 +1640,11 @@ def test_update_automatic_improvements_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_automatic_improvements_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_automatic_improvements_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: @@ -1178,12 +1658,17 @@ async def test_update_automatic_improvements_async_use_cached_wrapped_rpc(transp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_automatic_improvements in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_automatic_improvements + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_automatic_improvements] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_automatic_improvements + ] = mock_rpc request = {} await client.update_automatic_improvements(request) @@ -1197,8 +1682,12 @@ async def test_update_automatic_improvements_async_use_cached_wrapped_rpc(transp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_automatic_improvements_async(transport: str = 'grpc_asyncio', request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): +async def test_update_automatic_improvements_async( + transport: str = "grpc_asyncio", + request_type=automaticimprovements.UpdateAutomaticImprovementsRequest, +): client = AutomaticImprovementsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1210,12 +1699,14 @@ async def test_update_automatic_improvements_async(transport: str = 'grpc_asynci # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements( + name="name_value", + ) + ) response = await client.update_automatic_improvements(request) # Establish that the underlying gRPC stub method was called. @@ -1226,13 +1717,14 @@ async def test_update_automatic_improvements_async(transport: str = 'grpc_asynci # Establish that the response is the type that we expect. assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' + assert response.name == "name_value" @pytest.mark.asyncio async def test_update_automatic_improvements_async_from_dict(): await test_update_automatic_improvements_async(request_type=dict) + def test_update_automatic_improvements_field_headers(): client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1242,12 +1734,12 @@ def test_update_automatic_improvements_field_headers(): # a field header. Set these to a non-empty value. request = automaticimprovements.UpdateAutomaticImprovementsRequest() - request.automatic_improvements.name = 'name_value' + request.automatic_improvements.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: call.return_value = automaticimprovements.AutomaticImprovements() client.update_automatic_improvements(request) @@ -1259,9 +1751,9 @@ def test_update_automatic_improvements_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'automatic_improvements.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "automatic_improvements.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1274,13 +1766,15 @@ async def test_update_automatic_improvements_field_headers_async(): # a field header. Set these to a non-empty value. request = automaticimprovements.UpdateAutomaticImprovementsRequest() - request.automatic_improvements.name = 'name_value' + request.automatic_improvements.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + type(client.transport.update_automatic_improvements), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements() + ) await client.update_automatic_improvements(request) # Establish that the underlying gRPC stub method was called. @@ -1291,9 +1785,9 @@ async def test_update_automatic_improvements_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'automatic_improvements.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "automatic_improvements.name=name_value", + ) in kw["metadata"] def test_update_automatic_improvements_flattened(): @@ -1303,15 +1797,17 @@ def test_update_automatic_improvements_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = automaticimprovements.AutomaticImprovements() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_automatic_improvements( - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + automatic_improvements=automaticimprovements.AutomaticImprovements( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1319,10 +1815,10 @@ def test_update_automatic_improvements_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].automatic_improvements - mock_val = automaticimprovements.AutomaticImprovements(name='name_value') + mock_val = automaticimprovements.AutomaticImprovements(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1336,10 +1832,13 @@ def test_update_automatic_improvements_flattened_error(): with pytest.raises(ValueError): client.update_automatic_improvements( automaticimprovements.UpdateAutomaticImprovementsRequest(), - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + automatic_improvements=automaticimprovements.AutomaticImprovements( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_automatic_improvements_flattened_async(): client = AutomaticImprovementsServiceAsyncClient( @@ -1348,17 +1847,21 @@ async def test_update_automatic_improvements_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = automaticimprovements.AutomaticImprovements() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_automatic_improvements( - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + automatic_improvements=automaticimprovements.AutomaticImprovements( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1366,12 +1869,13 @@ async def test_update_automatic_improvements_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].automatic_improvements - mock_val = automaticimprovements.AutomaticImprovements(name='name_value') + mock_val = automaticimprovements.AutomaticImprovements(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_automatic_improvements_flattened_error_async(): client = AutomaticImprovementsServiceAsyncClient( @@ -1383,8 +1887,10 @@ async def test_update_automatic_improvements_flattened_error_async(): with pytest.raises(ValueError): await client.update_automatic_improvements( automaticimprovements.UpdateAutomaticImprovementsRequest(), - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + automatic_improvements=automaticimprovements.AutomaticImprovements( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1402,12 +1908,19 @@ def test_get_automatic_improvements_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_automatic_improvements in client._transport._wrapped_methods + assert ( + client._transport.get_automatic_improvements + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_automatic_improvements] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_automatic_improvements + ] = mock_rpc request = {} client.get_automatic_improvements(request) @@ -1422,55 +1935,60 @@ def test_get_automatic_improvements_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_automatic_improvements_rest_required_fields(request_type=automaticimprovements.GetAutomaticImprovementsRequest): +def test_get_automatic_improvements_rest_required_fields( + request_type=automaticimprovements.GetAutomaticImprovementsRequest, +): transport_class = transports.AutomaticImprovementsServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_automatic_improvements._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_automatic_improvements._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_automatic_improvements._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_automatic_improvements._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 = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = automaticimprovements.AutomaticImprovements() # Mock the http request 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 @@ -1481,24 +1999,24 @@ def test_get_automatic_improvements_rest_required_fields(request_type=automatici return_value = automaticimprovements.AutomaticImprovements.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_automatic_improvements(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_automatic_improvements_rest_unset_required_fields(): - transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AutomaticImprovementsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_automatic_improvements._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_automatic_improvements_rest_flattened(): @@ -1508,16 +2026,16 @@ def test_get_automatic_improvements_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 = automaticimprovements.AutomaticImprovements() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/automaticImprovements'} + sample_request = {"name": "accounts/sample1/automaticImprovements"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1527,7 +2045,7 @@ def test_get_automatic_improvements_rest_flattened(): # Convert return value to protobuf type return_value = automaticimprovements.AutomaticImprovements.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1537,10 +2055,14 @@ def test_get_automatic_improvements_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/automaticImprovements}" + % client.transport._host, + args[1], + ) -def test_get_automatic_improvements_rest_flattened_error(transport: str = 'rest'): +def test_get_automatic_improvements_rest_flattened_error(transport: str = "rest"): client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1551,7 +2073,7 @@ def test_get_automatic_improvements_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.get_automatic_improvements( automaticimprovements.GetAutomaticImprovementsRequest(), - name='name_value', + name="name_value", ) @@ -1569,12 +2091,19 @@ def test_update_automatic_improvements_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_automatic_improvements in client._transport._wrapped_methods + assert ( + client._transport.update_automatic_improvements + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_automatic_improvements] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_automatic_improvements + ] = mock_rpc request = {} client.update_automatic_improvements(request) @@ -1589,54 +2118,59 @@ def test_update_automatic_improvements_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_automatic_improvements_rest_required_fields(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): +def test_update_automatic_improvements_rest_required_fields( + request_type=automaticimprovements.UpdateAutomaticImprovementsRequest, +): transport_class = transports.AutomaticImprovementsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_automatic_improvements._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_automatic_improvements._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_automatic_improvements._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = automaticimprovements.AutomaticImprovements() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -1646,24 +2180,34 @@ def test_update_automatic_improvements_rest_required_fields(request_type=automat return_value = automaticimprovements.AutomaticImprovements.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_automatic_improvements(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_automatic_improvements_rest_unset_required_fields(): - transport = transports.AutomaticImprovementsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.AutomaticImprovementsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.update_automatic_improvements._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("automaticImprovements", "updateMask", ))) + unset_fields = transport.update_automatic_improvements._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "automaticImprovements", + "updateMask", + ) + ) + ) def test_update_automatic_improvements_rest_flattened(): @@ -1673,17 +2217,21 @@ def test_update_automatic_improvements_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 = automaticimprovements.AutomaticImprovements() # get arguments that satisfy an http rule for this method - sample_request = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + sample_request = { + "automatic_improvements": {"name": "accounts/sample1/automaticImprovements"} + } # get truthy value for each flattened field mock_args = dict( - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + automatic_improvements=automaticimprovements.AutomaticImprovements( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -1693,7 +2241,7 @@ def test_update_automatic_improvements_rest_flattened(): # Convert return value to protobuf type return_value = automaticimprovements.AutomaticImprovements.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1703,10 +2251,14 @@ def test_update_automatic_improvements_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{automatic_improvements.name=accounts/*/automaticImprovements}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{automatic_improvements.name=accounts/*/automaticImprovements}" + % client.transport._host, + args[1], + ) -def test_update_automatic_improvements_rest_flattened_error(transport: str = 'rest'): +def test_update_automatic_improvements_rest_flattened_error(transport: str = "rest"): client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1717,8 +2269,10 @@ def test_update_automatic_improvements_rest_flattened_error(transport: str = 're with pytest.raises(ValueError): client.update_automatic_improvements( automaticimprovements.UpdateAutomaticImprovementsRequest(), - automatic_improvements=automaticimprovements.AutomaticImprovements(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + automatic_improvements=automaticimprovements.AutomaticImprovements( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1760,8 +2314,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = AutomaticImprovementsServiceClient( - 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. @@ -1783,6 +2336,7 @@ def test_transport_instance(): client = AutomaticImprovementsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AutomaticImprovementsServiceGrpcTransport( @@ -1797,18 +2351,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.AutomaticImprovementsServiceGrpcTransport, - transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, - transports.AutomaticImprovementsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + transports.AutomaticImprovementsServiceRestTransport, + ], +) 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 = AutomaticImprovementsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1818,8 +2377,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1834,8 +2392,8 @@ def test_get_automatic_improvements_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: call.return_value = automaticimprovements.AutomaticImprovements() client.get_automatic_improvements(request=None) @@ -1857,8 +2415,8 @@ def test_update_automatic_improvements_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: call.return_value = automaticimprovements.AutomaticImprovements() client.update_automatic_improvements(request=None) @@ -1871,16 +2429,15 @@ def test_update_automatic_improvements_empty_call_grpc(): def test_transport_kind_grpc_asyncio(): - transport = AutomaticImprovementsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = AutomaticImprovementsServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = AutomaticImprovementsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1896,12 +2453,14 @@ async def test_get_automatic_improvements_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements( + name="name_value", + ) + ) await client.get_automatic_improvements(request=None) # Establish that the underlying stub method was called. @@ -1923,12 +2482,14 @@ async def test_update_automatic_improvements_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(automaticimprovements.AutomaticImprovements( - name='name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + automaticimprovements.AutomaticImprovements( + name="name_value", + ) + ) await client.update_automatic_improvements(request=None) # Establish that the underlying stub method was called. @@ -1946,20 +2507,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_automatic_improvements_rest_bad_request(request_type=automaticimprovements.GetAutomaticImprovementsRequest): +def test_get_automatic_improvements_rest_bad_request( + request_type=automaticimprovements.GetAutomaticImprovementsRequest, +): client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/automaticImprovements'} + request_init = {"name": "accounts/sample1/automaticImprovements"} 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() @@ -1968,25 +2532,27 @@ def test_get_automatic_improvements_rest_bad_request(request_type=automaticimpro client.get_automatic_improvements(request) -@pytest.mark.parametrize("request_type", [ - automaticimprovements.GetAutomaticImprovementsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + automaticimprovements.GetAutomaticImprovementsRequest, + dict, + ], +) def test_get_automatic_improvements_rest_call_success(request_type): client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/automaticImprovements'} + request_init = {"name": "accounts/sample1/automaticImprovements"} request = request_type(**request_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 = automaticimprovements.AutomaticImprovements( - name='name_value', + name="name_value", ) # Wrap the value into a proper Response obj @@ -1996,33 +2562,46 @@ def test_get_automatic_improvements_rest_call_success(request_type): # Convert return value to protobuf type return_value = automaticimprovements.AutomaticImprovements.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_automatic_improvements(request) # Establish that the response is the type that we expect. assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_automatic_improvements_rest_interceptors(null_interceptor): transport = transports.AutomaticImprovementsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AutomaticImprovementsServiceRestInterceptor(), + ) client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements") as post, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_get_automatic_improvements_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_get_automatic_improvements") 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.AutomaticImprovementsServiceRestInterceptor, + "post_get_automatic_improvements", + ) as post, mock.patch.object( + transports.AutomaticImprovementsServiceRestInterceptor, + "post_get_automatic_improvements_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AutomaticImprovementsServiceRestInterceptor, + "pre_get_automatic_improvements", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = automaticimprovements.GetAutomaticImprovementsRequest.pb(automaticimprovements.GetAutomaticImprovementsRequest()) + pb_message = automaticimprovements.GetAutomaticImprovementsRequest.pb( + automaticimprovements.GetAutomaticImprovementsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2033,39 +2612,55 @@ def test_get_automatic_improvements_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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) + return_value = automaticimprovements.AutomaticImprovements.to_json( + automaticimprovements.AutomaticImprovements() + ) req.return_value.content = return_value request = automaticimprovements.GetAutomaticImprovementsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = automaticimprovements.AutomaticImprovements() - post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata + post_with_metadata.return_value = ( + automaticimprovements.AutomaticImprovements(), + metadata, + ) - client.get_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_automatic_improvements( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_automatic_improvements_rest_bad_request(request_type=automaticimprovements.UpdateAutomaticImprovementsRequest): +def test_update_automatic_improvements_rest_bad_request( + request_type=automaticimprovements.UpdateAutomaticImprovementsRequest, +): client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} + request_init = { + "automatic_improvements": {"name": "accounts/sample1/automaticImprovements"} + } 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() @@ -2074,25 +2669,52 @@ def test_update_automatic_improvements_rest_bad_request(request_type=automaticim client.update_automatic_improvements(request) -@pytest.mark.parametrize("request_type", [ - automaticimprovements.UpdateAutomaticImprovementsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + automaticimprovements.UpdateAutomaticImprovementsRequest, + dict, + ], +) def test_update_automatic_improvements_rest_call_success(request_type): client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'automatic_improvements': {'name': 'accounts/sample1/automaticImprovements'}} - request_init["automatic_improvements"] = {'name': 'accounts/sample1/automaticImprovements', 'item_updates': {'account_item_updates_settings': {'allow_price_updates': True, 'allow_availability_updates': True, 'allow_strict_availability_updates': True, 'allow_condition_updates': True}, 'effective_allow_price_updates': True, 'effective_allow_availability_updates': True, 'effective_allow_strict_availability_updates': True, 'effective_allow_condition_updates': True}, 'image_improvements': {'account_image_improvements_settings': {'allow_automatic_image_improvements': True}, 'effective_allow_automatic_image_improvements': True}, 'shipping_improvements': {'allow_shipping_improvements': True}} + request_init = { + "automatic_improvements": {"name": "accounts/sample1/automaticImprovements"} + } + request_init["automatic_improvements"] = { + "name": "accounts/sample1/automaticImprovements", + "item_updates": { + "account_item_updates_settings": { + "allow_price_updates": True, + "allow_availability_updates": True, + "allow_strict_availability_updates": True, + "allow_condition_updates": True, + }, + "effective_allow_price_updates": True, + "effective_allow_availability_updates": True, + "effective_allow_strict_availability_updates": True, + "effective_allow_condition_updates": True, + }, + "image_improvements": { + "account_image_improvements_settings": { + "allow_automatic_image_improvements": True + }, + "effective_allow_automatic_image_improvements": True, + }, + "shipping_improvements": {"allow_shipping_improvements": True}, + } # 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 = automaticimprovements.UpdateAutomaticImprovementsRequest.meta.fields["automatic_improvements"] + test_field = automaticimprovements.UpdateAutomaticImprovementsRequest.meta.fields[ + "automatic_improvements" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2106,7 +2728,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 @@ -2120,7 +2742,9 @@ 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["automatic_improvements"].items(): # pragma: NO COVER + for field, value in request_init[ + "automatic_improvements" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2135,12 +2759,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") @@ -2153,10 +2781,10 @@ 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 = automaticimprovements.AutomaticImprovements( - name='name_value', + name="name_value", ) # Wrap the value into a proper Response obj @@ -2166,33 +2794,46 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = automaticimprovements.AutomaticImprovements.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_automatic_improvements(request) # Establish that the response is the type that we expect. assert isinstance(response, automaticimprovements.AutomaticImprovements) - assert response.name == 'name_value' + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_automatic_improvements_rest_interceptors(null_interceptor): transport = transports.AutomaticImprovementsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutomaticImprovementsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.AutomaticImprovementsServiceRestInterceptor(), + ) client = AutomaticImprovementsServiceClient(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.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements") as post, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "post_update_automatic_improvements_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.AutomaticImprovementsServiceRestInterceptor, "pre_update_automatic_improvements") 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.AutomaticImprovementsServiceRestInterceptor, + "post_update_automatic_improvements", + ) as post, mock.patch.object( + transports.AutomaticImprovementsServiceRestInterceptor, + "post_update_automatic_improvements_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AutomaticImprovementsServiceRestInterceptor, + "pre_update_automatic_improvements", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = automaticimprovements.UpdateAutomaticImprovementsRequest.pb(automaticimprovements.UpdateAutomaticImprovementsRequest()) + pb_message = automaticimprovements.UpdateAutomaticImprovementsRequest.pb( + automaticimprovements.UpdateAutomaticImprovementsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2203,28 +2844,39 @@ def test_update_automatic_improvements_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 = automaticimprovements.AutomaticImprovements.to_json(automaticimprovements.AutomaticImprovements()) + return_value = automaticimprovements.AutomaticImprovements.to_json( + automaticimprovements.AutomaticImprovements() + ) req.return_value.content = return_value request = automaticimprovements.UpdateAutomaticImprovementsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = automaticimprovements.AutomaticImprovements() - post_with_metadata.return_value = automaticimprovements.AutomaticImprovements(), metadata + post_with_metadata.return_value = ( + automaticimprovements.AutomaticImprovements(), + metadata, + ) - client.update_automatic_improvements(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_automatic_improvements( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = AutomaticImprovementsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2239,8 +2891,8 @@ def test_get_automatic_improvements_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_automatic_improvements), - '__call__') as call: + type(client.transport.get_automatic_improvements), "__call__" + ) as call: client.get_automatic_improvements(request=None) # Establish that the underlying stub method was called. @@ -2261,8 +2913,8 @@ def test_update_automatic_improvements_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_automatic_improvements), - '__call__') as call: + type(client.transport.update_automatic_improvements), "__call__" + ) as call: client.update_automatic_improvements(request=None) # Establish that the underlying stub method was called. @@ -2283,18 +2935,21 @@ def test_transport_grpc_default(): transports.AutomaticImprovementsServiceGrpcTransport, ) + def test_automatic_improvements_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AutomaticImprovementsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_automatic_improvements_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.AutomaticImprovementsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2303,8 +2958,8 @@ def test_automatic_improvements_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_automatic_improvements', - 'update_automatic_improvements', + "get_automatic_improvements", + "update_automatic_improvements", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2315,7 +2970,7 @@ def test_automatic_improvements_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2324,25 +2979,30 @@ def test_automatic_improvements_service_base_transport(): def test_automatic_improvements_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_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._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_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutomaticImprovementsServiceTransport( 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_automatic_improvements_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_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.automatic_improvements_service.transports.AutomaticImprovementsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AutomaticImprovementsServiceTransport() @@ -2351,14 +3011,12 @@ def test_automatic_improvements_service_base_transport_with_adc(): def test_automatic_improvements_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) AutomaticImprovementsServiceClient() 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, ) @@ -2373,12 +3031,12 @@ def test_automatic_improvements_service_auth_adc(): def test_automatic_improvements_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", ) @@ -2391,49 +3049,53 @@ def test_automatic_improvements_service_transport_auth_adc(transport_class): transports.AutomaticImprovementsServiceRestTransport, ], ) -def test_automatic_improvements_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'] +def test_automatic_improvements_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: + 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.AutomaticImprovementsServiceGrpcTransport, grpc_helpers), - (transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, grpc_helpers_async) + ( + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), ], ) -def test_automatic_improvements_service_transport_create_channel(transport_class, grpc_helpers): +def test_automatic_improvements_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, @@ -2444,9 +3106,15 @@ def test_automatic_improvements_service_transport_create_channel(transport_class ) -@pytest.mark.parametrize("transport_class", [transports.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + ], +) def test_automatic_improvements_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2456,7 +3124,7 @@ def test_automatic_improvements_service_grpc_transport_client_cert_source_for_mt 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", @@ -2477,62 +3145,80 @@ def test_automatic_improvements_service_grpc_transport_client_cert_source_for_mt 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_automatic_improvements_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.AutomaticImprovementsServiceRestTransport ( - 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.AutomaticImprovementsServiceRestTransport( + 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_automatic_improvements_service_host_no_port(transport_name): client = AutomaticImprovementsServiceClient( 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_automatic_improvements_service_host_with_port(transport_name): client = AutomaticImprovementsServiceClient( 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", -]) -def test_automatic_improvements_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_automatic_improvements_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = AutomaticImprovementsServiceClient( @@ -2549,8 +3235,10 @@ def test_automatic_improvements_service_client_transport_session_collision(trans session1 = client1.transport.update_automatic_improvements._session session2 = client2.transport.update_automatic_improvements._session assert session1 != session2 + + def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport( @@ -2563,7 +3251,7 @@ def test_automatic_improvements_service_grpc_transport_channel(): def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcAsyncIOTransport( @@ -2577,12 +3265,22 @@ def test_automatic_improvements_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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + ], +) def test_automatic_improvements_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 @@ -2591,7 +3289,7 @@ def test_automatic_improvements_service_transport_channel_mtls_with_client_cert_ 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", @@ -2621,9 +3319,15 @@ def test_automatic_improvements_service_transport_channel_mtls_with_client_cert_ # 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.AutomaticImprovementsServiceGrpcTransport, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutomaticImprovementsServiceGrpcTransport, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + ], +) def test_automatic_improvements_service_transport_channel_mtls_with_adc( - transport_class + transport_class, ): mock_ssl_cred = mock.Mock() with mock.patch.multiple( @@ -2631,7 +3335,9 @@ def test_automatic_improvements_service_transport_channel_mtls_with_adc( __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() @@ -2661,7 +3367,9 @@ def test_automatic_improvements_service_transport_channel_mtls_with_adc( def test_automatic_improvements_path(): account = "squid" - expected = "accounts/{account}/automaticImprovements".format(account=account, ) + expected = "accounts/{account}/automaticImprovements".format( + account=account, + ) actual = AutomaticImprovementsServiceClient.automatic_improvements_path(account) assert expected == actual @@ -2676,10 +3384,15 @@ def test_parse_automatic_improvements_path(): actual = AutomaticImprovementsServiceClient.parse_automatic_improvements_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AutomaticImprovementsServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = AutomaticImprovementsServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -2693,9 +3406,12 @@ def test_parse_common_billing_account_path(): actual = AutomaticImprovementsServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = AutomaticImprovementsServiceClient.common_folder_path(folder) assert expected == actual @@ -2710,9 +3426,12 @@ def test_parse_common_folder_path(): actual = AutomaticImprovementsServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = AutomaticImprovementsServiceClient.common_organization_path(organization) assert expected == actual @@ -2727,9 +3446,12 @@ def test_parse_common_organization_path(): actual = AutomaticImprovementsServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = AutomaticImprovementsServiceClient.common_project_path(project) assert expected == actual @@ -2744,10 +3466,14 @@ def test_parse_common_project_path(): actual = AutomaticImprovementsServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = AutomaticImprovementsServiceClient.common_location_path(project, location) assert expected == actual @@ -2767,14 +3493,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.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AutomaticImprovementsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = AutomaticImprovementsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.AutomaticImprovementsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.AutomaticImprovementsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = AutomaticImprovementsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2785,10 +3515,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = AutomaticImprovementsServiceClient( - 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() @@ -2797,10 +3528,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = AutomaticImprovementsServiceAsyncClient( - 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() @@ -2808,10 +3540,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = AutomaticImprovementsServiceClient( - 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() @@ -2819,13 +3552,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = AutomaticImprovementsServiceClient( - 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: @@ -2834,10 +3566,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (AutomaticImprovementsServiceClient, transports.AutomaticImprovementsServiceGrpcTransport), - (AutomaticImprovementsServiceAsyncClient, transports.AutomaticImprovementsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + AutomaticImprovementsServiceClient, + transports.AutomaticImprovementsServiceGrpcTransport, + ), + ( + AutomaticImprovementsServiceAsyncClient, + transports.AutomaticImprovementsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2852,7 +3594,9 @@ def test_api_key_credentials(client_class, transport_class): patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, diff --git a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py index 0cb00207a4ae..5879ebed7f3a 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_identity_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_business_identity_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,45 +22,43 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.business_identity_service import BusinessIdentityServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.business_identity_service import BusinessIdentityServiceClient -from google.shopping.merchant_accounts_v1.services.business_identity_service import transports -from google.shopping.merchant_accounts_v1.types import businessidentity -import google.auth - +from google.shopping.merchant_accounts_v1.services.business_identity_service import ( + BusinessIdentityServiceAsyncClient, + BusinessIdentityServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import businessidentity CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert BusinessIdentityServiceClient._get_default_mtls_endpoint(None) is None - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert BusinessIdentityServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + BusinessIdentityServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + BusinessIdentityServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + BusinessIdentityServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + BusinessIdentityServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + assert BusinessIdentityServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (True, "auto", None) + assert BusinessIdentityServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + assert BusinessIdentityServiceClient._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: BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._read_environment_variables() == (False, "never", None) + assert BusinessIdentityServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "always", None) + assert BusinessIdentityServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", None) + assert BusinessIdentityServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, False) is None - assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + BusinessIdentityServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + BusinessIdentityServiceClient._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 ( + BusinessIdentityServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert BusinessIdentityServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +@mock.patch.object( + BusinessIdentityServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceClient), +) +@mock.patch.object( + BusinessIdentityServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert BusinessIdentityServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessIdentityServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert BusinessIdentityServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == BusinessIdentityServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + BusinessIdentityServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - BusinessIdentityServiceClient._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." + BusinessIdentityServiceClient._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 BusinessIdentityServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert BusinessIdentityServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert BusinessIdentityServiceClient._get_universe_domain(None, None) == BusinessIdentityServiceClient._DEFAULT_UNIVERSE + assert ( + BusinessIdentityServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + BusinessIdentityServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + BusinessIdentityServiceClient._get_universe_domain(None, None) + == BusinessIdentityServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: BusinessIdentityServiceClient._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) @@ -215,7 +370,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") @@ -228,14 +384,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", [ - (BusinessIdentityServiceClient, "grpc"), - (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), - (BusinessIdentityServiceClient, "rest"), -]) -def test_business_identity_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BusinessIdentityServiceClient, "grpc"), + (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), + (BusinessIdentityServiceClient, "rest"), + ], +) +def test_business_identity_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) @@ -243,52 +407,70 @@ def test_business_identity_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.BusinessIdentityServiceGrpcTransport, "grpc"), - (transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.BusinessIdentityServiceRestTransport, "rest"), -]) -def test_business_identity_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.BusinessIdentityServiceGrpcTransport, "grpc"), + (transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BusinessIdentityServiceRestTransport, "rest"), + ], +) +def test_business_identity_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", [ - (BusinessIdentityServiceClient, "grpc"), - (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), - (BusinessIdentityServiceClient, "rest"), -]) -def test_business_identity_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BusinessIdentityServiceClient, "grpc"), + (BusinessIdentityServiceAsyncClient, "grpc_asyncio"), + (BusinessIdentityServiceClient, "rest"), + ], +) +def test_business_identity_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" ) @@ -304,30 +486,53 @@ def test_business_identity_service_client_get_transport_class(): assert transport == transports.BusinessIdentityServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), -]) -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) -def test_business_identity_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + "grpc", + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + BusinessIdentityServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceClient), +) +@mock.patch.object( + BusinessIdentityServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceAsyncClient), +) +def test_business_identity_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(BusinessIdentityServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(BusinessIdentityServiceClient, "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(BusinessIdentityServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(BusinessIdentityServiceClient, "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( @@ -345,13 +550,15 @@ def test_business_identity_service_client_client_options(client_class, transport # 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, @@ -363,7 +570,7 @@ def test_business_identity_service_client_client_options(client_class, transport # 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( @@ -383,23 +590,33 @@ def test_business_identity_service_client_client_options(client_class, transport 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", @@ -408,48 +625,102 @@ def test_business_identity_service_client_client_options(client_class, transport 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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "true"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", "false"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "true"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + "grpc", + "true", + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + "grpc", + "false", + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceRestTransport, + "rest", + "true", + ), + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + BusinessIdentityServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceClient), +) +@mock.patch.object( + BusinessIdentityServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_business_identity_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_business_identity_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 @@ -468,12 +739,22 @@ def test_business_identity_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 @@ -494,15 +775,22 @@ def test_business_identity_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, @@ -512,19 +800,33 @@ def test_business_identity_service_client_mtls_env_auto(client_class, transport_ ) -@pytest.mark.parametrize("client_class", [ - BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient -]) -@mock.patch.object(BusinessIdentityServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessIdentityServiceAsyncClient)) -def test_business_identity_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient] +) +@mock.patch.object( + BusinessIdentityServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BusinessIdentityServiceClient), +) +@mock.patch.object( + BusinessIdentityServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BusinessIdentityServiceAsyncClient), +) +def test_business_identity_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 @@ -532,8 +834,12 @@ def test_business_identity_service_client_get_mtls_endpoint_and_cert_source(clie 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 @@ -551,16 +857,28 @@ def test_business_identity_service_client_get_mtls_endpoint_and_cert_source(clie # 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 @@ -570,34 +888,62 @@ def test_business_identity_service_client_get_mtls_endpoint_and_cert_source(clie 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", [ - BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient -]) -@mock.patch.object(BusinessIdentityServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceClient)) -@mock.patch.object(BusinessIdentityServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessIdentityServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [BusinessIdentityServiceClient, BusinessIdentityServiceAsyncClient] +) +@mock.patch.object( + BusinessIdentityServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceClient), +) +@mock.patch.object( + BusinessIdentityServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessIdentityServiceAsyncClient), +) def test_business_identity_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = BusinessIdentityServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = BusinessIdentityServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = BusinessIdentityServiceClient._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", @@ -620,11 +966,19 @@ def test_business_identity_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. @@ -632,27 +986,48 @@ def test_business_identity_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", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc"), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest"), -]) -def test_business_identity_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + "grpc", + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceRestTransport, + "rest", + ), + ], +) +def test_business_identity_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, @@ -661,24 +1036,45 @@ def test_business_identity_service_client_client_options_scopes(client_class, tr api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceRestTransport, "rest", None), -]) -def test_business_identity_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", + [ + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceRestTransport, + "rest", + None, + ), + ], +) +def test_business_identity_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, @@ -687,11 +1083,14 @@ def test_business_identity_service_client_client_options_credentials_file(client api_audience=None, ) + def test_business_identity_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = BusinessIdentityServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1105,38 @@ def test_business_identity_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_business_identity_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", + [ + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_business_identity_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, @@ -749,9 +1163,7 @@ def test_business_identity_service_client_create_channel_credentials_file(client 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, @@ -762,11 +1174,14 @@ def test_business_identity_service_client_create_channel_credentials_file(client ) -@pytest.mark.parametrize("request_type", [ - businessidentity.GetBusinessIdentityRequest, - dict, -]) -def test_get_business_identity(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + businessidentity.GetBusinessIdentityRequest, + dict, + ], +) +def test_get_business_identity(request_type, transport: str = "grpc"): client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,11 +1193,11 @@ def test_get_business_identity(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessidentity.BusinessIdentity( - name='name_value', + name="name_value", promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, ) response = client.get_business_identity(request) @@ -795,8 +1210,11 @@ def test_get_business_identity(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + assert response.name == "name_value" + assert ( + response.promotions_consent + == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + ) def test_get_business_identity_non_empty_request_with_auto_populated_field(): @@ -804,28 +1222,31 @@ def test_get_business_identity_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = BusinessIdentityServiceClient( 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 = businessidentity.GetBusinessIdentityRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_business_identity), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_business_identity(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == businessidentity.GetBusinessIdentityRequest( - name='name_value', + name="name_value", ) + def test_get_business_identity_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -840,12 +1261,19 @@ def test_get_business_identity_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_business_identity in client._transport._wrapped_methods + assert ( + client._transport.get_business_identity + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_business_identity + ] = mock_rpc request = {} client.get_business_identity(request) @@ -858,8 +1286,11 @@ def test_get_business_identity_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_business_identity_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_business_identity_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: @@ -873,12 +1304,17 @@ async def test_get_business_identity_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_business_identity in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_business_identity + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_business_identity] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_business_identity + ] = mock_rpc request = {} await client.get_business_identity(request) @@ -892,8 +1328,12 @@ async def test_get_business_identity_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.GetBusinessIdentityRequest): +async def test_get_business_identity_async( + transport: str = "grpc_asyncio", + request_type=businessidentity.GetBusinessIdentityRequest, +): client = BusinessIdentityServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -905,13 +1345,15 @@ async def test_get_business_identity_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity( + name="name_value", + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + ) response = await client.get_business_identity(request) # Establish that the underlying gRPC stub method was called. @@ -922,14 +1364,18 @@ async def test_get_business_identity_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + assert response.name == "name_value" + assert ( + response.promotions_consent + == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + ) @pytest.mark.asyncio async def test_get_business_identity_async_from_dict(): await test_get_business_identity_async(request_type=dict) + def test_get_business_identity_field_headers(): client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -939,12 +1385,12 @@ def test_get_business_identity_field_headers(): # a field header. Set these to a non-empty value. request = businessidentity.GetBusinessIdentityRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: call.return_value = businessidentity.BusinessIdentity() client.get_business_identity(request) @@ -956,9 +1402,9 @@ def test_get_business_identity_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 @@ -971,13 +1417,15 @@ async def test_get_business_identity_field_headers_async(): # a field header. Set these to a non-empty value. request = businessidentity.GetBusinessIdentityRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + type(client.transport.get_business_identity), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity() + ) await client.get_business_identity(request) # Establish that the underlying gRPC stub method was called. @@ -988,9 +1436,9 @@ async def test_get_business_identity_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_business_identity_flattened(): @@ -1000,14 +1448,14 @@ def test_get_business_identity_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessidentity.BusinessIdentity() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_business_identity( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1015,7 +1463,7 @@ def test_get_business_identity_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 @@ -1029,9 +1477,10 @@ def test_get_business_identity_flattened_error(): with pytest.raises(ValueError): client.get_business_identity( businessidentity.GetBusinessIdentityRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_business_identity_flattened_async(): client = BusinessIdentityServiceAsyncClient( @@ -1040,16 +1489,18 @@ async def test_get_business_identity_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessidentity.BusinessIdentity() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_business_identity( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1057,9 +1508,10 @@ async def test_get_business_identity_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_business_identity_flattened_error_async(): client = BusinessIdentityServiceAsyncClient( @@ -1071,15 +1523,18 @@ async def test_get_business_identity_flattened_error_async(): with pytest.raises(ValueError): await client.get_business_identity( businessidentity.GetBusinessIdentityRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - businessidentity.UpdateBusinessIdentityRequest, - dict, -]) -def test_update_business_identity(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + businessidentity.UpdateBusinessIdentityRequest, + dict, + ], +) +def test_update_business_identity(request_type, transport: str = "grpc"): client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1091,11 +1546,11 @@ def test_update_business_identity(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessidentity.BusinessIdentity( - name='name_value', + name="name_value", promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, ) response = client.update_business_identity(request) @@ -1108,8 +1563,11 @@ def test_update_business_identity(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + assert response.name == "name_value" + assert ( + response.promotions_consent + == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + ) def test_update_business_identity_non_empty_request_with_auto_populated_field(): @@ -1117,25 +1575,26 @@ def test_update_business_identity_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = BusinessIdentityServiceClient( 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 = businessidentity.UpdateBusinessIdentityRequest( - ) + request = businessidentity.UpdateBusinessIdentityRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_business_identity), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_business_identity(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == businessidentity.UpdateBusinessIdentityRequest( - ) + assert args[0] == businessidentity.UpdateBusinessIdentityRequest() + def test_update_business_identity_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1151,12 +1610,19 @@ def test_update_business_identity_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_business_identity in client._transport._wrapped_methods + assert ( + client._transport.update_business_identity + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_business_identity + ] = mock_rpc request = {} client.update_business_identity(request) @@ -1169,8 +1635,11 @@ def test_update_business_identity_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_business_identity_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_business_identity_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: @@ -1184,12 +1653,17 @@ async def test_update_business_identity_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_business_identity in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_business_identity + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_business_identity] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_business_identity + ] = mock_rpc request = {} await client.update_business_identity(request) @@ -1203,8 +1677,12 @@ async def test_update_business_identity_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_business_identity_async(transport: str = 'grpc_asyncio', request_type=businessidentity.UpdateBusinessIdentityRequest): +async def test_update_business_identity_async( + transport: str = "grpc_asyncio", + request_type=businessidentity.UpdateBusinessIdentityRequest, +): client = BusinessIdentityServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1216,13 +1694,15 @@ async def test_update_business_identity_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity( + name="name_value", + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + ) response = await client.update_business_identity(request) # Establish that the underlying gRPC stub method was called. @@ -1233,14 +1713,18 @@ async def test_update_business_identity_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + assert response.name == "name_value" + assert ( + response.promotions_consent + == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + ) @pytest.mark.asyncio async def test_update_business_identity_async_from_dict(): await test_update_business_identity_async(request_type=dict) + def test_update_business_identity_field_headers(): client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1250,12 +1734,12 @@ def test_update_business_identity_field_headers(): # a field header. Set these to a non-empty value. request = businessidentity.UpdateBusinessIdentityRequest() - request.business_identity.name = 'name_value' + request.business_identity.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: call.return_value = businessidentity.BusinessIdentity() client.update_business_identity(request) @@ -1267,9 +1751,9 @@ def test_update_business_identity_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'business_identity.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "business_identity.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1282,13 +1766,15 @@ async def test_update_business_identity_field_headers_async(): # a field header. Set these to a non-empty value. request = businessidentity.UpdateBusinessIdentityRequest() - request.business_identity.name = 'name_value' + request.business_identity.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + type(client.transport.update_business_identity), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity() + ) await client.update_business_identity(request) # Establish that the underlying gRPC stub method was called. @@ -1299,9 +1785,9 @@ async def test_update_business_identity_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'business_identity.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "business_identity.name=name_value", + ) in kw["metadata"] def test_update_business_identity_flattened(): @@ -1311,15 +1797,15 @@ def test_update_business_identity_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessidentity.BusinessIdentity() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_business_identity( - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_identity=businessidentity.BusinessIdentity(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1327,10 +1813,10 @@ def test_update_business_identity_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].business_identity - mock_val = businessidentity.BusinessIdentity(name='name_value') + mock_val = businessidentity.BusinessIdentity(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1344,10 +1830,11 @@ def test_update_business_identity_flattened_error(): with pytest.raises(ValueError): client.update_business_identity( businessidentity.UpdateBusinessIdentityRequest(), - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_identity=businessidentity.BusinessIdentity(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_business_identity_flattened_async(): client = BusinessIdentityServiceAsyncClient( @@ -1356,17 +1843,19 @@ async def test_update_business_identity_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessidentity.BusinessIdentity() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_business_identity( - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_identity=businessidentity.BusinessIdentity(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1374,12 +1863,13 @@ async def test_update_business_identity_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].business_identity - mock_val = businessidentity.BusinessIdentity(name='name_value') + mock_val = businessidentity.BusinessIdentity(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_business_identity_flattened_error_async(): client = BusinessIdentityServiceAsyncClient( @@ -1391,8 +1881,8 @@ async def test_update_business_identity_flattened_error_async(): with pytest.raises(ValueError): await client.update_business_identity( businessidentity.UpdateBusinessIdentityRequest(), - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_identity=businessidentity.BusinessIdentity(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1410,12 +1900,19 @@ def test_get_business_identity_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_business_identity in client._transport._wrapped_methods + assert ( + client._transport.get_business_identity + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_identity] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_business_identity + ] = mock_rpc request = {} client.get_business_identity(request) @@ -1430,55 +1927,60 @@ def test_get_business_identity_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_business_identity_rest_required_fields(request_type=businessidentity.GetBusinessIdentityRequest): +def test_get_business_identity_rest_required_fields( + request_type=businessidentity.GetBusinessIdentityRequest, +): transport_class = transports.BusinessIdentityServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_identity._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_business_identity._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_identity._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_business_identity._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 = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = businessidentity.BusinessIdentity() # Mock the http request 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 @@ -1489,24 +1991,24 @@ def test_get_business_identity_rest_required_fields(request_type=businessidentit return_value = businessidentity.BusinessIdentity.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_business_identity(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_business_identity_rest_unset_required_fields(): - transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.BusinessIdentityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_business_identity._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_business_identity_rest_flattened(): @@ -1516,16 +2018,16 @@ def test_get_business_identity_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 = businessidentity.BusinessIdentity() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/businessIdentity'} + sample_request = {"name": "accounts/sample1/businessIdentity"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1535,7 +2037,7 @@ def test_get_business_identity_rest_flattened(): # Convert return value to protobuf type return_value = businessidentity.BusinessIdentity.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1545,10 +2047,14 @@ def test_get_business_identity_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/businessIdentity}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/businessIdentity}" + % client.transport._host, + args[1], + ) -def test_get_business_identity_rest_flattened_error(transport: str = 'rest'): +def test_get_business_identity_rest_flattened_error(transport: str = "rest"): client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1559,7 +2065,7 @@ def test_get_business_identity_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_business_identity( businessidentity.GetBusinessIdentityRequest(), - name='name_value', + name="name_value", ) @@ -1577,12 +2083,19 @@ def test_update_business_identity_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_business_identity in client._transport._wrapped_methods + assert ( + client._transport.update_business_identity + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_identity] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_business_identity + ] = mock_rpc request = {} client.update_business_identity(request) @@ -1597,54 +2110,59 @@ def test_update_business_identity_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_business_identity_rest_required_fields(request_type=businessidentity.UpdateBusinessIdentityRequest): +def test_update_business_identity_rest_required_fields( + request_type=businessidentity.UpdateBusinessIdentityRequest, +): transport_class = transports.BusinessIdentityServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_business_identity._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_identity._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_business_identity._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = businessidentity.BusinessIdentity() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -1654,24 +2172,24 @@ def test_update_business_identity_rest_required_fields(request_type=businessiden return_value = businessidentity.BusinessIdentity.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_business_identity(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_business_identity_rest_unset_required_fields(): - transport = transports.BusinessIdentityServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.BusinessIdentityServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_business_identity._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("businessIdentity", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("businessIdentity",))) def test_update_business_identity_rest_flattened(): @@ -1681,17 +2199,19 @@ def test_update_business_identity_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 = businessidentity.BusinessIdentity() # get arguments that satisfy an http rule for this method - sample_request = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + sample_request = { + "business_identity": {"name": "accounts/sample1/businessIdentity"} + } # get truthy value for each flattened field mock_args = dict( - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_identity=businessidentity.BusinessIdentity(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -1701,7 +2221,7 @@ def test_update_business_identity_rest_flattened(): # Convert return value to protobuf type return_value = businessidentity.BusinessIdentity.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1711,10 +2231,14 @@ def test_update_business_identity_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{business_identity.name=accounts/*/businessIdentity}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{business_identity.name=accounts/*/businessIdentity}" + % client.transport._host, + args[1], + ) -def test_update_business_identity_rest_flattened_error(transport: str = 'rest'): +def test_update_business_identity_rest_flattened_error(transport: str = "rest"): client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1725,8 +2249,8 @@ def test_update_business_identity_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_business_identity( businessidentity.UpdateBusinessIdentityRequest(), - business_identity=businessidentity.BusinessIdentity(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_identity=businessidentity.BusinessIdentity(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1768,8 +2292,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = BusinessIdentityServiceClient( - 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. @@ -1791,6 +2314,7 @@ def test_transport_instance(): client = BusinessIdentityServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.BusinessIdentityServiceGrpcTransport( @@ -1805,18 +2329,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.BusinessIdentityServiceGrpcTransport, - transports.BusinessIdentityServiceGrpcAsyncIOTransport, - transports.BusinessIdentityServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + transports.BusinessIdentityServiceRestTransport, + ], +) 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 = BusinessIdentityServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1826,8 +2355,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1842,8 +2370,8 @@ def test_get_business_identity_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: call.return_value = businessidentity.BusinessIdentity() client.get_business_identity(request=None) @@ -1865,8 +2393,8 @@ def test_update_business_identity_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: call.return_value = businessidentity.BusinessIdentity() client.update_business_identity(request=None) @@ -1887,8 +2415,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = BusinessIdentityServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1904,13 +2431,15 @@ async def test_get_business_identity_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity( + name="name_value", + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + ) await client.get_business_identity(request=None) # Establish that the underlying stub method was called. @@ -1932,13 +2461,15 @@ async def test_update_business_identity_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessidentity.BusinessIdentity( + name="name_value", + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + ) + ) await client.update_business_identity(request=None) # Establish that the underlying stub method was called. @@ -1956,20 +2487,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_business_identity_rest_bad_request(request_type=businessidentity.GetBusinessIdentityRequest): +def test_get_business_identity_rest_bad_request( + request_type=businessidentity.GetBusinessIdentityRequest, +): client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessIdentity'} + request_init = {"name": "accounts/sample1/businessIdentity"} 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() @@ -1978,26 +2512,28 @@ def test_get_business_identity_rest_bad_request(request_type=businessidentity.Ge client.get_business_identity(request) -@pytest.mark.parametrize("request_type", [ - businessidentity.GetBusinessIdentityRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + businessidentity.GetBusinessIdentityRequest, + dict, + ], +) def test_get_business_identity_rest_call_success(request_type): client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessIdentity'} + request_init = {"name": "accounts/sample1/businessIdentity"} request = request_type(**request_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 = businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + name="name_value", + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, ) # Wrap the value into a proper Response obj @@ -2007,34 +2543,48 @@ def test_get_business_identity_rest_call_success(request_type): # Convert return value to protobuf type return_value = businessidentity.BusinessIdentity.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_business_identity(request) # Establish that the response is the type that we expect. assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + assert response.name == "name_value" + assert ( + response.promotions_consent + == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_business_identity_rest_interceptors(null_interceptor): transport = transports.BusinessIdentityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.BusinessIdentityServiceRestInterceptor(), + ) client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_get_business_identity") as post, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_get_business_identity_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_get_business_identity") 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.BusinessIdentityServiceRestInterceptor, "post_get_business_identity" + ) as post, mock.patch.object( + transports.BusinessIdentityServiceRestInterceptor, + "post_get_business_identity_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BusinessIdentityServiceRestInterceptor, "pre_get_business_identity" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = businessidentity.GetBusinessIdentityRequest.pb(businessidentity.GetBusinessIdentityRequest()) + pb_message = businessidentity.GetBusinessIdentityRequest.pb( + businessidentity.GetBusinessIdentityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2045,11 +2595,13 @@ def test_get_business_identity_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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) + return_value = businessidentity.BusinessIdentity.to_json( + businessidentity.BusinessIdentity() + ) req.return_value.content = return_value request = businessidentity.GetBusinessIdentityRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2057,27 +2609,36 @@ def test_get_business_identity_rest_interceptors(null_interceptor): post.return_value = businessidentity.BusinessIdentity() post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata - client.get_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_business_identity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_business_identity_rest_bad_request(request_type=businessidentity.UpdateBusinessIdentityRequest): +def test_update_business_identity_rest_bad_request( + request_type=businessidentity.UpdateBusinessIdentityRequest, +): client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} + request_init = {"business_identity": {"name": "accounts/sample1/businessIdentity"}} 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() @@ -2086,25 +2647,37 @@ def test_update_business_identity_rest_bad_request(request_type=businessidentity client.update_business_identity(request) -@pytest.mark.parametrize("request_type", [ - businessidentity.UpdateBusinessIdentityRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + businessidentity.UpdateBusinessIdentityRequest, + dict, + ], +) def test_update_business_identity_rest_call_success(request_type): client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'business_identity': {'name': 'accounts/sample1/businessIdentity'}} - request_init["business_identity"] = {'name': 'accounts/sample1/businessIdentity', 'promotions_consent': 1, 'black_owned': {'identity_declaration': 1}, 'women_owned': {}, 'veteran_owned': {}, 'latino_owned': {}, 'small_business': {}} + request_init = {"business_identity": {"name": "accounts/sample1/businessIdentity"}} + request_init["business_identity"] = { + "name": "accounts/sample1/businessIdentity", + "promotions_consent": 1, + "black_owned": {"identity_declaration": 1}, + "women_owned": {}, + "veteran_owned": {}, + "latino_owned": {}, + "small_business": {}, + } # 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 = businessidentity.UpdateBusinessIdentityRequest.meta.fields["business_identity"] + test_field = businessidentity.UpdateBusinessIdentityRequest.meta.fields[ + "business_identity" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2118,7 +2691,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 @@ -2132,7 +2705,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["business_identity"].items(): # pragma: NO COVER + for field, value in request_init["business_identity"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2147,12 +2720,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") @@ -2165,11 +2742,11 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = businessidentity.BusinessIdentity( - name='name_value', - promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, + name="name_value", + promotions_consent=businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN, ) # Wrap the value into a proper Response obj @@ -2179,34 +2756,50 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = businessidentity.BusinessIdentity.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_business_identity(request) # Establish that the response is the type that we expect. assert isinstance(response, businessidentity.BusinessIdentity) - assert response.name == 'name_value' - assert response.promotions_consent == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + assert response.name == "name_value" + assert ( + response.promotions_consent + == businessidentity.BusinessIdentity.PromotionsConsent.PROMOTIONS_CONSENT_GIVEN + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_business_identity_rest_interceptors(null_interceptor): transport = transports.BusinessIdentityServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessIdentityServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.BusinessIdentityServiceRestInterceptor(), + ) client = BusinessIdentityServiceClient(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.BusinessIdentityServiceRestInterceptor, "post_update_business_identity") as post, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "post_update_business_identity_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessIdentityServiceRestInterceptor, "pre_update_business_identity") 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.BusinessIdentityServiceRestInterceptor, + "post_update_business_identity", + ) as post, mock.patch.object( + transports.BusinessIdentityServiceRestInterceptor, + "post_update_business_identity_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BusinessIdentityServiceRestInterceptor, + "pre_update_business_identity", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = businessidentity.UpdateBusinessIdentityRequest.pb(businessidentity.UpdateBusinessIdentityRequest()) + pb_message = businessidentity.UpdateBusinessIdentityRequest.pb( + businessidentity.UpdateBusinessIdentityRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2217,11 +2810,13 @@ def test_update_business_identity_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 = businessidentity.BusinessIdentity.to_json(businessidentity.BusinessIdentity()) + return_value = businessidentity.BusinessIdentity.to_json( + businessidentity.BusinessIdentity() + ) req.return_value.content = return_value request = businessidentity.UpdateBusinessIdentityRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2229,16 +2824,22 @@ def test_update_business_identity_rest_interceptors(null_interceptor): post.return_value = businessidentity.BusinessIdentity() post_with_metadata.return_value = businessidentity.BusinessIdentity(), metadata - client.update_business_identity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_business_identity( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = BusinessIdentityServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2253,8 +2854,8 @@ def test_get_business_identity_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_business_identity), - '__call__') as call: + type(client.transport.get_business_identity), "__call__" + ) as call: client.get_business_identity(request=None) # Establish that the underlying stub method was called. @@ -2275,8 +2876,8 @@ def test_update_business_identity_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_business_identity), - '__call__') as call: + type(client.transport.update_business_identity), "__call__" + ) as call: client.update_business_identity(request=None) # Establish that the underlying stub method was called. @@ -2297,18 +2898,21 @@ def test_transport_grpc_default(): transports.BusinessIdentityServiceGrpcTransport, ) + def test_business_identity_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.BusinessIdentityServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_business_identity_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.BusinessIdentityServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2317,8 +2921,8 @@ def test_business_identity_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_business_identity', - 'update_business_identity', + "get_business_identity", + "update_business_identity", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2329,7 +2933,7 @@ def test_business_identity_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2338,25 +2942,30 @@ def test_business_identity_service_base_transport(): def test_business_identity_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_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport._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_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BusinessIdentityServiceTransport( 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_business_identity_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_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.business_identity_service.transports.BusinessIdentityServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BusinessIdentityServiceTransport() @@ -2365,14 +2974,12 @@ def test_business_identity_service_base_transport_with_adc(): def test_business_identity_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) BusinessIdentityServiceClient() 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, ) @@ -2387,12 +2994,12 @@ def test_business_identity_service_auth_adc(): def test_business_identity_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", ) @@ -2406,48 +3013,47 @@ def test_business_identity_service_transport_auth_adc(transport_class): ], ) def test_business_identity_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.BusinessIdentityServiceGrpcTransport, grpc_helpers), - (transports.BusinessIdentityServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.BusinessIdentityServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_business_identity_service_transport_create_channel(transport_class, grpc_helpers): +def test_business_identity_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, @@ -2458,9 +3064,15 @@ def test_business_identity_service_transport_create_channel(transport_class, grp ) -@pytest.mark.parametrize("transport_class", [transports.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + ], +) def test_business_identity_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2470,7 +3082,7 @@ def test_business_identity_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", @@ -2491,61 +3103,77 @@ def test_business_identity_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_business_identity_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.BusinessIdentityServiceRestTransport ( - 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.BusinessIdentityServiceRestTransport( + 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_business_identity_service_host_no_port(transport_name): client = BusinessIdentityServiceClient( 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_business_identity_service_host_with_port(transport_name): client = BusinessIdentityServiceClient( 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_business_identity_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2563,8 +3191,10 @@ def test_business_identity_service_client_transport_session_collision(transport_ session1 = client1.transport.update_business_identity._session session2 = client2.transport.update_business_identity._session assert session1 != session2 + + def test_business_identity_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.BusinessIdentityServiceGrpcTransport( @@ -2577,7 +3207,7 @@ def test_business_identity_service_grpc_transport_channel(): def test_business_identity_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.BusinessIdentityServiceGrpcAsyncIOTransport( @@ -2591,12 +3221,22 @@ def test_business_identity_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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + ], +) def test_business_identity_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 @@ -2605,7 +3245,7 @@ def test_business_identity_service_transport_channel_mtls_with_client_cert_sourc 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", @@ -2635,17 +3275,23 @@ def test_business_identity_service_transport_channel_mtls_with_client_cert_sourc # 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.BusinessIdentityServiceGrpcTransport, transports.BusinessIdentityServiceGrpcAsyncIOTransport]) -def test_business_identity_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessIdentityServiceGrpcTransport, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + ], +) +def test_business_identity_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() @@ -2675,7 +3321,9 @@ def test_business_identity_service_transport_channel_mtls_with_adc( def test_business_identity_path(): account = "squid" - expected = "accounts/{account}/businessIdentity".format(account=account, ) + expected = "accounts/{account}/businessIdentity".format( + account=account, + ) actual = BusinessIdentityServiceClient.business_identity_path(account) assert expected == actual @@ -2690,9 +3338,12 @@ def test_parse_business_identity_path(): actual = BusinessIdentityServiceClient.parse_business_identity_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = BusinessIdentityServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2707,9 +3358,12 @@ def test_parse_common_billing_account_path(): actual = BusinessIdentityServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = BusinessIdentityServiceClient.common_folder_path(folder) assert expected == actual @@ -2724,9 +3378,12 @@ def test_parse_common_folder_path(): actual = BusinessIdentityServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = BusinessIdentityServiceClient.common_organization_path(organization) assert expected == actual @@ -2741,9 +3398,12 @@ def test_parse_common_organization_path(): actual = BusinessIdentityServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = BusinessIdentityServiceClient.common_project_path(project) assert expected == actual @@ -2758,10 +3418,14 @@ def test_parse_common_project_path(): actual = BusinessIdentityServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = BusinessIdentityServiceClient.common_location_path(project, location) assert expected == actual @@ -2781,14 +3445,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.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.BusinessIdentityServiceTransport, "_prep_wrapped_messages" + ) as prep: client = BusinessIdentityServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.BusinessIdentityServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.BusinessIdentityServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = BusinessIdentityServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2799,10 +3467,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = BusinessIdentityServiceClient( - 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() @@ -2811,10 +3480,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = BusinessIdentityServiceAsyncClient( - 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() @@ -2822,10 +3492,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = BusinessIdentityServiceClient( - 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() @@ -2833,13 +3504,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = BusinessIdentityServiceClient( - 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: @@ -2848,10 +3518,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (BusinessIdentityServiceClient, transports.BusinessIdentityServiceGrpcTransport), - (BusinessIdentityServiceAsyncClient, transports.BusinessIdentityServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + BusinessIdentityServiceClient, + transports.BusinessIdentityServiceGrpcTransport, + ), + ( + BusinessIdentityServiceAsyncClient, + transports.BusinessIdentityServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2866,7 +3546,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py similarity index 65% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py index 708c9ea01bb2..15c4297b2529 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_business_info_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_business_info_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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.business_info_service import BusinessInfoServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.business_info_service import BusinessInfoServiceClient -from google.shopping.merchant_accounts_v1.services.business_info_service import transports -from google.shopping.merchant_accounts_v1.types import businessinfo -from google.shopping.merchant_accounts_v1.types import customerservice -from google.shopping.merchant_accounts_v1.types import phoneverificationstate from google.type import phone_number_pb2 # type: ignore from google.type import postal_address_pb2 # type: ignore -import google.auth - +from google.shopping.merchant_accounts_v1.services.business_info_service import ( + BusinessInfoServiceAsyncClient, + BusinessInfoServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import ( + businessinfo, + customerservice, + phoneverificationstate, +) 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,243 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert BusinessInfoServiceClient._get_default_mtls_endpoint(None) is None - assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert BusinessInfoServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + BusinessInfoServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + BusinessInfoServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + BusinessInfoServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + BusinessInfoServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + assert BusinessInfoServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert BusinessInfoServiceClient._read_environment_variables() == (True, "auto", None) + assert BusinessInfoServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + assert BusinessInfoServiceClient._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: BusinessInfoServiceClient._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 BusinessInfoServiceClient._read_environment_variables() == (False, "never", None) + assert BusinessInfoServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "always", None) + assert BusinessInfoServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert BusinessInfoServiceClient._read_environment_variables() == (False, "auto", None) + assert BusinessInfoServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: BusinessInfoServiceClient._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 BusinessInfoServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, False) is None - assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + BusinessInfoServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + BusinessInfoServiceClient._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 ( + BusinessInfoServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert BusinessInfoServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +@mock.patch.object( + BusinessInfoServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceClient), +) +@mock.patch.object( + BusinessInfoServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert BusinessInfoServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessInfoServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT - assert BusinessInfoServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert BusinessInfoServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + BusinessInfoServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + BusinessInfoServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + BusinessInfoServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + BusinessInfoServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + BusinessInfoServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == BusinessInfoServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + BusinessInfoServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + BusinessInfoServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - BusinessInfoServiceClient._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." + BusinessInfoServiceClient._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 BusinessInfoServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert BusinessInfoServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert BusinessInfoServiceClient._get_universe_domain(None, None) == BusinessInfoServiceClient._DEFAULT_UNIVERSE + assert ( + BusinessInfoServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + BusinessInfoServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + BusinessInfoServiceClient._get_universe_domain(None, None) + == BusinessInfoServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: BusinessInfoServiceClient._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 +374,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 +388,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", [ - (BusinessInfoServiceClient, "grpc"), - (BusinessInfoServiceAsyncClient, "grpc_asyncio"), - (BusinessInfoServiceClient, "rest"), -]) -def test_business_info_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BusinessInfoServiceClient, "grpc"), + (BusinessInfoServiceAsyncClient, "grpc_asyncio"), + (BusinessInfoServiceClient, "rest"), + ], +) +def test_business_info_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 +411,70 @@ def test_business_info_service_client_from_service_account_info(client_class, tr 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.BusinessInfoServiceGrpcTransport, "grpc"), - (transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.BusinessInfoServiceRestTransport, "rest"), -]) -def test_business_info_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.BusinessInfoServiceGrpcTransport, "grpc"), + (transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BusinessInfoServiceRestTransport, "rest"), + ], +) +def test_business_info_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", [ - (BusinessInfoServiceClient, "grpc"), - (BusinessInfoServiceAsyncClient, "grpc_asyncio"), - (BusinessInfoServiceClient, "rest"), -]) -def test_business_info_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (BusinessInfoServiceClient, "grpc"), + (BusinessInfoServiceAsyncClient, "grpc_asyncio"), + (BusinessInfoServiceClient, "rest"), + ], +) +def test_business_info_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 +490,53 @@ def test_business_info_service_client_get_transport_class(): assert transport == transports.BusinessInfoServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), -]) -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) -def test_business_info_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceGrpcTransport, + "grpc", + ), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + BusinessInfoServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceClient), +) +@mock.patch.object( + BusinessInfoServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceAsyncClient), +) +def test_business_info_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(BusinessInfoServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(BusinessInfoServiceClient, "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(BusinessInfoServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(BusinessInfoServiceClient, "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 +554,15 @@ def test_business_info_service_client_client_options(client_class, transport_cla # 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 +574,7 @@ def test_business_info_service_client_client_options(client_class, transport_cla # 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 +594,33 @@ def test_business_info_service_client_client_options(client_class, transport_cla 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 +629,102 @@ def test_business_info_service_client_client_options(client_class, transport_cla 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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "true"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", "false"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "true"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceGrpcTransport, + "grpc", + "true", + ), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceGrpcTransport, + "grpc", + "false", + ), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceRestTransport, + "rest", + "true", + ), + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + BusinessInfoServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceClient), +) +@mock.patch.object( + BusinessInfoServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_business_info_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_business_info_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 +743,22 @@ def test_business_info_service_client_mtls_env_auto(client_class, transport_clas # 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 +779,22 @@ def test_business_info_service_client_mtls_env_auto(client_class, transport_clas ) # 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 +804,31 @@ def test_business_info_service_client_mtls_env_auto(client_class, transport_clas ) -@pytest.mark.parametrize("client_class", [ - BusinessInfoServiceClient, BusinessInfoServiceAsyncClient -]) -@mock.patch.object(BusinessInfoServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(BusinessInfoServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [BusinessInfoServiceClient, BusinessInfoServiceAsyncClient] +) +@mock.patch.object( + BusinessInfoServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BusinessInfoServiceClient), +) +@mock.patch.object( + BusinessInfoServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(BusinessInfoServiceAsyncClient), +) def test_business_info_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 +836,12 @@ def test_business_info_service_client_get_mtls_endpoint_and_cert_source(client_c 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 +859,28 @@ def test_business_info_service_client_get_mtls_endpoint_and_cert_source(client_c # 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 +890,62 @@ def test_business_info_service_client_get_mtls_endpoint_and_cert_source(client_c 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", [ - BusinessInfoServiceClient, BusinessInfoServiceAsyncClient -]) -@mock.patch.object(BusinessInfoServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceClient)) -@mock.patch.object(BusinessInfoServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(BusinessInfoServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [BusinessInfoServiceClient, BusinessInfoServiceAsyncClient] +) +@mock.patch.object( + BusinessInfoServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceClient), +) +@mock.patch.object( + BusinessInfoServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(BusinessInfoServiceAsyncClient), +) def test_business_info_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = BusinessInfoServiceClient._DEFAULT_UNIVERSE - default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = BusinessInfoServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = BusinessInfoServiceClient._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 +968,19 @@ def test_business_info_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 +988,48 @@ def test_business_info_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", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc"), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest"), -]) -def test_business_info_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceGrpcTransport, + "grpc", + ), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceRestTransport, + "rest", + ), + ], +) +def test_business_info_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 +1038,45 @@ def test_business_info_service_client_client_options_scopes(client_class, transp api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (BusinessInfoServiceClient, transports.BusinessInfoServiceRestTransport, "rest", None), -]) -def test_business_info_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", + [ + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceRestTransport, + "rest", + None, + ), + ], +) +def test_business_info_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 +1085,14 @@ def test_business_info_service_client_client_options_credentials_file(client_cla api_audience=None, ) + def test_business_info_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = BusinessInfoServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -710,23 +1107,38 @@ def test_business_info_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport, "grpc", grpc_helpers), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_business_info_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", + [ + ( + BusinessInfoServiceClient, + transports.BusinessInfoServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_business_info_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 +1165,7 @@ def test_business_info_service_client_create_channel_credentials_file(client_cla 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 +1176,14 @@ def test_business_info_service_client_create_channel_credentials_file(client_cla ) -@pytest.mark.parametrize("request_type", [ - businessinfo.GetBusinessInfoRequest, - dict, -]) -def test_get_business_info(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + businessinfo.GetBusinessInfoRequest, + dict, + ], +) +def test_get_business_info(request_type, transport: str = "grpc"): client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -782,13 +1195,13 @@ def test_get_business_info(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessinfo.BusinessInfo( - name='name_value', + name="name_value", phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', + korean_business_registration_number="korean_business_registration_number_value", ) response = client.get_business_info(request) @@ -800,9 +1213,15 @@ def test_get_business_info(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' + assert response.name == "name_value" + assert ( + response.phone_verification_state + == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + ) + assert ( + response.korean_business_registration_number + == "korean_business_registration_number_value" + ) def test_get_business_info_non_empty_request_with_auto_populated_field(): @@ -810,28 +1229,31 @@ def test_get_business_info_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = BusinessInfoServiceClient( 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 = businessinfo.GetBusinessInfoRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_business_info), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_business_info(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == businessinfo.GetBusinessInfoRequest( - name='name_value', + name="name_value", ) + def test_get_business_info_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -850,8 +1272,12 @@ def test_get_business_info_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_business_info + ] = mock_rpc request = {} client.get_business_info(request) @@ -864,8 +1290,11 @@ def test_get_business_info_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_business_info_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_business_info_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: @@ -879,12 +1308,17 @@ async def test_get_business_info_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_business_info in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_business_info + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_business_info] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_business_info + ] = mock_rpc request = {} await client.get_business_info(request) @@ -898,8 +1332,11 @@ async def test_get_business_info_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.GetBusinessInfoRequest): +async def test_get_business_info_async( + transport: str = "grpc_asyncio", request_type=businessinfo.GetBusinessInfoRequest +): client = BusinessInfoServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -911,14 +1348,16 @@ async def test_get_business_info_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo( + name="name_value", + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number="korean_business_registration_number_value", + ) + ) response = await client.get_business_info(request) # Establish that the underlying gRPC stub method was called. @@ -929,15 +1368,22 @@ async def test_get_business_info_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' + assert response.name == "name_value" + assert ( + response.phone_verification_state + == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + ) + assert ( + response.korean_business_registration_number + == "korean_business_registration_number_value" + ) @pytest.mark.asyncio async def test_get_business_info_async_from_dict(): await test_get_business_info_async(request_type=dict) + def test_get_business_info_field_headers(): client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -947,12 +1393,12 @@ def test_get_business_info_field_headers(): # a field header. Set these to a non-empty value. request = businessinfo.GetBusinessInfoRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: call.return_value = businessinfo.BusinessInfo() client.get_business_info(request) @@ -964,9 +1410,9 @@ def test_get_business_info_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 @@ -979,13 +1425,15 @@ async def test_get_business_info_field_headers_async(): # a field header. Set these to a non-empty value. request = businessinfo.GetBusinessInfoRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + type(client.transport.get_business_info), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo() + ) await client.get_business_info(request) # Establish that the underlying gRPC stub method was called. @@ -996,9 +1444,9 @@ async def test_get_business_info_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_business_info_flattened(): @@ -1008,14 +1456,14 @@ def test_get_business_info_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessinfo.BusinessInfo() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_business_info( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1023,7 +1471,7 @@ def test_get_business_info_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 @@ -1037,9 +1485,10 @@ def test_get_business_info_flattened_error(): with pytest.raises(ValueError): client.get_business_info( businessinfo.GetBusinessInfoRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_business_info_flattened_async(): client = BusinessInfoServiceAsyncClient( @@ -1048,16 +1497,18 @@ async def test_get_business_info_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessinfo.BusinessInfo() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_business_info( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1065,9 +1516,10 @@ async def test_get_business_info_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_business_info_flattened_error_async(): client = BusinessInfoServiceAsyncClient( @@ -1079,15 +1531,18 @@ async def test_get_business_info_flattened_error_async(): with pytest.raises(ValueError): await client.get_business_info( businessinfo.GetBusinessInfoRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - businessinfo.UpdateBusinessInfoRequest, - dict, -]) -def test_update_business_info(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + businessinfo.UpdateBusinessInfoRequest, + dict, + ], +) +def test_update_business_info(request_type, transport: str = "grpc"): client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1099,13 +1554,13 @@ def test_update_business_info(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessinfo.BusinessInfo( - name='name_value', + name="name_value", phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', + korean_business_registration_number="korean_business_registration_number_value", ) response = client.update_business_info(request) @@ -1117,9 +1572,15 @@ def test_update_business_info(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' + assert response.name == "name_value" + assert ( + response.phone_verification_state + == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + ) + assert ( + response.korean_business_registration_number + == "korean_business_registration_number_value" + ) def test_update_business_info_non_empty_request_with_auto_populated_field(): @@ -1127,25 +1588,26 @@ def test_update_business_info_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = BusinessInfoServiceClient( 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 = businessinfo.UpdateBusinessInfoRequest( - ) + request = businessinfo.UpdateBusinessInfoRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_business_info), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_business_info(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == businessinfo.UpdateBusinessInfoRequest( - ) + assert args[0] == businessinfo.UpdateBusinessInfoRequest() + def test_update_business_info_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1161,12 +1623,18 @@ def test_update_business_info_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_business_info in client._transport._wrapped_methods + assert ( + client._transport.update_business_info in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_business_info + ] = mock_rpc request = {} client.update_business_info(request) @@ -1179,8 +1647,11 @@ def test_update_business_info_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_business_info_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_business_info_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: @@ -1194,12 +1665,17 @@ async def test_update_business_info_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_business_info in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_business_info + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_business_info] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_business_info + ] = mock_rpc request = {} await client.update_business_info(request) @@ -1213,8 +1689,11 @@ async def test_update_business_info_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_business_info_async(transport: str = 'grpc_asyncio', request_type=businessinfo.UpdateBusinessInfoRequest): +async def test_update_business_info_async( + transport: str = "grpc_asyncio", request_type=businessinfo.UpdateBusinessInfoRequest +): client = BusinessInfoServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1226,14 +1705,16 @@ async def test_update_business_info_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo( + name="name_value", + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number="korean_business_registration_number_value", + ) + ) response = await client.update_business_info(request) # Establish that the underlying gRPC stub method was called. @@ -1244,15 +1725,22 @@ async def test_update_business_info_async(transport: str = 'grpc_asyncio', reque # Establish that the response is the type that we expect. assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' + assert response.name == "name_value" + assert ( + response.phone_verification_state + == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + ) + assert ( + response.korean_business_registration_number + == "korean_business_registration_number_value" + ) @pytest.mark.asyncio async def test_update_business_info_async_from_dict(): await test_update_business_info_async(request_type=dict) + def test_update_business_info_field_headers(): client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1262,12 +1750,12 @@ def test_update_business_info_field_headers(): # a field header. Set these to a non-empty value. request = businessinfo.UpdateBusinessInfoRequest() - request.business_info.name = 'name_value' + request.business_info.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: call.return_value = businessinfo.BusinessInfo() client.update_business_info(request) @@ -1279,9 +1767,9 @@ def test_update_business_info_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'business_info.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "business_info.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1294,13 +1782,15 @@ async def test_update_business_info_field_headers_async(): # a field header. Set these to a non-empty value. request = businessinfo.UpdateBusinessInfoRequest() - request.business_info.name = 'name_value' + request.business_info.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + type(client.transport.update_business_info), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo() + ) await client.update_business_info(request) # Establish that the underlying gRPC stub method was called. @@ -1311,9 +1801,9 @@ async def test_update_business_info_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'business_info.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "business_info.name=name_value", + ) in kw["metadata"] def test_update_business_info_flattened(): @@ -1323,15 +1813,15 @@ def test_update_business_info_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessinfo.BusinessInfo() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_business_info( - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_info=businessinfo.BusinessInfo(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1339,10 +1829,10 @@ def test_update_business_info_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].business_info - mock_val = businessinfo.BusinessInfo(name='name_value') + mock_val = businessinfo.BusinessInfo(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1356,10 +1846,11 @@ def test_update_business_info_flattened_error(): with pytest.raises(ValueError): client.update_business_info( businessinfo.UpdateBusinessInfoRequest(), - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_info=businessinfo.BusinessInfo(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_business_info_flattened_async(): client = BusinessInfoServiceAsyncClient( @@ -1368,17 +1859,19 @@ async def test_update_business_info_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = businessinfo.BusinessInfo() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_business_info( - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_info=businessinfo.BusinessInfo(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1386,12 +1879,13 @@ async def test_update_business_info_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].business_info - mock_val = businessinfo.BusinessInfo(name='name_value') + mock_val = businessinfo.BusinessInfo(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_business_info_flattened_error_async(): client = BusinessInfoServiceAsyncClient( @@ -1403,8 +1897,8 @@ async def test_update_business_info_flattened_error_async(): with pytest.raises(ValueError): await client.update_business_info( businessinfo.UpdateBusinessInfoRequest(), - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_info=businessinfo.BusinessInfo(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1426,8 +1920,12 @@ def test_get_business_info_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_business_info] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_business_info + ] = mock_rpc request = {} client.get_business_info(request) @@ -1442,55 +1940,60 @@ def test_get_business_info_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_business_info_rest_required_fields(request_type=businessinfo.GetBusinessInfoRequest): +def test_get_business_info_rest_required_fields( + request_type=businessinfo.GetBusinessInfoRequest, +): transport_class = transports.BusinessInfoServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_info._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_business_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_business_info._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_business_info._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 = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = businessinfo.BusinessInfo() # Mock the http request 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 @@ -1501,24 +2004,24 @@ def test_get_business_info_rest_required_fields(request_type=businessinfo.GetBus return_value = businessinfo.BusinessInfo.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_business_info(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_business_info_rest_unset_required_fields(): - transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.BusinessInfoServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_business_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_business_info_rest_flattened(): @@ -1528,16 +2031,16 @@ def test_get_business_info_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 = businessinfo.BusinessInfo() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/businessInfo'} + sample_request = {"name": "accounts/sample1/businessInfo"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1547,7 +2050,7 @@ def test_get_business_info_rest_flattened(): # Convert return value to protobuf type return_value = businessinfo.BusinessInfo.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1557,10 +2060,13 @@ def test_get_business_info_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/businessInfo}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/businessInfo}" % client.transport._host, + args[1], + ) -def test_get_business_info_rest_flattened_error(transport: str = 'rest'): +def test_get_business_info_rest_flattened_error(transport: str = "rest"): client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1571,7 +2077,7 @@ def test_get_business_info_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_business_info( businessinfo.GetBusinessInfoRequest(), - name='name_value', + name="name_value", ) @@ -1589,12 +2095,18 @@ def test_update_business_info_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_business_info in client._transport._wrapped_methods + assert ( + client._transport.update_business_info in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_business_info] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_business_info + ] = mock_rpc request = {} client.update_business_info(request) @@ -1609,54 +2121,59 @@ def test_update_business_info_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_business_info_rest_required_fields(request_type=businessinfo.UpdateBusinessInfoRequest): +def test_update_business_info_rest_required_fields( + request_type=businessinfo.UpdateBusinessInfoRequest, +): transport_class = transports.BusinessInfoServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_business_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_business_info._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_business_info._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = businessinfo.BusinessInfo() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -1666,24 +2183,24 @@ def test_update_business_info_rest_required_fields(request_type=businessinfo.Upd return_value = businessinfo.BusinessInfo.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_business_info(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_business_info_rest_unset_required_fields(): - transport = transports.BusinessInfoServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.BusinessInfoServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_business_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("businessInfo", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("businessInfo",))) def test_update_business_info_rest_flattened(): @@ -1693,17 +2210,17 @@ def test_update_business_info_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 = businessinfo.BusinessInfo() # get arguments that satisfy an http rule for this method - sample_request = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + sample_request = {"business_info": {"name": "accounts/sample1/businessInfo"}} # get truthy value for each flattened field mock_args = dict( - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_info=businessinfo.BusinessInfo(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -1713,7 +2230,7 @@ def test_update_business_info_rest_flattened(): # Convert return value to protobuf type return_value = businessinfo.BusinessInfo.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1723,10 +2240,14 @@ def test_update_business_info_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{business_info.name=accounts/*/businessInfo}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{business_info.name=accounts/*/businessInfo}" + % client.transport._host, + args[1], + ) -def test_update_business_info_rest_flattened_error(transport: str = 'rest'): +def test_update_business_info_rest_flattened_error(transport: str = "rest"): client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1737,8 +2258,8 @@ def test_update_business_info_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_business_info( businessinfo.UpdateBusinessInfoRequest(), - business_info=businessinfo.BusinessInfo(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + business_info=businessinfo.BusinessInfo(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1780,8 +2301,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = BusinessInfoServiceClient( - 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. @@ -1803,6 +2323,7 @@ def test_transport_instance(): client = BusinessInfoServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.BusinessInfoServiceGrpcTransport( @@ -1817,18 +2338,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.BusinessInfoServiceGrpcTransport, - transports.BusinessInfoServiceGrpcAsyncIOTransport, - transports.BusinessInfoServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + transports.BusinessInfoServiceRestTransport, + ], +) 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 = BusinessInfoServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1838,8 +2364,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1854,8 +2379,8 @@ def test_get_business_info_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: call.return_value = businessinfo.BusinessInfo() client.get_business_info(request=None) @@ -1877,8 +2402,8 @@ def test_update_business_info_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: call.return_value = businessinfo.BusinessInfo() client.update_business_info(request=None) @@ -1899,8 +2424,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = BusinessInfoServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1916,14 +2440,16 @@ async def test_get_business_info_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo( + name="name_value", + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number="korean_business_registration_number_value", + ) + ) await client.get_business_info(request=None) # Establish that the underlying stub method was called. @@ -1945,14 +2471,16 @@ async def test_update_business_info_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + businessinfo.BusinessInfo( + name="name_value", + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number="korean_business_registration_number_value", + ) + ) await client.update_business_info(request=None) # Establish that the underlying stub method was called. @@ -1970,20 +2498,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_business_info_rest_bad_request(request_type=businessinfo.GetBusinessInfoRequest): +def test_get_business_info_rest_bad_request( + request_type=businessinfo.GetBusinessInfoRequest, +): client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessInfo'} + request_init = {"name": "accounts/sample1/businessInfo"} 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() @@ -1992,27 +2523,29 @@ def test_get_business_info_rest_bad_request(request_type=businessinfo.GetBusines client.get_business_info(request) -@pytest.mark.parametrize("request_type", [ - businessinfo.GetBusinessInfoRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + businessinfo.GetBusinessInfoRequest, + dict, + ], +) def test_get_business_info_rest_call_success(request_type): client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/businessInfo'} + request_init = {"name": "accounts/sample1/businessInfo"} request = request_type(**request_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 = businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', + name="name_value", + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number="korean_business_registration_number_value", ) # Wrap the value into a proper Response obj @@ -2022,35 +2555,52 @@ def test_get_business_info_rest_call_success(request_type): # Convert return value to protobuf type return_value = businessinfo.BusinessInfo.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_business_info(request) # Establish that the response is the type that we expect. assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' + assert response.name == "name_value" + assert ( + response.phone_verification_state + == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + ) + assert ( + response.korean_business_registration_number + == "korean_business_registration_number_value" + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_business_info_rest_interceptors(null_interceptor): transport = transports.BusinessInfoServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.BusinessInfoServiceRestInterceptor(), + ) client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_get_business_info") as post, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_get_business_info_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_get_business_info") 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.BusinessInfoServiceRestInterceptor, "post_get_business_info" + ) as post, mock.patch.object( + transports.BusinessInfoServiceRestInterceptor, + "post_get_business_info_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BusinessInfoServiceRestInterceptor, "pre_get_business_info" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = businessinfo.GetBusinessInfoRequest.pb(businessinfo.GetBusinessInfoRequest()) + pb_message = businessinfo.GetBusinessInfoRequest.pb( + businessinfo.GetBusinessInfoRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2065,7 +2615,7 @@ def test_get_business_info_rest_interceptors(null_interceptor): req.return_value.content = return_value request = businessinfo.GetBusinessInfoRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2073,27 +2623,36 @@ def test_get_business_info_rest_interceptors(null_interceptor): post.return_value = businessinfo.BusinessInfo() post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata - client.get_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_business_info( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_business_info_rest_bad_request(request_type=businessinfo.UpdateBusinessInfoRequest): +def test_update_business_info_rest_bad_request( + request_type=businessinfo.UpdateBusinessInfoRequest, +): client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} + request_init = {"business_info": {"name": "accounts/sample1/businessInfo"}} 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() @@ -2102,19 +2661,47 @@ def test_update_business_info_rest_bad_request(request_type=businessinfo.UpdateB client.update_business_info(request) -@pytest.mark.parametrize("request_type", [ - businessinfo.UpdateBusinessInfoRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + businessinfo.UpdateBusinessInfoRequest, + dict, + ], +) def test_update_business_info_rest_call_success(request_type): client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'business_info': {'name': 'accounts/sample1/businessInfo'}} - request_init["business_info"] = {'name': 'accounts/sample1/businessInfo', 'address': {'revision': 879, 'region_code': 'region_code_value', 'language_code': 'language_code_value', 'postal_code': 'postal_code_value', 'sorting_code': 'sorting_code_value', 'administrative_area': 'administrative_area_value', 'locality': 'locality_value', 'sublocality': 'sublocality_value', 'address_lines': ['address_lines_value1', 'address_lines_value2'], 'recipients': ['recipients_value1', 'recipients_value2'], 'organization': 'organization_value'}, 'phone': {'e164_number': 'e164_number_value', 'short_code': {'region_code': 'region_code_value', 'number': 'number_value'}, 'extension': 'extension_value'}, 'phone_verification_state': 1, 'customer_service': {'uri': 'uri_value', 'email': 'email_value', 'phone': {}}, 'korean_business_registration_number': 'korean_business_registration_number_value'} + request_init = {"business_info": {"name": "accounts/sample1/businessInfo"}} + request_init["business_info"] = { + "name": "accounts/sample1/businessInfo", + "address": { + "revision": 879, + "region_code": "region_code_value", + "language_code": "language_code_value", + "postal_code": "postal_code_value", + "sorting_code": "sorting_code_value", + "administrative_area": "administrative_area_value", + "locality": "locality_value", + "sublocality": "sublocality_value", + "address_lines": ["address_lines_value1", "address_lines_value2"], + "recipients": ["recipients_value1", "recipients_value2"], + "organization": "organization_value", + }, + "phone": { + "e164_number": "e164_number_value", + "short_code": { + "region_code": "region_code_value", + "number": "number_value", + }, + "extension": "extension_value", + }, + "phone_verification_state": 1, + "customer_service": {"uri": "uri_value", "email": "email_value", "phone": {}}, + "korean_business_registration_number": "korean_business_registration_number_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 @@ -2134,7 +2721,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 @@ -2148,7 +2735,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["business_info"].items(): # pragma: NO COVER + for field, value in request_init["business_info"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2163,12 +2750,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") @@ -2181,12 +2772,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 = businessinfo.BusinessInfo( - name='name_value', - phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, - korean_business_registration_number='korean_business_registration_number_value', + name="name_value", + phone_verification_state=phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED, + korean_business_registration_number="korean_business_registration_number_value", ) # Wrap the value into a proper Response obj @@ -2196,35 +2787,52 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = businessinfo.BusinessInfo.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_business_info(request) # Establish that the response is the type that we expect. assert isinstance(response, businessinfo.BusinessInfo) - assert response.name == 'name_value' - assert response.phone_verification_state == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED - assert response.korean_business_registration_number == 'korean_business_registration_number_value' + assert response.name == "name_value" + assert ( + response.phone_verification_state + == phoneverificationstate.PhoneVerificationState.PHONE_VERIFICATION_STATE_VERIFIED + ) + assert ( + response.korean_business_registration_number + == "korean_business_registration_number_value" + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_business_info_rest_interceptors(null_interceptor): transport = transports.BusinessInfoServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BusinessInfoServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.BusinessInfoServiceRestInterceptor(), + ) client = BusinessInfoServiceClient(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.BusinessInfoServiceRestInterceptor, "post_update_business_info") as post, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "post_update_business_info_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.BusinessInfoServiceRestInterceptor, "pre_update_business_info") 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.BusinessInfoServiceRestInterceptor, "post_update_business_info" + ) as post, mock.patch.object( + transports.BusinessInfoServiceRestInterceptor, + "post_update_business_info_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.BusinessInfoServiceRestInterceptor, "pre_update_business_info" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = businessinfo.UpdateBusinessInfoRequest.pb(businessinfo.UpdateBusinessInfoRequest()) + pb_message = businessinfo.UpdateBusinessInfoRequest.pb( + businessinfo.UpdateBusinessInfoRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2239,7 +2847,7 @@ def test_update_business_info_rest_interceptors(null_interceptor): req.return_value.content = return_value request = businessinfo.UpdateBusinessInfoRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2247,16 +2855,22 @@ def test_update_business_info_rest_interceptors(null_interceptor): post.return_value = businessinfo.BusinessInfo() post_with_metadata.return_value = businessinfo.BusinessInfo(), metadata - client.update_business_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_business_info( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = BusinessInfoServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2271,8 +2885,8 @@ def test_get_business_info_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_business_info), - '__call__') as call: + type(client.transport.get_business_info), "__call__" + ) as call: client.get_business_info(request=None) # Establish that the underlying stub method was called. @@ -2293,8 +2907,8 @@ def test_update_business_info_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_business_info), - '__call__') as call: + type(client.transport.update_business_info), "__call__" + ) as call: client.update_business_info(request=None) # Establish that the underlying stub method was called. @@ -2315,18 +2929,21 @@ def test_transport_grpc_default(): transports.BusinessInfoServiceGrpcTransport, ) + def test_business_info_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.BusinessInfoServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_business_info_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.BusinessInfoServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2335,8 +2952,8 @@ def test_business_info_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_business_info', - 'update_business_info', + "get_business_info", + "update_business_info", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2347,7 +2964,7 @@ def test_business_info_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2356,25 +2973,30 @@ def test_business_info_service_base_transport(): def test_business_info_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_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport._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_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BusinessInfoServiceTransport( 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_business_info_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_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.business_info_service.transports.BusinessInfoServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.BusinessInfoServiceTransport() @@ -2383,14 +3005,12 @@ def test_business_info_service_base_transport_with_adc(): def test_business_info_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) BusinessInfoServiceClient() 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, ) @@ -2405,12 +3025,12 @@ def test_business_info_service_auth_adc(): def test_business_info_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", ) @@ -2424,48 +3044,45 @@ def test_business_info_service_transport_auth_adc(transport_class): ], ) def test_business_info_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.BusinessInfoServiceGrpcTransport, grpc_helpers), - (transports.BusinessInfoServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.BusinessInfoServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_business_info_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, @@ -2476,9 +3093,15 @@ def test_business_info_service_transport_create_channel(transport_class, grpc_he ) -@pytest.mark.parametrize("transport_class", [transports.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + ], +) def test_business_info_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2488,7 +3111,7 @@ def test_business_info_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", @@ -2509,61 +3132,77 @@ def test_business_info_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_business_info_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.BusinessInfoServiceRestTransport ( - 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.BusinessInfoServiceRestTransport( + 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_business_info_service_host_no_port(transport_name): client = BusinessInfoServiceClient( 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_business_info_service_host_with_port(transport_name): client = BusinessInfoServiceClient( 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_business_info_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2581,8 +3220,10 @@ def test_business_info_service_client_transport_session_collision(transport_name session1 = client1.transport.update_business_info._session session2 = client2.transport.update_business_info._session assert session1 != session2 + + def test_business_info_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.BusinessInfoServiceGrpcTransport( @@ -2595,7 +3236,7 @@ def test_business_info_service_grpc_transport_channel(): def test_business_info_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.BusinessInfoServiceGrpcAsyncIOTransport( @@ -2609,12 +3250,22 @@ def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + ], +) def test_business_info_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 @@ -2623,7 +3274,7 @@ def test_business_info_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", @@ -2653,17 +3304,23 @@ def test_business_info_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.BusinessInfoServiceGrpcTransport, transports.BusinessInfoServiceGrpcAsyncIOTransport]) -def test_business_info_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.BusinessInfoServiceGrpcTransport, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + ], +) +def test_business_info_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() @@ -2693,7 +3350,9 @@ def test_business_info_service_transport_channel_mtls_with_adc( def test_business_info_path(): account = "squid" - expected = "accounts/{account}/businessInfo".format(account=account, ) + expected = "accounts/{account}/businessInfo".format( + account=account, + ) actual = BusinessInfoServiceClient.business_info_path(account) assert expected == actual @@ -2708,9 +3367,12 @@ def test_parse_business_info_path(): actual = BusinessInfoServiceClient.parse_business_info_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = BusinessInfoServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2725,9 +3387,12 @@ def test_parse_common_billing_account_path(): actual = BusinessInfoServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = BusinessInfoServiceClient.common_folder_path(folder) assert expected == actual @@ -2742,9 +3407,12 @@ def test_parse_common_folder_path(): actual = BusinessInfoServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = BusinessInfoServiceClient.common_organization_path(organization) assert expected == actual @@ -2759,9 +3427,12 @@ def test_parse_common_organization_path(): actual = BusinessInfoServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = BusinessInfoServiceClient.common_project_path(project) assert expected == actual @@ -2776,10 +3447,14 @@ def test_parse_common_project_path(): actual = BusinessInfoServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = BusinessInfoServiceClient.common_location_path(project, location) assert expected == actual @@ -2799,14 +3474,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.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.BusinessInfoServiceTransport, "_prep_wrapped_messages" + ) as prep: client = BusinessInfoServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.BusinessInfoServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.BusinessInfoServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = BusinessInfoServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2817,10 +3496,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = BusinessInfoServiceClient( - 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() @@ -2829,10 +3509,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = BusinessInfoServiceAsyncClient( - 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() @@ -2840,10 +3521,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = BusinessInfoServiceClient( - 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() @@ -2851,13 +3533,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = BusinessInfoServiceClient( - 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: @@ -2866,10 +3547,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport), - (BusinessInfoServiceAsyncClient, transports.BusinessInfoServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (BusinessInfoServiceClient, transports.BusinessInfoServiceGrpcTransport), + ( + BusinessInfoServiceAsyncClient, + transports.BusinessInfoServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2884,7 +3572,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py index 2e57c5160d4d..2f28b060d8cd 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_checkout_settings_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,46 +22,44 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.checkout_settings_service import CheckoutSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.checkout_settings_service import CheckoutSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.checkout_settings_service import transports -from google.shopping.merchant_accounts_v1.types import checkoutsettings from google.shopping.type.types import types -import google.auth - +from google.shopping.merchant_accounts_v1.services.checkout_settings_service import ( + CheckoutSettingsServiceAsyncClient, + CheckoutSettingsServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import checkoutsettings CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +74,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(): @@ -85,17 +86,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(): @@ -106,101 +117,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CheckoutSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + CheckoutSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CheckoutSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + CheckoutSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert CheckoutSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (True, "auto", None) + assert CheckoutSettingsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert CheckoutSettingsServiceClient._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: CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._read_environment_variables() == (False, "never", None) + assert CheckoutSettingsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "always", None) + assert CheckoutSettingsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert CheckoutSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, False) is None - assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + CheckoutSettingsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + CheckoutSettingsServiceClient._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 ( + CheckoutSettingsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert CheckoutSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +@mock.patch.object( + CheckoutSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceClient), +) +@mock.patch.object( + CheckoutSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert CheckoutSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CheckoutSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert CheckoutSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == CheckoutSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + CheckoutSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - CheckoutSettingsServiceClient._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." + CheckoutSettingsServiceClient._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 CheckoutSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert CheckoutSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert CheckoutSettingsServiceClient._get_universe_domain(None, None) == CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + assert ( + CheckoutSettingsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + CheckoutSettingsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + CheckoutSettingsServiceClient._get_universe_domain(None, None) + == CheckoutSettingsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: CheckoutSettingsServiceClient._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) @@ -216,7 +371,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") @@ -229,14 +385,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", [ - (CheckoutSettingsServiceClient, "grpc"), - (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), - (CheckoutSettingsServiceClient, "rest"), -]) -def test_checkout_settings_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CheckoutSettingsServiceClient, "grpc"), + (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), + (CheckoutSettingsServiceClient, "rest"), + ], +) +def test_checkout_settings_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) @@ -244,52 +408,70 @@ def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, "grpc"), - (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.CheckoutSettingsServiceRestTransport, "rest"), -]) -def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, "grpc"), + (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CheckoutSettingsServiceRestTransport, "rest"), + ], +) +def test_checkout_settings_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", [ - (CheckoutSettingsServiceClient, "grpc"), - (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), - (CheckoutSettingsServiceClient, "rest"), -]) -def test_checkout_settings_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (CheckoutSettingsServiceClient, "grpc"), + (CheckoutSettingsServiceAsyncClient, "grpc_asyncio"), + (CheckoutSettingsServiceClient, "rest"), + ], +) +def test_checkout_settings_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" ) @@ -305,30 +487,53 @@ def test_checkout_settings_service_client_get_transport_class(): assert transport == transports.CheckoutSettingsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) -def test_checkout_settings_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + "grpc", + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + CheckoutSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceClient), +) +@mock.patch.object( + CheckoutSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient), +) +def test_checkout_settings_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(CheckoutSettingsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(CheckoutSettingsServiceClient, "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(CheckoutSettingsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(CheckoutSettingsServiceClient, "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( @@ -346,13 +551,15 @@ def test_checkout_settings_service_client_client_options(client_class, transport # 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, @@ -364,7 +571,7 @@ def test_checkout_settings_service_client_client_options(client_class, transport # 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( @@ -384,23 +591,33 @@ def test_checkout_settings_service_client_client_options(client_class, transport 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", @@ -409,48 +626,102 @@ def test_checkout_settings_service_client_client_options(client_class, transport 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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "true"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", "false"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "true"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + "grpc", + "true", + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + "grpc", + "false", + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceRestTransport, + "rest", + "true", + ), + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + CheckoutSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceClient), +) +@mock.patch.object( + CheckoutSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_checkout_settings_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_checkout_settings_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 @@ -469,12 +740,22 @@ def test_checkout_settings_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 @@ -495,15 +776,22 @@ def test_checkout_settings_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, @@ -513,19 +801,33 @@ def test_checkout_settings_service_client_mtls_env_auto(client_class, transport_ ) -@pytest.mark.parametrize("client_class", [ - CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient -]) -@mock.patch.object(CheckoutSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CheckoutSettingsServiceAsyncClient)) -def test_checkout_settings_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient] +) +@mock.patch.object( + CheckoutSettingsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CheckoutSettingsServiceClient), +) +@mock.patch.object( + CheckoutSettingsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(CheckoutSettingsServiceAsyncClient), +) +def test_checkout_settings_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 @@ -533,8 +835,12 @@ def test_checkout_settings_service_client_get_mtls_endpoint_and_cert_source(clie 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 @@ -552,16 +858,28 @@ def test_checkout_settings_service_client_get_mtls_endpoint_and_cert_source(clie # 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 @@ -571,34 +889,62 @@ def test_checkout_settings_service_client_get_mtls_endpoint_and_cert_source(clie 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", [ - CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient -]) -@mock.patch.object(CheckoutSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceClient)) -@mock.patch.object(CheckoutSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [CheckoutSettingsServiceClient, CheckoutSettingsServiceAsyncClient] +) +@mock.patch.object( + CheckoutSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceClient), +) +@mock.patch.object( + CheckoutSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(CheckoutSettingsServiceAsyncClient), +) def test_checkout_settings_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = CheckoutSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = CheckoutSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = CheckoutSettingsServiceClient._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", @@ -621,11 +967,19 @@ def test_checkout_settings_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. @@ -633,27 +987,48 @@ def test_checkout_settings_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", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc"), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest"), -]) -def test_checkout_settings_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + "grpc", + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceRestTransport, + "rest", + ), + ], +) +def test_checkout_settings_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, @@ -662,24 +1037,45 @@ def test_checkout_settings_service_client_client_options_scopes(client_class, tr api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceRestTransport, "rest", None), -]) -def test_checkout_settings_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", + [ + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_checkout_settings_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, @@ -688,11 +1084,14 @@ def test_checkout_settings_service_client_client_options_credentials_file(client api_audience=None, ) + def test_checkout_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = CheckoutSettingsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1106,38 @@ def test_checkout_settings_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_checkout_settings_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", + [ + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_checkout_settings_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, @@ -750,9 +1164,7 @@ def test_checkout_settings_service_client_create_channel_credentials_file(client 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, @@ -763,11 +1175,14 @@ def test_checkout_settings_service_client_create_channel_credentials_file(client ) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.GetCheckoutSettingsRequest, - dict, -]) -def test_get_checkout_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.GetCheckoutSettingsRequest, + dict, + ], +) +def test_get_checkout_settings(request_type, transport: str = "grpc"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,11 +1194,11 @@ def test_get_checkout_settings(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings( - name='name_value', + name="name_value", eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, @@ -800,12 +1215,26 @@ def test_get_checkout_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) def test_get_checkout_settings_non_empty_request_with_auto_populated_field(): @@ -813,28 +1242,31 @@ def test_get_checkout_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = CheckoutSettingsServiceClient( 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 = checkoutsettings.GetCheckoutSettingsRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_checkout_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_checkout_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == checkoutsettings.GetCheckoutSettingsRequest( - name='name_value', + name="name_value", ) + def test_get_checkout_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -849,12 +1281,19 @@ def test_get_checkout_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.get_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_checkout_settings + ] = mock_rpc request = {} client.get_checkout_settings(request) @@ -867,8 +1306,11 @@ def test_get_checkout_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_checkout_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_checkout_settings_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: @@ -882,12 +1324,17 @@ async def test_get_checkout_settings_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_checkout_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_checkout_settings + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_checkout_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_checkout_settings + ] = mock_rpc request = {} await client.get_checkout_settings(request) @@ -901,8 +1348,12 @@ async def test_get_checkout_settings_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.GetCheckoutSettingsRequest): +async def test_get_checkout_settings_async( + transport: str = "grpc_asyncio", + request_type=checkoutsettings.GetCheckoutSettingsRequest, +): client = CheckoutSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -914,17 +1365,19 @@ async def test_get_checkout_settings_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings( + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + ) response = await client.get_checkout_settings(request) # Establish that the underlying gRPC stub method was called. @@ -935,18 +1388,33 @@ async def test_get_checkout_settings_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) @pytest.mark.asyncio async def test_get_checkout_settings_async_from_dict(): await test_get_checkout_settings_async(request_type=dict) + def test_get_checkout_settings_field_headers(): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -956,12 +1424,12 @@ def test_get_checkout_settings_field_headers(): # a field header. Set these to a non-empty value. request = checkoutsettings.GetCheckoutSettingsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: call.return_value = checkoutsettings.CheckoutSettings() client.get_checkout_settings(request) @@ -973,9 +1441,9 @@ def test_get_checkout_settings_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 @@ -988,13 +1456,15 @@ async def test_get_checkout_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = checkoutsettings.GetCheckoutSettingsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + type(client.transport.get_checkout_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings() + ) await client.get_checkout_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1005,9 +1475,9 @@ async def test_get_checkout_settings_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_checkout_settings_flattened(): @@ -1017,14 +1487,14 @@ def test_get_checkout_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_checkout_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1032,7 +1502,7 @@ def test_get_checkout_settings_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 @@ -1046,9 +1516,10 @@ def test_get_checkout_settings_flattened_error(): with pytest.raises(ValueError): client.get_checkout_settings( checkoutsettings.GetCheckoutSettingsRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_checkout_settings_flattened_async(): client = CheckoutSettingsServiceAsyncClient( @@ -1057,16 +1528,18 @@ async def test_get_checkout_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_checkout_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1074,9 +1547,10 @@ async def test_get_checkout_settings_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_checkout_settings_flattened_error_async(): client = CheckoutSettingsServiceAsyncClient( @@ -1088,15 +1562,18 @@ async def test_get_checkout_settings_flattened_error_async(): with pytest.raises(ValueError): await client.get_checkout_settings( checkoutsettings.GetCheckoutSettingsRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.CreateCheckoutSettingsRequest, - dict, -]) -def test_create_checkout_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.CreateCheckoutSettingsRequest, + dict, + ], +) +def test_create_checkout_settings(request_type, transport: str = "grpc"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1108,11 +1585,11 @@ def test_create_checkout_settings(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings( - name='name_value', + name="name_value", eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, @@ -1129,12 +1606,26 @@ def test_create_checkout_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) def test_create_checkout_settings_non_empty_request_with_auto_populated_field(): @@ -1142,28 +1633,31 @@ def test_create_checkout_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = CheckoutSettingsServiceClient( 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 = checkoutsettings.CreateCheckoutSettingsRequest( - 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.create_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.create_checkout_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_checkout_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == checkoutsettings.CreateCheckoutSettingsRequest( - parent='parent_value', + parent="parent_value", ) + def test_create_checkout_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1178,12 +1672,19 @@ def test_create_checkout_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.create_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_checkout_settings + ] = mock_rpc request = {} client.create_checkout_settings(request) @@ -1196,8 +1697,11 @@ def test_create_checkout_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_checkout_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_checkout_settings_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: @@ -1211,12 +1715,17 @@ async def test_create_checkout_settings_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_checkout_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_checkout_settings + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_checkout_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_checkout_settings + ] = mock_rpc request = {} await client.create_checkout_settings(request) @@ -1230,8 +1739,12 @@ async def test_create_checkout_settings_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.CreateCheckoutSettingsRequest): +async def test_create_checkout_settings_async( + transport: str = "grpc_asyncio", + request_type=checkoutsettings.CreateCheckoutSettingsRequest, +): client = CheckoutSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1243,17 +1756,19 @@ async def test_create_checkout_settings_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings( + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + ) response = await client.create_checkout_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1264,18 +1779,33 @@ async def test_create_checkout_settings_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) @pytest.mark.asyncio async def test_create_checkout_settings_async_from_dict(): await test_create_checkout_settings_async(request_type=dict) + def test_create_checkout_settings_field_headers(): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1285,12 +1815,12 @@ def test_create_checkout_settings_field_headers(): # a field header. Set these to a non-empty value. request = checkoutsettings.CreateCheckoutSettingsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: call.return_value = checkoutsettings.CheckoutSettings() client.create_checkout_settings(request) @@ -1302,9 +1832,9 @@ def test_create_checkout_settings_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 @@ -1317,13 +1847,15 @@ async def test_create_checkout_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = checkoutsettings.CreateCheckoutSettingsRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + type(client.transport.create_checkout_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings() + ) await client.create_checkout_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1334,9 +1866,9 @@ async def test_create_checkout_settings_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_checkout_settings_flattened(): @@ -1346,15 +1878,15 @@ def test_create_checkout_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_checkout_settings( - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + parent="parent_value", + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -1362,10 +1894,10 @@ def test_create_checkout_settings_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') + mock_val = checkoutsettings.CheckoutSettings(name="name_value") assert arg == mock_val @@ -1379,10 +1911,11 @@ def test_create_checkout_settings_flattened_error(): with pytest.raises(ValueError): client.create_checkout_settings( checkoutsettings.CreateCheckoutSettingsRequest(), - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + parent="parent_value", + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), ) + @pytest.mark.asyncio async def test_create_checkout_settings_flattened_async(): client = CheckoutSettingsServiceAsyncClient( @@ -1391,17 +1924,19 @@ async def test_create_checkout_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_checkout_settings( - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + parent="parent_value", + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), ) # Establish that the underlying call was made with the expected @@ -1409,12 +1944,13 @@ async def test_create_checkout_settings_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') + mock_val = checkoutsettings.CheckoutSettings(name="name_value") assert arg == mock_val + @pytest.mark.asyncio async def test_create_checkout_settings_flattened_error_async(): client = CheckoutSettingsServiceAsyncClient( @@ -1426,16 +1962,19 @@ async def test_create_checkout_settings_flattened_error_async(): with pytest.raises(ValueError): await client.create_checkout_settings( checkoutsettings.CreateCheckoutSettingsRequest(), - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + parent="parent_value", + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), ) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.UpdateCheckoutSettingsRequest, - dict, -]) -def test_update_checkout_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.UpdateCheckoutSettingsRequest, + dict, + ], +) +def test_update_checkout_settings(request_type, transport: str = "grpc"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1447,11 +1986,11 @@ def test_update_checkout_settings(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings( - name='name_value', + name="name_value", eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, @@ -1468,12 +2007,26 @@ def test_update_checkout_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) def test_update_checkout_settings_non_empty_request_with_auto_populated_field(): @@ -1481,25 +2034,26 @@ def test_update_checkout_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = CheckoutSettingsServiceClient( 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 = checkoutsettings.UpdateCheckoutSettingsRequest( - ) + request = checkoutsettings.UpdateCheckoutSettingsRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_checkout_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_checkout_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == checkoutsettings.UpdateCheckoutSettingsRequest( - ) + assert args[0] == checkoutsettings.UpdateCheckoutSettingsRequest() + def test_update_checkout_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1515,12 +2069,19 @@ def test_update_checkout_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.update_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_checkout_settings + ] = mock_rpc request = {} client.update_checkout_settings(request) @@ -1533,8 +2094,11 @@ def test_update_checkout_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_checkout_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_checkout_settings_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: @@ -1548,12 +2112,17 @@ async def test_update_checkout_settings_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_checkout_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_checkout_settings + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_checkout_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_checkout_settings + ] = mock_rpc request = {} await client.update_checkout_settings(request) @@ -1567,8 +2136,12 @@ async def test_update_checkout_settings_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.UpdateCheckoutSettingsRequest): +async def test_update_checkout_settings_async( + transport: str = "grpc_asyncio", + request_type=checkoutsettings.UpdateCheckoutSettingsRequest, +): client = CheckoutSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1580,17 +2153,19 @@ async def test_update_checkout_settings_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings( + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + ) response = await client.update_checkout_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1601,18 +2176,33 @@ async def test_update_checkout_settings_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) @pytest.mark.asyncio async def test_update_checkout_settings_async_from_dict(): await test_update_checkout_settings_async(request_type=dict) + def test_update_checkout_settings_field_headers(): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1622,12 +2212,12 @@ def test_update_checkout_settings_field_headers(): # a field header. Set these to a non-empty value. request = checkoutsettings.UpdateCheckoutSettingsRequest() - request.checkout_settings.name = 'name_value' + request.checkout_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: call.return_value = checkoutsettings.CheckoutSettings() client.update_checkout_settings(request) @@ -1639,9 +2229,9 @@ def test_update_checkout_settings_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'checkout_settings.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "checkout_settings.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1654,13 +2244,15 @@ async def test_update_checkout_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = checkoutsettings.UpdateCheckoutSettingsRequest() - request.checkout_settings.name = 'name_value' + request.checkout_settings.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + type(client.transport.update_checkout_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings() + ) await client.update_checkout_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1671,9 +2263,9 @@ async def test_update_checkout_settings_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'checkout_settings.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "checkout_settings.name=name_value", + ) in kw["metadata"] def test_update_checkout_settings_flattened(): @@ -1683,15 +2275,15 @@ def test_update_checkout_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_checkout_settings( - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1699,10 +2291,10 @@ def test_update_checkout_settings_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') + mock_val = checkoutsettings.CheckoutSettings(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1716,10 +2308,11 @@ def test_update_checkout_settings_flattened_error(): with pytest.raises(ValueError): client.update_checkout_settings( checkoutsettings.UpdateCheckoutSettingsRequest(), - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_checkout_settings_flattened_async(): client = CheckoutSettingsServiceAsyncClient( @@ -1728,17 +2321,19 @@ async def test_update_checkout_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = checkoutsettings.CheckoutSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_checkout_settings( - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1746,12 +2341,13 @@ async def test_update_checkout_settings_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].checkout_settings - mock_val = checkoutsettings.CheckoutSettings(name='name_value') + mock_val = checkoutsettings.CheckoutSettings(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_checkout_settings_flattened_error_async(): client = CheckoutSettingsServiceAsyncClient( @@ -1763,16 +2359,19 @@ async def test_update_checkout_settings_flattened_error_async(): with pytest.raises(ValueError): await client.update_checkout_settings( checkoutsettings.UpdateCheckoutSettingsRequest(), - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.DeleteCheckoutSettingsRequest, - dict, -]) -def test_delete_checkout_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.DeleteCheckoutSettingsRequest, + dict, + ], +) +def test_delete_checkout_settings(request_type, transport: str = "grpc"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1784,8 +2383,8 @@ def test_delete_checkout_settings(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_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_checkout_settings(request) @@ -1805,28 +2404,31 @@ def test_delete_checkout_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = CheckoutSettingsServiceClient( 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 = checkoutsettings.DeleteCheckoutSettingsRequest( - 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_checkout_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.delete_checkout_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_checkout_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == checkoutsettings.DeleteCheckoutSettingsRequest( - name='name_value', + name="name_value", ) + def test_delete_checkout_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1841,12 +2443,19 @@ def test_delete_checkout_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.delete_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_checkout_settings] = 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_checkout_settings + ] = mock_rpc request = {} client.delete_checkout_settings(request) @@ -1859,8 +2468,11 @@ def test_delete_checkout_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_checkout_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_checkout_settings_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: @@ -1874,12 +2486,17 @@ async def test_delete_checkout_settings_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_checkout_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_checkout_settings + 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_checkout_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_checkout_settings + ] = mock_rpc request = {} await client.delete_checkout_settings(request) @@ -1893,8 +2510,12 @@ async def test_delete_checkout_settings_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_checkout_settings_async(transport: str = 'grpc_asyncio', request_type=checkoutsettings.DeleteCheckoutSettingsRequest): +async def test_delete_checkout_settings_async( + transport: str = "grpc_asyncio", + request_type=checkoutsettings.DeleteCheckoutSettingsRequest, +): client = CheckoutSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1906,8 +2527,8 @@ async def test_delete_checkout_settings_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_checkout_settings(request) @@ -1926,6 +2547,7 @@ async def test_delete_checkout_settings_async(transport: str = 'grpc_asyncio', r async def test_delete_checkout_settings_async_from_dict(): await test_delete_checkout_settings_async(request_type=dict) + def test_delete_checkout_settings_field_headers(): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1935,12 +2557,12 @@ def test_delete_checkout_settings_field_headers(): # a field header. Set these to a non-empty value. request = checkoutsettings.DeleteCheckoutSettingsRequest() - 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_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: call.return_value = None client.delete_checkout_settings(request) @@ -1952,9 +2574,9 @@ def test_delete_checkout_settings_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 @@ -1967,12 +2589,12 @@ async def test_delete_checkout_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = checkoutsettings.DeleteCheckoutSettingsRequest() - 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_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_checkout_settings(request) @@ -1984,9 +2606,9 @@ async def test_delete_checkout_settings_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_checkout_settings_flattened(): @@ -1996,14 +2618,14 @@ def test_delete_checkout_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__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_checkout_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2011,7 +2633,7 @@ def test_delete_checkout_settings_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 @@ -2025,9 +2647,10 @@ def test_delete_checkout_settings_flattened_error(): with pytest.raises(ValueError): client.delete_checkout_settings( checkoutsettings.DeleteCheckoutSettingsRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_checkout_settings_flattened_async(): client = CheckoutSettingsServiceAsyncClient( @@ -2036,8 +2659,8 @@ async def test_delete_checkout_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -2045,7 +2668,7 @@ async def test_delete_checkout_settings_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_checkout_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2053,9 +2676,10 @@ async def test_delete_checkout_settings_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_checkout_settings_flattened_error_async(): client = CheckoutSettingsServiceAsyncClient( @@ -2067,7 +2691,7 @@ async def test_delete_checkout_settings_flattened_error_async(): with pytest.raises(ValueError): await client.delete_checkout_settings( checkoutsettings.DeleteCheckoutSettingsRequest(), - name='name_value', + name="name_value", ) @@ -2085,12 +2709,19 @@ def test_get_checkout_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.get_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_checkout_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_checkout_settings + ] = mock_rpc request = {} client.get_checkout_settings(request) @@ -2105,55 +2736,60 @@ def test_get_checkout_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_checkout_settings_rest_required_fields(request_type=checkoutsettings.GetCheckoutSettingsRequest): +def test_get_checkout_settings_rest_required_fields( + request_type=checkoutsettings.GetCheckoutSettingsRequest, +): transport_class = transports.CheckoutSettingsServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_checkout_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_checkout_settings._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 = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = checkoutsettings.CheckoutSettings() # Mock the http request 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 @@ -2164,24 +2800,24 @@ def test_get_checkout_settings_rest_required_fields(request_type=checkoutsetting return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_checkout_settings(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_checkout_settings_rest_flattened(): @@ -2191,16 +2827,16 @@ def test_get_checkout_settings_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 = checkoutsettings.CheckoutSettings() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + sample_request = {"name": "accounts/sample1/programs/sample2/checkoutSettings"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2210,7 +2846,7 @@ def test_get_checkout_settings_rest_flattened(): # Convert return value to protobuf type return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2220,10 +2856,14 @@ def test_get_checkout_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}" + % client.transport._host, + args[1], + ) -def test_get_checkout_settings_rest_flattened_error(transport: str = 'rest'): +def test_get_checkout_settings_rest_flattened_error(transport: str = "rest"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2234,7 +2874,7 @@ def test_get_checkout_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_checkout_settings( checkoutsettings.GetCheckoutSettingsRequest(), - name='name_value', + name="name_value", ) @@ -2252,12 +2892,19 @@ def test_create_checkout_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.create_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_checkout_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_checkout_settings + ] = mock_rpc request = {} client.create_checkout_settings(request) @@ -2272,57 +2919,62 @@ def test_create_checkout_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_checkout_settings_rest_required_fields(request_type=checkoutsettings.CreateCheckoutSettingsRequest): +def test_create_checkout_settings_rest_required_fields( + request_type=checkoutsettings.CreateCheckoutSettingsRequest, +): transport_class = transports.CheckoutSettingsServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_checkout_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_checkout_settings._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 = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = checkoutsettings.CheckoutSettings() # Mock the http request 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() @@ -2332,24 +2984,32 @@ def test_create_checkout_settings_rest_required_fields(request_type=checkoutsett return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_checkout_settings(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "checkoutSettings", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "checkoutSettings", + ) + ) + ) def test_create_checkout_settings_rest_flattened(): @@ -2359,17 +3019,17 @@ def test_create_checkout_settings_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 = checkoutsettings.CheckoutSettings() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/programs/sample2'} + sample_request = {"parent": "accounts/sample1/programs/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + parent="parent_value", + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), ) mock_args.update(sample_request) @@ -2379,7 +3039,7 @@ def test_create_checkout_settings_rest_flattened(): # Convert return value to protobuf type return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2389,10 +3049,14 @@ def test_create_checkout_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*/programs/*}/checkoutSettings" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*/programs/*}/checkoutSettings" + % client.transport._host, + args[1], + ) -def test_create_checkout_settings_rest_flattened_error(transport: str = 'rest'): +def test_create_checkout_settings_rest_flattened_error(transport: str = "rest"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2403,8 +3067,8 @@ def test_create_checkout_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_checkout_settings( checkoutsettings.CreateCheckoutSettingsRequest(), - parent='parent_value', - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), + parent="parent_value", + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), ) @@ -2422,12 +3086,19 @@ def test_update_checkout_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.update_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_checkout_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_checkout_settings + ] = mock_rpc request = {} client.update_checkout_settings(request) @@ -2442,54 +3113,59 @@ def test_update_checkout_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_checkout_settings_rest_required_fields(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): +def test_update_checkout_settings_rest_required_fields( + request_type=checkoutsettings.UpdateCheckoutSettingsRequest, +): transport_class = transports.CheckoutSettingsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_checkout_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_checkout_settings._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = checkoutsettings.CheckoutSettings() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2499,24 +3175,32 @@ def test_update_checkout_settings_rest_required_fields(request_type=checkoutsett return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_checkout_settings(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("checkoutSettings", "updateMask", ))) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "checkoutSettings", + "updateMask", + ) + ) + ) def test_update_checkout_settings_rest_flattened(): @@ -2526,17 +3210,21 @@ def test_update_checkout_settings_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 = checkoutsettings.CheckoutSettings() # get arguments that satisfy an http rule for this method - sample_request = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + sample_request = { + "checkout_settings": { + "name": "accounts/sample1/programs/sample2/checkoutSettings" + } + } # get truthy value for each flattened field mock_args = dict( - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -2546,7 +3234,7 @@ def test_update_checkout_settings_rest_flattened(): # Convert return value to protobuf type return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2556,10 +3244,14 @@ def test_update_checkout_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{checkout_settings.name=accounts/*/programs/*/checkoutSettings}" + % client.transport._host, + args[1], + ) -def test_update_checkout_settings_rest_flattened_error(transport: str = 'rest'): +def test_update_checkout_settings_rest_flattened_error(transport: str = "rest"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2570,8 +3262,8 @@ def test_update_checkout_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_checkout_settings( checkoutsettings.UpdateCheckoutSettingsRequest(), - checkout_settings=checkoutsettings.CheckoutSettings(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + checkout_settings=checkoutsettings.CheckoutSettings(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2589,12 +3281,19 @@ def test_delete_checkout_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_checkout_settings in client._transport._wrapped_methods + assert ( + client._transport.delete_checkout_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_checkout_settings] = 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_checkout_settings + ] = mock_rpc request = {} client.delete_checkout_settings(request) @@ -2609,80 +3308,85 @@ def test_delete_checkout_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_checkout_settings_rest_required_fields(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): +def test_delete_checkout_settings_rest_required_fields( + request_type=checkoutsettings.DeleteCheckoutSettingsRequest, +): transport_class = transports.CheckoutSettingsServiceRestTransport 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_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_checkout_settings._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_checkout_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_checkout_settings._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 = CheckoutSettingsServiceClient( 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_checkout_settings(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_checkout_settings_rest_unset_required_fields(): - transport = transports.CheckoutSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.CheckoutSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_checkout_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_delete_checkout_settings_rest_flattened(): @@ -2692,24 +3396,24 @@ def test_delete_checkout_settings_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/programs/sample2/checkoutSettings'} + sample_request = {"name": "accounts/sample1/programs/sample2/checkoutSettings"} # 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"} @@ -2719,10 +3423,14 @@ def test_delete_checkout_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/programs/*/checkoutSettings}" + % client.transport._host, + args[1], + ) -def test_delete_checkout_settings_rest_flattened_error(transport: str = 'rest'): +def test_delete_checkout_settings_rest_flattened_error(transport: str = "rest"): client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2733,7 +3441,7 @@ def test_delete_checkout_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_checkout_settings( checkoutsettings.DeleteCheckoutSettingsRequest(), - name='name_value', + name="name_value", ) @@ -2775,8 +3483,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = CheckoutSettingsServiceClient( - 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. @@ -2798,6 +3505,7 @@ def test_transport_instance(): client = CheckoutSettingsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CheckoutSettingsServiceGrpcTransport( @@ -2812,18 +3520,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.CheckoutSettingsServiceGrpcTransport, - transports.CheckoutSettingsServiceGrpcAsyncIOTransport, - transports.CheckoutSettingsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + transports.CheckoutSettingsServiceRestTransport, + ], +) 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 = CheckoutSettingsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2833,8 +3546,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2849,8 +3561,8 @@ def test_get_checkout_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: call.return_value = checkoutsettings.CheckoutSettings() client.get_checkout_settings(request=None) @@ -2872,8 +3584,8 @@ def test_create_checkout_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: call.return_value = checkoutsettings.CheckoutSettings() client.create_checkout_settings(request=None) @@ -2895,8 +3607,8 @@ def test_update_checkout_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: call.return_value = checkoutsettings.CheckoutSettings() client.update_checkout_settings(request=None) @@ -2918,8 +3630,8 @@ def test_delete_checkout_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: call.return_value = None client.delete_checkout_settings(request=None) @@ -2940,8 +3652,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = CheckoutSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2957,17 +3668,19 @@ async def test_get_checkout_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings( + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + ) await client.get_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -2989,17 +3702,19 @@ async def test_create_checkout_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings( + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + ) await client.create_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -3021,17 +3736,19 @@ async def test_update_checkout_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + checkoutsettings.CheckoutSettings( + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + ) + ) await client.update_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -3053,8 +3770,8 @@ async def test_delete_checkout_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_checkout_settings(request=None) @@ -3074,20 +3791,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_checkout_settings_rest_bad_request(request_type=checkoutsettings.GetCheckoutSettingsRequest): +def test_get_checkout_settings_rest_bad_request( + request_type=checkoutsettings.GetCheckoutSettingsRequest, +): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request_init = {"name": "accounts/sample1/programs/sample2/checkoutSettings"} 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() @@ -3096,30 +3816,32 @@ def test_get_checkout_settings_rest_bad_request(request_type=checkoutsettings.Ge client.get_checkout_settings(request) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.GetCheckoutSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.GetCheckoutSettingsRequest, + dict, + ], +) def test_get_checkout_settings_rest_call_success(request_type): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request_init = {"name": "accounts/sample1/programs/sample2/checkoutSettings"} request = request_type(**request_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 = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, ) # Wrap the value into a proper Response obj @@ -3129,38 +3851,63 @@ def test_get_checkout_settings_rest_call_success(request_type): # Convert return value to protobuf type return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_checkout_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_checkout_settings_rest_interceptors(null_interceptor): transport = transports.CheckoutSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.CheckoutSettingsServiceRestInterceptor(), + ) client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings") as post, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_get_checkout_settings") 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.CheckoutSettingsServiceRestInterceptor, "post_get_checkout_settings" + ) as post, mock.patch.object( + transports.CheckoutSettingsServiceRestInterceptor, + "post_get_checkout_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.CheckoutSettingsServiceRestInterceptor, "pre_get_checkout_settings" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = checkoutsettings.GetCheckoutSettingsRequest.pb(checkoutsettings.GetCheckoutSettingsRequest()) + pb_message = checkoutsettings.GetCheckoutSettingsRequest.pb( + checkoutsettings.GetCheckoutSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3171,11 +3918,13 @@ def test_get_checkout_settings_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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + return_value = checkoutsettings.CheckoutSettings.to_json( + checkoutsettings.CheckoutSettings() + ) req.return_value.content = return_value request = checkoutsettings.GetCheckoutSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3183,27 +3932,36 @@ def test_get_checkout_settings_rest_interceptors(null_interceptor): post.return_value = checkoutsettings.CheckoutSettings() post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata - client.get_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_checkout_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_create_checkout_settings_rest_bad_request(request_type=checkoutsettings.CreateCheckoutSettingsRequest): +def test_create_checkout_settings_rest_bad_request( + request_type=checkoutsettings.CreateCheckoutSettingsRequest, +): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/programs/sample2'} + request_init = {"parent": "accounts/sample1/programs/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() @@ -3212,25 +3970,41 @@ def test_create_checkout_settings_rest_bad_request(request_type=checkoutsettings client.create_checkout_settings(request) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.CreateCheckoutSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.CreateCheckoutSettingsRequest, + dict, + ], +) def test_create_checkout_settings_rest_call_success(request_type): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/programs/sample2'} - request_init["checkout_settings"] = {'name': 'name_value', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 1} + request_init = {"parent": "accounts/sample1/programs/sample2"} + request_init["checkout_settings"] = { + "name": "name_value", + "uri_settings": { + "checkout_uri_template": "checkout_uri_template_value", + "cart_uri_template": "cart_uri_template_value", + }, + "eligible_destinations": [1], + "enrollment_state": 1, + "review_state": 1, + "effective_uri_settings": {}, + "effective_enrollment_state": 1, + "effective_review_state": 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 = checkoutsettings.CreateCheckoutSettingsRequest.meta.fields["checkout_settings"] + test_field = checkoutsettings.CreateCheckoutSettingsRequest.meta.fields[ + "checkout_settings" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -3244,7 +4018,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 @@ -3258,7 +4032,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["checkout_settings"].items(): # pragma: NO COVER + for field, value in request_init["checkout_settings"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3273,12 +4047,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") @@ -3291,15 +4069,15 @@ 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 = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, ) # Wrap the value into a proper Response obj @@ -3309,38 +4087,65 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_checkout_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_checkout_settings_rest_interceptors(null_interceptor): transport = transports.CheckoutSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.CheckoutSettingsServiceRestInterceptor(), + ) client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings") as post, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_create_checkout_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_create_checkout_settings") 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.CheckoutSettingsServiceRestInterceptor, + "post_create_checkout_settings", + ) as post, mock.patch.object( + transports.CheckoutSettingsServiceRestInterceptor, + "post_create_checkout_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.CheckoutSettingsServiceRestInterceptor, + "pre_create_checkout_settings", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = checkoutsettings.CreateCheckoutSettingsRequest.pb(checkoutsettings.CreateCheckoutSettingsRequest()) + pb_message = checkoutsettings.CreateCheckoutSettingsRequest.pb( + checkoutsettings.CreateCheckoutSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3351,11 +4156,13 @@ def test_create_checkout_settings_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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + return_value = checkoutsettings.CheckoutSettings.to_json( + checkoutsettings.CheckoutSettings() + ) req.return_value.content = return_value request = checkoutsettings.CreateCheckoutSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3363,27 +4170,40 @@ def test_create_checkout_settings_rest_interceptors(null_interceptor): post.return_value = checkoutsettings.CheckoutSettings() post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata - client.create_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_checkout_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_checkout_settings_rest_bad_request(request_type=checkoutsettings.UpdateCheckoutSettingsRequest): +def test_update_checkout_settings_rest_bad_request( + request_type=checkoutsettings.UpdateCheckoutSettingsRequest, +): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} + request_init = { + "checkout_settings": { + "name": "accounts/sample1/programs/sample2/checkoutSettings" + } + } 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() @@ -3392,25 +4212,45 @@ def test_update_checkout_settings_rest_bad_request(request_type=checkoutsettings client.update_checkout_settings(request) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.UpdateCheckoutSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.UpdateCheckoutSettingsRequest, + dict, + ], +) def test_update_checkout_settings_rest_call_success(request_type): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'checkout_settings': {'name': 'accounts/sample1/programs/sample2/checkoutSettings'}} - request_init["checkout_settings"] = {'name': 'accounts/sample1/programs/sample2/checkoutSettings', 'uri_settings': {'checkout_uri_template': 'checkout_uri_template_value', 'cart_uri_template': 'cart_uri_template_value'}, 'eligible_destinations': [1], 'enrollment_state': 1, 'review_state': 1, 'effective_uri_settings': {}, 'effective_enrollment_state': 1, 'effective_review_state': 1} + request_init = { + "checkout_settings": { + "name": "accounts/sample1/programs/sample2/checkoutSettings" + } + } + request_init["checkout_settings"] = { + "name": "accounts/sample1/programs/sample2/checkoutSettings", + "uri_settings": { + "checkout_uri_template": "checkout_uri_template_value", + "cart_uri_template": "cart_uri_template_value", + }, + "eligible_destinations": [1], + "enrollment_state": 1, + "review_state": 1, + "effective_uri_settings": {}, + "effective_enrollment_state": 1, + "effective_review_state": 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 = checkoutsettings.UpdateCheckoutSettingsRequest.meta.fields["checkout_settings"] + test_field = checkoutsettings.UpdateCheckoutSettingsRequest.meta.fields[ + "checkout_settings" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -3424,7 +4264,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 @@ -3438,7 +4278,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["checkout_settings"].items(): # pragma: NO COVER + for field, value in request_init["checkout_settings"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3453,12 +4293,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") @@ -3471,15 +4315,15 @@ 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 = checkoutsettings.CheckoutSettings( - name='name_value', - eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], - enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, - effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, - effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + name="name_value", + eligible_destinations=[types.Destination.DestinationEnum.SHOPPING_ADS], + enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, + effective_enrollment_state=checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE, + effective_review_state=checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW, ) # Wrap the value into a proper Response obj @@ -3489,38 +4333,65 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = checkoutsettings.CheckoutSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_checkout_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, checkoutsettings.CheckoutSettings) - assert response.name == 'name_value' - assert response.eligible_destinations == [types.Destination.DestinationEnum.SHOPPING_ADS] - assert response.enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW - assert response.effective_enrollment_state == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE - assert response.effective_review_state == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + assert response.name == "name_value" + assert response.eligible_destinations == [ + types.Destination.DestinationEnum.SHOPPING_ADS + ] + assert ( + response.enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) + assert ( + response.effective_enrollment_state + == checkoutsettings.CheckoutSettings.CheckoutEnrollmentState.INACTIVE + ) + assert ( + response.effective_review_state + == checkoutsettings.CheckoutSettings.CheckoutReviewState.IN_REVIEW + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_checkout_settings_rest_interceptors(null_interceptor): transport = transports.CheckoutSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.CheckoutSettingsServiceRestInterceptor(), + ) client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings") as post, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "post_update_checkout_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.CheckoutSettingsServiceRestInterceptor, "pre_update_checkout_settings") 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.CheckoutSettingsServiceRestInterceptor, + "post_update_checkout_settings", + ) as post, mock.patch.object( + transports.CheckoutSettingsServiceRestInterceptor, + "post_update_checkout_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.CheckoutSettingsServiceRestInterceptor, + "pre_update_checkout_settings", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = checkoutsettings.UpdateCheckoutSettingsRequest.pb(checkoutsettings.UpdateCheckoutSettingsRequest()) + pb_message = checkoutsettings.UpdateCheckoutSettingsRequest.pb( + checkoutsettings.UpdateCheckoutSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3531,11 +4402,13 @@ def test_update_checkout_settings_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 = checkoutsettings.CheckoutSettings.to_json(checkoutsettings.CheckoutSettings()) + return_value = checkoutsettings.CheckoutSettings.to_json( + checkoutsettings.CheckoutSettings() + ) req.return_value.content = return_value request = checkoutsettings.UpdateCheckoutSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3543,27 +4416,36 @@ def test_update_checkout_settings_rest_interceptors(null_interceptor): post.return_value = checkoutsettings.CheckoutSettings() post_with_metadata.return_value = checkoutsettings.CheckoutSettings(), metadata - client.update_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_checkout_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_checkout_settings_rest_bad_request(request_type=checkoutsettings.DeleteCheckoutSettingsRequest): +def test_delete_checkout_settings_rest_bad_request( + request_type=checkoutsettings.DeleteCheckoutSettingsRequest, +): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request_init = {"name": "accounts/sample1/programs/sample2/checkoutSettings"} 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() @@ -3572,30 +4454,32 @@ def test_delete_checkout_settings_rest_bad_request(request_type=checkoutsettings client.delete_checkout_settings(request) -@pytest.mark.parametrize("request_type", [ - checkoutsettings.DeleteCheckoutSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + checkoutsettings.DeleteCheckoutSettingsRequest, + dict, + ], +) def test_delete_checkout_settings_rest_call_success(request_type): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2/checkoutSettings'} + request_init = {"name": "accounts/sample1/programs/sample2/checkoutSettings"} request = request_type(**request_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_checkout_settings(request) @@ -3608,15 +4492,24 @@ def test_delete_checkout_settings_rest_call_success(request_type): def test_delete_checkout_settings_rest_interceptors(null_interceptor): transport = transports.CheckoutSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CheckoutSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.CheckoutSettingsServiceRestInterceptor(), + ) client = CheckoutSettingsServiceClient(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.CheckoutSettingsServiceRestInterceptor, "pre_delete_checkout_settings") 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.CheckoutSettingsServiceRestInterceptor, + "pre_delete_checkout_settings", + ) as pre: pre.assert_not_called() - pb_message = checkoutsettings.DeleteCheckoutSettingsRequest.pb(checkoutsettings.DeleteCheckoutSettingsRequest()) + pb_message = checkoutsettings.DeleteCheckoutSettingsRequest.pb( + checkoutsettings.DeleteCheckoutSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3629,20 +4522,26 @@ def test_delete_checkout_settings_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = checkoutsettings.DeleteCheckoutSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_checkout_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_checkout_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() + def test_initialize_client_w_rest(): client = CheckoutSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -3657,8 +4556,8 @@ def test_get_checkout_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_checkout_settings), - '__call__') as call: + type(client.transport.get_checkout_settings), "__call__" + ) as call: client.get_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -3679,8 +4578,8 @@ def test_create_checkout_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_checkout_settings), - '__call__') as call: + type(client.transport.create_checkout_settings), "__call__" + ) as call: client.create_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -3701,8 +4600,8 @@ def test_update_checkout_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_checkout_settings), - '__call__') as call: + type(client.transport.update_checkout_settings), "__call__" + ) as call: client.update_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -3723,8 +4622,8 @@ def test_delete_checkout_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_checkout_settings), - '__call__') as call: + type(client.transport.delete_checkout_settings), "__call__" + ) as call: client.delete_checkout_settings(request=None) # Establish that the underlying stub method was called. @@ -3745,18 +4644,21 @@ def test_transport_grpc_default(): transports.CheckoutSettingsServiceGrpcTransport, ) + def test_checkout_settings_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.CheckoutSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_checkout_settings_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.CheckoutSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3765,10 +4667,10 @@ def test_checkout_settings_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_checkout_settings', - 'create_checkout_settings', - 'update_checkout_settings', - 'delete_checkout_settings', + "get_checkout_settings", + "create_checkout_settings", + "update_checkout_settings", + "delete_checkout_settings", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3779,7 +4681,7 @@ def test_checkout_settings_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3788,25 +4690,30 @@ def test_checkout_settings_service_base_transport(): def test_checkout_settings_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_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._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_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CheckoutSettingsServiceTransport( 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_checkout_settings_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_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.checkout_settings_service.transports.CheckoutSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CheckoutSettingsServiceTransport() @@ -3815,14 +4722,12 @@ def test_checkout_settings_service_base_transport_with_adc(): def test_checkout_settings_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) CheckoutSettingsServiceClient() 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, ) @@ -3837,12 +4742,12 @@ def test_checkout_settings_service_auth_adc(): def test_checkout_settings_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", ) @@ -3856,48 +4761,47 @@ def test_checkout_settings_service_transport_auth_adc(transport_class): ], ) def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, grpc_helpers), - (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.CheckoutSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_checkout_settings_service_transport_create_channel(transport_class, grpc_helpers): +def test_checkout_settings_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, @@ -3908,9 +4812,15 @@ def test_checkout_settings_service_transport_create_channel(transport_class, grp ) -@pytest.mark.parametrize("transport_class", [transports.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + ], +) def test_checkout_settings_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -3920,7 +4830,7 @@ def test_checkout_settings_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", @@ -3941,61 +4851,77 @@ def test_checkout_settings_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_checkout_settings_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.CheckoutSettingsServiceRestTransport ( - 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.CheckoutSettingsServiceRestTransport( + 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_checkout_settings_service_host_no_port(transport_name): client = CheckoutSettingsServiceClient( 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_checkout_settings_service_host_with_port(transport_name): client = CheckoutSettingsServiceClient( 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_checkout_settings_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4019,8 +4945,10 @@ def test_checkout_settings_service_client_transport_session_collision(transport_ session1 = client1.transport.delete_checkout_settings._session session2 = client2.transport.delete_checkout_settings._session assert session1 != session2 + + def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport( @@ -4033,7 +4961,7 @@ def test_checkout_settings_service_grpc_transport_channel(): def test_checkout_settings_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.CheckoutSettingsServiceGrpcAsyncIOTransport( @@ -4047,12 +4975,22 @@ def test_checkout_settings_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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + ], +) def test_checkout_settings_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 @@ -4061,7 +4999,7 @@ def test_checkout_settings_service_transport_channel_mtls_with_client_cert_sourc 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", @@ -4091,17 +5029,23 @@ def test_checkout_settings_service_transport_channel_mtls_with_client_cert_sourc # 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.CheckoutSettingsServiceGrpcTransport, transports.CheckoutSettingsServiceGrpcAsyncIOTransport]) -def test_checkout_settings_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.CheckoutSettingsServiceGrpcTransport, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_checkout_settings_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() @@ -4132,7 +5076,10 @@ def test_checkout_settings_service_transport_channel_mtls_with_adc( def test_checkout_settings_path(): account = "squid" program = "clam" - expected = "accounts/{account}/programs/{program}/checkoutSettings".format(account=account, program=program, ) + expected = "accounts/{account}/programs/{program}/checkoutSettings".format( + account=account, + program=program, + ) actual = CheckoutSettingsServiceClient.checkout_settings_path(account, program) assert expected == actual @@ -4148,9 +5095,12 @@ def test_parse_checkout_settings_path(): actual = CheckoutSettingsServiceClient.parse_checkout_settings_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = CheckoutSettingsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -4165,9 +5115,12 @@ def test_parse_common_billing_account_path(): actual = CheckoutSettingsServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = CheckoutSettingsServiceClient.common_folder_path(folder) assert expected == actual @@ -4182,9 +5135,12 @@ def test_parse_common_folder_path(): actual = CheckoutSettingsServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = CheckoutSettingsServiceClient.common_organization_path(organization) assert expected == actual @@ -4199,9 +5155,12 @@ def test_parse_common_organization_path(): actual = CheckoutSettingsServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = CheckoutSettingsServiceClient.common_project_path(project) assert expected == actual @@ -4216,10 +5175,14 @@ def test_parse_common_project_path(): actual = CheckoutSettingsServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = CheckoutSettingsServiceClient.common_location_path(project, location) assert expected == actual @@ -4239,14 +5202,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.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.CheckoutSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = CheckoutSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.CheckoutSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.CheckoutSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = CheckoutSettingsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -4257,10 +5224,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = CheckoutSettingsServiceClient( - 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() @@ -4269,10 +5237,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = CheckoutSettingsServiceAsyncClient( - 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() @@ -4280,10 +5249,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = CheckoutSettingsServiceClient( - 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() @@ -4291,13 +5261,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = CheckoutSettingsServiceClient( - 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: @@ -4306,10 +5275,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (CheckoutSettingsServiceClient, transports.CheckoutSettingsServiceGrpcTransport), - (CheckoutSettingsServiceAsyncClient, transports.CheckoutSettingsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + CheckoutSettingsServiceClient, + transports.CheckoutSettingsServiceGrpcTransport, + ), + ( + CheckoutSettingsServiceAsyncClient, + transports.CheckoutSettingsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -4324,7 +5303,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py index cd958ad19b4c..60906ed1ad0b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_developer_registration_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,44 +22,42 @@ 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.shopping.merchant_accounts_v1.services.developer_registration_service import DeveloperRegistrationServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.developer_registration_service import DeveloperRegistrationServiceClient -from google.shopping.merchant_accounts_v1.services.developer_registration_service import transports -from google.shopping.merchant_accounts_v1.types import developerregistration -import google.auth - +from google.shopping.merchant_accounts_v1.services.developer_registration_service import ( + DeveloperRegistrationServiceAsyncClient, + DeveloperRegistrationServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import developerregistration CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -73,9 +72,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(): @@ -83,17 +84,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(): @@ -104,101 +115,255 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(None) is None - assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DeveloperRegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + DeveloperRegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + DeveloperRegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + DeveloperRegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + DeveloperRegistrationServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + DeveloperRegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", None) + assert DeveloperRegistrationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert DeveloperRegistrationServiceClient._read_environment_variables() == (True, "auto", None) + assert DeveloperRegistrationServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", None) + assert DeveloperRegistrationServiceClient._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: DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._read_environment_variables() == (False, "never", None) + assert DeveloperRegistrationServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "always", None) + assert DeveloperRegistrationServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", None) + assert DeveloperRegistrationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._get_client_cert_source(None, False) is None - assert DeveloperRegistrationServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert DeveloperRegistrationServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + DeveloperRegistrationServiceClient._get_client_cert_source(None, False) is None + ) + assert ( + DeveloperRegistrationServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + DeveloperRegistrationServiceClient._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 ( + DeveloperRegistrationServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert DeveloperRegistrationServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) -@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) +@mock.patch.object( + DeveloperRegistrationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceClient), +) +@mock.patch.object( + DeveloperRegistrationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE - default_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) - assert DeveloperRegistrationServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert DeveloperRegistrationServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, default_universe, "always") == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeveloperRegistrationServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT - assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert DeveloperRegistrationServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == DeveloperRegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + DeveloperRegistrationServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - DeveloperRegistrationServiceClient._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." + DeveloperRegistrationServiceClient._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 DeveloperRegistrationServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert DeveloperRegistrationServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert DeveloperRegistrationServiceClient._get_universe_domain(None, None) == DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + assert ( + DeveloperRegistrationServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + DeveloperRegistrationServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + DeveloperRegistrationServiceClient._get_universe_domain(None, None) + == DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: DeveloperRegistrationServiceClient._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) @@ -214,7 +379,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") @@ -227,14 +393,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", [ - (DeveloperRegistrationServiceClient, "grpc"), - (DeveloperRegistrationServiceAsyncClient, "grpc_asyncio"), - (DeveloperRegistrationServiceClient, "rest"), -]) -def test_developer_registration_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DeveloperRegistrationServiceClient, "grpc"), + (DeveloperRegistrationServiceAsyncClient, "grpc_asyncio"), + (DeveloperRegistrationServiceClient, "rest"), + ], +) +def test_developer_registration_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) @@ -242,52 +416,70 @@ def test_developer_registration_service_client_from_service_account_info(client_ 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.DeveloperRegistrationServiceGrpcTransport, "grpc"), - (transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DeveloperRegistrationServiceRestTransport, "rest"), -]) -def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, "grpc"), + (transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DeveloperRegistrationServiceRestTransport, "rest"), + ], +) +def test_developer_registration_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", [ - (DeveloperRegistrationServiceClient, "grpc"), - (DeveloperRegistrationServiceAsyncClient, "grpc_asyncio"), - (DeveloperRegistrationServiceClient, "rest"), -]) -def test_developer_registration_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DeveloperRegistrationServiceClient, "grpc"), + (DeveloperRegistrationServiceAsyncClient, "grpc_asyncio"), + (DeveloperRegistrationServiceClient, "rest"), + ], +) +def test_developer_registration_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" ) @@ -303,30 +495,57 @@ def test_developer_registration_service_client_get_transport_class(): assert transport == transports.DeveloperRegistrationServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc"), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest"), -]) -@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) -@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) -def test_developer_registration_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + "grpc", + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + DeveloperRegistrationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceClient), +) +@mock.patch.object( + DeveloperRegistrationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient), +) +def test_developer_registration_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(DeveloperRegistrationServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + DeveloperRegistrationServiceClient, "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(DeveloperRegistrationServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + DeveloperRegistrationServiceClient, "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( @@ -344,13 +563,15 @@ def test_developer_registration_service_client_client_options(client_class, tran # 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, @@ -362,7 +583,7 @@ def test_developer_registration_service_client_client_options(client_class, tran # 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( @@ -382,23 +603,33 @@ def test_developer_registration_service_client_client_options(client_class, tran 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", @@ -407,48 +638,102 @@ def test_developer_registration_service_client_client_options(client_class, tran 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", [ - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", "true"), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", "false"), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest", "true"), - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) -@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + "grpc", + "true", + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + "grpc", + "false", + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceRestTransport, + "rest", + "true", + ), + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + DeveloperRegistrationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceClient), +) +@mock.patch.object( + DeveloperRegistrationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_developer_registration_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_developer_registration_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 @@ -467,12 +752,22 @@ def test_developer_registration_service_client_mtls_env_auto(client_class, trans # 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 @@ -493,15 +788,22 @@ def test_developer_registration_service_client_mtls_env_auto(client_class, trans ) # 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, @@ -511,19 +813,34 @@ def test_developer_registration_service_client_mtls_env_auto(client_class, trans ) -@pytest.mark.parametrize("client_class", [ - DeveloperRegistrationServiceClient, DeveloperRegistrationServiceAsyncClient -]) -@mock.patch.object(DeveloperRegistrationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeveloperRegistrationServiceClient)) -@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DeveloperRegistrationServiceAsyncClient)) -def test_developer_registration_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [DeveloperRegistrationServiceClient, DeveloperRegistrationServiceAsyncClient], +) +@mock.patch.object( + DeveloperRegistrationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DeveloperRegistrationServiceClient), +) +@mock.patch.object( + DeveloperRegistrationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DeveloperRegistrationServiceAsyncClient), +) +def test_developer_registration_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 @@ -531,8 +848,12 @@ def test_developer_registration_service_client_get_mtls_endpoint_and_cert_source 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 @@ -550,16 +871,28 @@ def test_developer_registration_service_client_get_mtls_endpoint_and_cert_source # 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 @@ -569,34 +902,67 @@ def test_developer_registration_service_client_get_mtls_endpoint_and_cert_source 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", [ - DeveloperRegistrationServiceClient, DeveloperRegistrationServiceAsyncClient -]) -@mock.patch.object(DeveloperRegistrationServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceClient)) -@mock.patch.object(DeveloperRegistrationServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [DeveloperRegistrationServiceClient, DeveloperRegistrationServiceAsyncClient], +) +@mock.patch.object( + DeveloperRegistrationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceClient), +) +@mock.patch.object( + DeveloperRegistrationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(DeveloperRegistrationServiceAsyncClient), +) def test_developer_registration_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = DeveloperRegistrationServiceClient._DEFAULT_UNIVERSE - default_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = DeveloperRegistrationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + DeveloperRegistrationServiceClient._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", @@ -619,11 +985,19 @@ def test_developer_registration_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. @@ -631,27 +1005,48 @@ def test_developer_registration_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", [ - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc"), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest"), -]) -def test_developer_registration_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + "grpc", + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceRestTransport, + "rest", + ), + ], +) +def test_developer_registration_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, @@ -660,24 +1055,45 @@ def test_developer_registration_service_client_client_options_scopes(client_clas api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", grpc_helpers), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceRestTransport, "rest", None), -]) -def test_developer_registration_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", + [ + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceRestTransport, + "rest", + None, + ), + ], +) +def test_developer_registration_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, @@ -686,11 +1102,14 @@ def test_developer_registration_service_client_client_options_credentials_file(c api_audience=None, ) + def test_developer_registration_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = DeveloperRegistrationServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -705,23 +1124,38 @@ def test_developer_registration_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport, "grpc", grpc_helpers), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_developer_registration_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", + [ + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_developer_registration_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, @@ -748,9 +1182,7 @@ def test_developer_registration_service_client_create_channel_credentials_file(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, @@ -761,11 +1193,14 @@ def test_developer_registration_service_client_create_channel_credentials_file(c ) -@pytest.mark.parametrize("request_type", [ - developerregistration.RegisterGcpRequest, - dict, -]) -def test_register_gcp(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + developerregistration.RegisterGcpRequest, + dict, + ], +) +def test_register_gcp(request_type, transport: str = "grpc"): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -776,13 +1211,11 @@ def test_register_gcp(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.register_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], + name="name_value", + gcp_ids=["gcp_ids_value"], ) response = client.register_gcp(request) @@ -794,8 +1227,8 @@ def test_register_gcp(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, developerregistration.DeveloperRegistration) - assert response.name == 'name_value' - assert response.gcp_ids == ['gcp_ids_value'] + assert response.name == "name_value" + assert response.gcp_ids == ["gcp_ids_value"] def test_register_gcp_non_empty_request_with_auto_populated_field(): @@ -803,30 +1236,31 @@ def test_register_gcp_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = DeveloperRegistrationServiceClient( 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 = developerregistration.RegisterGcpRequest( - name='name_value', - developer_email='developer_email_value', + name="name_value", + developer_email="developer_email_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.register_gcp), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.register_gcp(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == developerregistration.RegisterGcpRequest( - name='name_value', - developer_email='developer_email_value', + name="name_value", + developer_email="developer_email_value", ) + def test_register_gcp_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -845,7 +1279,9 @@ def test_register_gcp_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.register_gcp] = mock_rpc request = {} client.register_gcp(request) @@ -859,8 +1295,11 @@ def test_register_gcp_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_register_gcp_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_register_gcp_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: @@ -874,12 +1313,17 @@ async def test_register_gcp_async_use_cached_wrapped_rpc(transport: str = "grpc_ wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.register_gcp in client._client._transport._wrapped_methods + assert ( + client._client._transport.register_gcp + 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.register_gcp] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.register_gcp + ] = mock_rpc request = {} await client.register_gcp(request) @@ -893,8 +1337,12 @@ async def test_register_gcp_async_use_cached_wrapped_rpc(transport: str = "grpc_ assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_register_gcp_async(transport: str = 'grpc_asyncio', request_type=developerregistration.RegisterGcpRequest): +async def test_register_gcp_async( + transport: str = "grpc_asyncio", + request_type=developerregistration.RegisterGcpRequest, +): client = DeveloperRegistrationServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -905,14 +1353,14 @@ async def test_register_gcp_async(transport: str = 'grpc_asyncio', request_type= request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.register_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration( + name="name_value", + gcp_ids=["gcp_ids_value"], + ) + ) response = await client.register_gcp(request) # Establish that the underlying gRPC stub method was called. @@ -923,14 +1371,15 @@ async def test_register_gcp_async(transport: str = 'grpc_asyncio', request_type= # Establish that the response is the type that we expect. assert isinstance(response, developerregistration.DeveloperRegistration) - assert response.name == 'name_value' - assert response.gcp_ids == ['gcp_ids_value'] + assert response.name == "name_value" + assert response.gcp_ids == ["gcp_ids_value"] @pytest.mark.asyncio async def test_register_gcp_async_from_dict(): await test_register_gcp_async(request_type=dict) + def test_register_gcp_field_headers(): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -940,12 +1389,10 @@ def test_register_gcp_field_headers(): # a field header. Set these to a non-empty value. request = developerregistration.RegisterGcpRequest() - 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.register_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: call.return_value = developerregistration.DeveloperRegistration() client.register_gcp(request) @@ -957,9 +1404,9 @@ def test_register_gcp_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 @@ -972,13 +1419,13 @@ async def test_register_gcp_field_headers_async(): # a field header. Set these to a non-empty value. request = developerregistration.RegisterGcpRequest() - 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.register_gcp), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration()) + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration() + ) await client.register_gcp(request) # Establish that the underlying gRPC stub method was called. @@ -989,16 +1436,19 @@ async def test_register_gcp_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"] -@pytest.mark.parametrize("request_type", [ - developerregistration.GetDeveloperRegistrationRequest, - dict, -]) -def test_get_developer_registration(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + developerregistration.GetDeveloperRegistrationRequest, + dict, + ], +) +def test_get_developer_registration(request_type, transport: str = "grpc"): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1010,12 +1460,12 @@ def test_get_developer_registration(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], + name="name_value", + gcp_ids=["gcp_ids_value"], ) response = client.get_developer_registration(request) @@ -1027,8 +1477,8 @@ def test_get_developer_registration(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, developerregistration.DeveloperRegistration) - assert response.name == 'name_value' - assert response.gcp_ids == ['gcp_ids_value'] + assert response.name == "name_value" + assert response.gcp_ids == ["gcp_ids_value"] def test_get_developer_registration_non_empty_request_with_auto_populated_field(): @@ -1036,28 +1486,31 @@ def test_get_developer_registration_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = DeveloperRegistrationServiceClient( 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 = developerregistration.GetDeveloperRegistrationRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_developer_registration), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_developer_registration(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == developerregistration.GetDeveloperRegistrationRequest( - name='name_value', + name="name_value", ) + def test_get_developer_registration_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1072,12 +1525,19 @@ def test_get_developer_registration_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_developer_registration in client._transport._wrapped_methods + assert ( + client._transport.get_developer_registration + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_developer_registration] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_developer_registration + ] = mock_rpc request = {} client.get_developer_registration(request) @@ -1090,8 +1550,11 @@ def test_get_developer_registration_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_developer_registration_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_developer_registration_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: @@ -1105,12 +1568,17 @@ async def test_get_developer_registration_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_developer_registration in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_developer_registration + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_developer_registration] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_developer_registration + ] = mock_rpc request = {} await client.get_developer_registration(request) @@ -1124,8 +1592,12 @@ async def test_get_developer_registration_async_use_cached_wrapped_rpc(transport assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_developer_registration_async(transport: str = 'grpc_asyncio', request_type=developerregistration.GetDeveloperRegistrationRequest): +async def test_get_developer_registration_async( + transport: str = "grpc_asyncio", + request_type=developerregistration.GetDeveloperRegistrationRequest, +): client = DeveloperRegistrationServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1137,13 +1609,15 @@ async def test_get_developer_registration_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration( + name="name_value", + gcp_ids=["gcp_ids_value"], + ) + ) response = await client.get_developer_registration(request) # Establish that the underlying gRPC stub method was called. @@ -1154,14 +1628,15 @@ async def test_get_developer_registration_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, developerregistration.DeveloperRegistration) - assert response.name == 'name_value' - assert response.gcp_ids == ['gcp_ids_value'] + assert response.name == "name_value" + assert response.gcp_ids == ["gcp_ids_value"] @pytest.mark.asyncio async def test_get_developer_registration_async_from_dict(): await test_get_developer_registration_async(request_type=dict) + def test_get_developer_registration_field_headers(): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1171,12 +1646,12 @@ def test_get_developer_registration_field_headers(): # a field header. Set these to a non-empty value. request = developerregistration.GetDeveloperRegistrationRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: call.return_value = developerregistration.DeveloperRegistration() client.get_developer_registration(request) @@ -1188,9 +1663,9 @@ def test_get_developer_registration_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 @@ -1203,13 +1678,15 @@ async def test_get_developer_registration_field_headers_async(): # a field header. Set these to a non-empty value. request = developerregistration.GetDeveloperRegistrationRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration()) + type(client.transport.get_developer_registration), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration() + ) await client.get_developer_registration(request) # Establish that the underlying gRPC stub method was called. @@ -1220,9 +1697,9 @@ async def test_get_developer_registration_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_developer_registration_flattened(): @@ -1232,14 +1709,14 @@ def test_get_developer_registration_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = developerregistration.DeveloperRegistration() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_developer_registration( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1247,7 +1724,7 @@ def test_get_developer_registration_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 @@ -1261,9 +1738,10 @@ def test_get_developer_registration_flattened_error(): with pytest.raises(ValueError): client.get_developer_registration( developerregistration.GetDeveloperRegistrationRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_developer_registration_flattened_async(): client = DeveloperRegistrationServiceAsyncClient( @@ -1272,16 +1750,18 @@ async def test_get_developer_registration_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = developerregistration.DeveloperRegistration() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_developer_registration( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1289,9 +1769,10 @@ async def test_get_developer_registration_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_developer_registration_flattened_error_async(): client = DeveloperRegistrationServiceAsyncClient( @@ -1303,15 +1784,18 @@ async def test_get_developer_registration_flattened_error_async(): with pytest.raises(ValueError): await client.get_developer_registration( developerregistration.GetDeveloperRegistrationRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - developerregistration.UnregisterGcpRequest, - dict, -]) -def test_unregister_gcp(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + developerregistration.UnregisterGcpRequest, + dict, + ], +) +def test_unregister_gcp(request_type, transport: str = "grpc"): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1322,9 +1806,7 @@ def test_unregister_gcp(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None response = client.unregister_gcp(request) @@ -1344,28 +1826,29 @@ def test_unregister_gcp_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = DeveloperRegistrationServiceClient( 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 = developerregistration.UnregisterGcpRequest( - 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.unregister_gcp), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.unregister_gcp(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == developerregistration.UnregisterGcpRequest( - name='name_value', + name="name_value", ) + def test_unregister_gcp_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1384,7 +1867,9 @@ def test_unregister_gcp_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.unregister_gcp] = mock_rpc request = {} client.unregister_gcp(request) @@ -1398,8 +1883,11 @@ def test_unregister_gcp_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_unregister_gcp_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_unregister_gcp_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: @@ -1413,12 +1901,17 @@ async def test_unregister_gcp_async_use_cached_wrapped_rpc(transport: str = "grp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.unregister_gcp in client._client._transport._wrapped_methods + assert ( + client._client._transport.unregister_gcp + 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.unregister_gcp] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.unregister_gcp + ] = mock_rpc request = {} await client.unregister_gcp(request) @@ -1432,8 +1925,12 @@ async def test_unregister_gcp_async_use_cached_wrapped_rpc(transport: str = "grp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_unregister_gcp_async(transport: str = 'grpc_asyncio', request_type=developerregistration.UnregisterGcpRequest): +async def test_unregister_gcp_async( + transport: str = "grpc_asyncio", + request_type=developerregistration.UnregisterGcpRequest, +): client = DeveloperRegistrationServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1444,9 +1941,7 @@ async def test_unregister_gcp_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.unregister_gcp(request) @@ -1465,6 +1960,7 @@ async def test_unregister_gcp_async(transport: str = 'grpc_asyncio', request_typ async def test_unregister_gcp_async_from_dict(): await test_unregister_gcp_async(request_type=dict) + def test_unregister_gcp_field_headers(): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1474,12 +1970,10 @@ def test_unregister_gcp_field_headers(): # a field header. Set these to a non-empty value. request = developerregistration.UnregisterGcpRequest() - 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.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: call.return_value = None client.unregister_gcp(request) @@ -1491,9 +1985,9 @@ def test_unregister_gcp_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 @@ -1506,12 +2000,10 @@ async def test_unregister_gcp_field_headers_async(): # a field header. Set these to a non-empty value. request = developerregistration.UnregisterGcpRequest() - 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.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.unregister_gcp(request) @@ -1523,9 +2015,9 @@ async def test_unregister_gcp_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_register_gcp_rest_use_cached_wrapped_rpc(): @@ -1546,7 +2038,9 @@ def test_register_gcp_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.register_gcp] = mock_rpc request = {} @@ -1562,57 +2056,62 @@ def test_register_gcp_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_register_gcp_rest_required_fields(request_type=developerregistration.RegisterGcpRequest): +def test_register_gcp_rest_required_fields( + request_type=developerregistration.RegisterGcpRequest, +): transport_class = transports.DeveloperRegistrationServiceRestTransport 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()).register_gcp._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).register_gcp._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()).register_gcp._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).register_gcp._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 = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = developerregistration.DeveloperRegistration() # Mock the http request 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() @@ -1622,24 +2121,24 @@ def test_register_gcp_rest_required_fields(request_type=developerregistration.Re return_value = developerregistration.DeveloperRegistration.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.register_gcp(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_register_gcp_rest_unset_required_fields(): - transport = transports.DeveloperRegistrationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DeveloperRegistrationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.register_gcp._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_developer_registration_rest_use_cached_wrapped_rpc(): @@ -1656,12 +2155,19 @@ def test_get_developer_registration_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_developer_registration in client._transport._wrapped_methods + assert ( + client._transport.get_developer_registration + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_developer_registration] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_developer_registration + ] = mock_rpc request = {} client.get_developer_registration(request) @@ -1676,55 +2182,60 @@ def test_get_developer_registration_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_developer_registration_rest_required_fields(request_type=developerregistration.GetDeveloperRegistrationRequest): +def test_get_developer_registration_rest_required_fields( + request_type=developerregistration.GetDeveloperRegistrationRequest, +): transport_class = transports.DeveloperRegistrationServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_developer_registration._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_developer_registration._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_developer_registration._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_developer_registration._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 = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = developerregistration.DeveloperRegistration() # Mock the http request 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 @@ -1735,24 +2246,24 @@ def test_get_developer_registration_rest_required_fields(request_type=developerr return_value = developerregistration.DeveloperRegistration.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_developer_registration(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_developer_registration_rest_unset_required_fields(): - transport = transports.DeveloperRegistrationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DeveloperRegistrationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_developer_registration._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_developer_registration_rest_flattened(): @@ -1762,16 +2273,16 @@ def test_get_developer_registration_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 = developerregistration.DeveloperRegistration() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/developerRegistration'} + sample_request = {"name": "accounts/sample1/developerRegistration"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1781,7 +2292,7 @@ def test_get_developer_registration_rest_flattened(): # Convert return value to protobuf type return_value = developerregistration.DeveloperRegistration.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1791,10 +2302,14 @@ def test_get_developer_registration_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/developerRegistration}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/developerRegistration}" + % client.transport._host, + args[1], + ) -def test_get_developer_registration_rest_flattened_error(transport: str = 'rest'): +def test_get_developer_registration_rest_flattened_error(transport: str = "rest"): client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1805,7 +2320,7 @@ def test_get_developer_registration_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.get_developer_registration( developerregistration.GetDeveloperRegistrationRequest(), - name='name_value', + name="name_value", ) @@ -1827,7 +2342,9 @@ def test_unregister_gcp_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.unregister_gcp] = mock_rpc request = {} @@ -1843,81 +2360,86 @@ def test_unregister_gcp_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_unregister_gcp_rest_required_fields(request_type=developerregistration.UnregisterGcpRequest): +def test_unregister_gcp_rest_required_fields( + request_type=developerregistration.UnregisterGcpRequest, +): transport_class = transports.DeveloperRegistrationServiceRestTransport 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()).unregister_gcp._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).unregister_gcp._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()).unregister_gcp._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).unregister_gcp._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 = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = None # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = '' + json_return_value = "" - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.unregister_gcp(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_unregister_gcp_rest_unset_required_fields(): - transport = transports.DeveloperRegistrationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DeveloperRegistrationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.unregister_gcp._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_credentials_transport_error(): @@ -1958,8 +2480,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = DeveloperRegistrationServiceClient( - 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. @@ -1981,6 +2502,7 @@ def test_transport_instance(): client = DeveloperRegistrationServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DeveloperRegistrationServiceGrpcTransport( @@ -1995,18 +2517,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.DeveloperRegistrationServiceGrpcTransport, - transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, - transports.DeveloperRegistrationServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + transports.DeveloperRegistrationServiceRestTransport, + ], +) 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 = DeveloperRegistrationServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2016,8 +2543,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2031,9 +2557,7 @@ def test_register_gcp_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.register_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: call.return_value = developerregistration.DeveloperRegistration() client.register_gcp(request=None) @@ -2055,8 +2579,8 @@ def test_get_developer_registration_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: call.return_value = developerregistration.DeveloperRegistration() client.get_developer_registration(request=None) @@ -2077,9 +2601,7 @@ def test_unregister_gcp_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: call.return_value = None client.unregister_gcp(request=None) @@ -2092,16 +2614,15 @@ def test_unregister_gcp_empty_call_grpc(): def test_transport_kind_grpc_asyncio(): - transport = DeveloperRegistrationServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = DeveloperRegistrationServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = DeveloperRegistrationServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2116,14 +2637,14 @@ async def test_register_gcp_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.register_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration( + name="name_value", + gcp_ids=["gcp_ids_value"], + ) + ) await client.register_gcp(request=None) # Establish that the underlying stub method was called. @@ -2145,13 +2666,15 @@ async def test_get_developer_registration_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developerregistration.DeveloperRegistration( + name="name_value", + gcp_ids=["gcp_ids_value"], + ) + ) await client.get_developer_registration(request=None) # Establish that the underlying stub method was called. @@ -2172,9 +2695,7 @@ async def test_unregister_gcp_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.unregister_gcp(request=None) @@ -2194,20 +2715,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_register_gcp_rest_bad_request(request_type=developerregistration.RegisterGcpRequest): +def test_register_gcp_rest_bad_request( + request_type=developerregistration.RegisterGcpRequest, +): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/developerRegistration'} + request_init = {"name": "accounts/sample1/developerRegistration"} 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() @@ -2216,26 +2740,28 @@ def test_register_gcp_rest_bad_request(request_type=developerregistration.Regist client.register_gcp(request) -@pytest.mark.parametrize("request_type", [ - developerregistration.RegisterGcpRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + developerregistration.RegisterGcpRequest, + dict, + ], +) def test_register_gcp_rest_call_success(request_type): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/developerRegistration'} + request_init = {"name": "accounts/sample1/developerRegistration"} request = request_type(**request_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 = developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], + name="name_value", + gcp_ids=["gcp_ids_value"], ) # Wrap the value into a proper Response obj @@ -2245,34 +2771,45 @@ def test_register_gcp_rest_call_success(request_type): # Convert return value to protobuf type return_value = developerregistration.DeveloperRegistration.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.register_gcp(request) # Establish that the response is the type that we expect. assert isinstance(response, developerregistration.DeveloperRegistration) - assert response.name == 'name_value' - assert response.gcp_ids == ['gcp_ids_value'] + assert response.name == "name_value" + assert response.gcp_ids == ["gcp_ids_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_register_gcp_rest_interceptors(null_interceptor): transport = transports.DeveloperRegistrationServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeveloperRegistrationServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DeveloperRegistrationServiceRestInterceptor(), + ) client = DeveloperRegistrationServiceClient(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.DeveloperRegistrationServiceRestInterceptor, "post_register_gcp") as post, \ - mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "post_register_gcp_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "pre_register_gcp") 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.DeveloperRegistrationServiceRestInterceptor, "post_register_gcp" + ) as post, mock.patch.object( + transports.DeveloperRegistrationServiceRestInterceptor, + "post_register_gcp_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.DeveloperRegistrationServiceRestInterceptor, "pre_register_gcp" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developerregistration.RegisterGcpRequest.pb(developerregistration.RegisterGcpRequest()) + pb_message = developerregistration.RegisterGcpRequest.pb( + developerregistration.RegisterGcpRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2283,39 +2820,53 @@ def test_register_gcp_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 = developerregistration.DeveloperRegistration.to_json(developerregistration.DeveloperRegistration()) + return_value = developerregistration.DeveloperRegistration.to_json( + developerregistration.DeveloperRegistration() + ) req.return_value.content = return_value request = developerregistration.RegisterGcpRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = developerregistration.DeveloperRegistration() - post_with_metadata.return_value = developerregistration.DeveloperRegistration(), metadata + post_with_metadata.return_value = ( + developerregistration.DeveloperRegistration(), + metadata, + ) - client.register_gcp(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.register_gcp( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_get_developer_registration_rest_bad_request(request_type=developerregistration.GetDeveloperRegistrationRequest): +def test_get_developer_registration_rest_bad_request( + request_type=developerregistration.GetDeveloperRegistrationRequest, +): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/developerRegistration'} + request_init = {"name": "accounts/sample1/developerRegistration"} 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() @@ -2324,26 +2875,28 @@ def test_get_developer_registration_rest_bad_request(request_type=developerregis client.get_developer_registration(request) -@pytest.mark.parametrize("request_type", [ - developerregistration.GetDeveloperRegistrationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + developerregistration.GetDeveloperRegistrationRequest, + dict, + ], +) def test_get_developer_registration_rest_call_success(request_type): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/developerRegistration'} + request_init = {"name": "accounts/sample1/developerRegistration"} request = request_type(**request_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 = developerregistration.DeveloperRegistration( - name='name_value', - gcp_ids=['gcp_ids_value'], + name="name_value", + gcp_ids=["gcp_ids_value"], ) # Wrap the value into a proper Response obj @@ -2353,34 +2906,47 @@ def test_get_developer_registration_rest_call_success(request_type): # Convert return value to protobuf type return_value = developerregistration.DeveloperRegistration.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_developer_registration(request) # Establish that the response is the type that we expect. assert isinstance(response, developerregistration.DeveloperRegistration) - assert response.name == 'name_value' - assert response.gcp_ids == ['gcp_ids_value'] + assert response.name == "name_value" + assert response.gcp_ids == ["gcp_ids_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_developer_registration_rest_interceptors(null_interceptor): transport = transports.DeveloperRegistrationServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeveloperRegistrationServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DeveloperRegistrationServiceRestInterceptor(), + ) client = DeveloperRegistrationServiceClient(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.DeveloperRegistrationServiceRestInterceptor, "post_get_developer_registration") as post, \ - mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "post_get_developer_registration_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.DeveloperRegistrationServiceRestInterceptor, "pre_get_developer_registration") 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.DeveloperRegistrationServiceRestInterceptor, + "post_get_developer_registration", + ) as post, mock.patch.object( + transports.DeveloperRegistrationServiceRestInterceptor, + "post_get_developer_registration_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.DeveloperRegistrationServiceRestInterceptor, + "pre_get_developer_registration", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developerregistration.GetDeveloperRegistrationRequest.pb(developerregistration.GetDeveloperRegistrationRequest()) + pb_message = developerregistration.GetDeveloperRegistrationRequest.pb( + developerregistration.GetDeveloperRegistrationRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2391,39 +2957,53 @@ def test_get_developer_registration_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 = developerregistration.DeveloperRegistration.to_json(developerregistration.DeveloperRegistration()) + return_value = developerregistration.DeveloperRegistration.to_json( + developerregistration.DeveloperRegistration() + ) req.return_value.content = return_value request = developerregistration.GetDeveloperRegistrationRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = developerregistration.DeveloperRegistration() - post_with_metadata.return_value = developerregistration.DeveloperRegistration(), metadata + post_with_metadata.return_value = ( + developerregistration.DeveloperRegistration(), + metadata, + ) - client.get_developer_registration(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_developer_registration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_unregister_gcp_rest_bad_request(request_type=developerregistration.UnregisterGcpRequest): +def test_unregister_gcp_rest_bad_request( + request_type=developerregistration.UnregisterGcpRequest, +): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/developerRegistration'} + request_init = {"name": "accounts/sample1/developerRegistration"} 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() @@ -2432,30 +3012,32 @@ def test_unregister_gcp_rest_bad_request(request_type=developerregistration.Unre client.unregister_gcp(request) -@pytest.mark.parametrize("request_type", [ - developerregistration.UnregisterGcpRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + developerregistration.UnregisterGcpRequest, + dict, + ], +) def test_unregister_gcp_rest_call_success(request_type): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/developerRegistration'} + request_init = {"name": "accounts/sample1/developerRegistration"} request = request_type(**request_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.unregister_gcp(request) @@ -2468,15 +3050,23 @@ def test_unregister_gcp_rest_call_success(request_type): def test_unregister_gcp_rest_interceptors(null_interceptor): transport = transports.DeveloperRegistrationServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DeveloperRegistrationServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DeveloperRegistrationServiceRestInterceptor(), + ) client = DeveloperRegistrationServiceClient(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.DeveloperRegistrationServiceRestInterceptor, "pre_unregister_gcp") 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.DeveloperRegistrationServiceRestInterceptor, "pre_unregister_gcp" + ) as pre: pre.assert_not_called() - pb_message = developerregistration.UnregisterGcpRequest.pb(developerregistration.UnregisterGcpRequest()) + pb_message = developerregistration.UnregisterGcpRequest.pb( + developerregistration.UnregisterGcpRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2489,20 +3079,26 @@ def test_unregister_gcp_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = developerregistration.UnregisterGcpRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.unregister_gcp(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.unregister_gcp( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() + def test_initialize_client_w_rest(): client = DeveloperRegistrationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2516,9 +3112,7 @@ def test_register_gcp_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.register_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.register_gcp), "__call__") as call: client.register_gcp(request=None) # Establish that the underlying stub method was called. @@ -2539,8 +3133,8 @@ def test_get_developer_registration_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_developer_registration), - '__call__') as call: + type(client.transport.get_developer_registration), "__call__" + ) as call: client.get_developer_registration(request=None) # Establish that the underlying stub method was called. @@ -2560,9 +3154,7 @@ def test_unregister_gcp_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unregister_gcp), - '__call__') as call: + with mock.patch.object(type(client.transport.unregister_gcp), "__call__") as call: client.unregister_gcp(request=None) # Establish that the underlying stub method was called. @@ -2583,18 +3175,21 @@ def test_transport_grpc_default(): transports.DeveloperRegistrationServiceGrpcTransport, ) + def test_developer_registration_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DeveloperRegistrationServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_developer_registration_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.DeveloperRegistrationServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2603,9 +3198,9 @@ def test_developer_registration_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'register_gcp', - 'get_developer_registration', - 'unregister_gcp', + "register_gcp", + "get_developer_registration", + "unregister_gcp", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2616,7 +3211,7 @@ def test_developer_registration_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2625,25 +3220,30 @@ def test_developer_registration_service_base_transport(): def test_developer_registration_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_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport._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_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DeveloperRegistrationServiceTransport( 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_developer_registration_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_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.developer_registration_service.transports.DeveloperRegistrationServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DeveloperRegistrationServiceTransport() @@ -2652,14 +3252,12 @@ def test_developer_registration_service_base_transport_with_adc(): def test_developer_registration_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) DeveloperRegistrationServiceClient() 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, ) @@ -2674,12 +3272,12 @@ def test_developer_registration_service_auth_adc(): def test_developer_registration_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", ) @@ -2692,49 +3290,53 @@ def test_developer_registration_service_transport_auth_adc(transport_class): transports.DeveloperRegistrationServiceRestTransport, ], ) -def test_developer_registration_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'] +def test_developer_registration_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: + 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.DeveloperRegistrationServiceGrpcTransport, grpc_helpers), - (transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, grpc_helpers_async) + ( + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), ], ) -def test_developer_registration_service_transport_create_channel(transport_class, grpc_helpers): +def test_developer_registration_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, @@ -2745,9 +3347,15 @@ def test_developer_registration_service_transport_create_channel(transport_class ) -@pytest.mark.parametrize("transport_class", [transports.DeveloperRegistrationServiceGrpcTransport, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + ], +) def test_developer_registration_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2757,7 +3365,7 @@ def test_developer_registration_service_grpc_transport_client_cert_source_for_mt 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", @@ -2778,62 +3386,80 @@ def test_developer_registration_service_grpc_transport_client_cert_source_for_mt 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_developer_registration_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.DeveloperRegistrationServiceRestTransport ( - 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.DeveloperRegistrationServiceRestTransport( + 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_developer_registration_service_host_no_port(transport_name): client = DeveloperRegistrationServiceClient( 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_developer_registration_service_host_with_port(transport_name): client = DeveloperRegistrationServiceClient( 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", -]) -def test_developer_registration_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_developer_registration_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = DeveloperRegistrationServiceClient( @@ -2853,8 +3479,10 @@ def test_developer_registration_service_client_transport_session_collision(trans session1 = client1.transport.unregister_gcp._session session2 = client2.transport.unregister_gcp._session assert session1 != session2 + + def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport( @@ -2867,7 +3495,7 @@ def test_developer_registration_service_grpc_transport_channel(): def test_developer_registration_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.DeveloperRegistrationServiceGrpcAsyncIOTransport( @@ -2881,12 +3509,22 @@ def test_developer_registration_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.DeveloperRegistrationServiceGrpcTransport, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + ], +) def test_developer_registration_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 @@ -2895,7 +3533,7 @@ def test_developer_registration_service_transport_channel_mtls_with_client_cert_ 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", @@ -2925,9 +3563,15 @@ def test_developer_registration_service_transport_channel_mtls_with_client_cert_ # 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.DeveloperRegistrationServiceGrpcTransport, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeveloperRegistrationServiceGrpcTransport, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + ], +) def test_developer_registration_service_transport_channel_mtls_with_adc( - transport_class + transport_class, ): mock_ssl_cred = mock.Mock() with mock.patch.multiple( @@ -2935,7 +3579,9 @@ def test_developer_registration_service_transport_channel_mtls_with_adc( __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() @@ -2965,7 +3611,9 @@ def test_developer_registration_service_transport_channel_mtls_with_adc( def test_developer_registration_path(): account = "squid" - expected = "accounts/{account}/developerRegistration".format(account=account, ) + expected = "accounts/{account}/developerRegistration".format( + account=account, + ) actual = DeveloperRegistrationServiceClient.developer_registration_path(account) assert expected == actual @@ -2980,10 +3628,15 @@ def test_parse_developer_registration_path(): actual = DeveloperRegistrationServiceClient.parse_developer_registration_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DeveloperRegistrationServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = DeveloperRegistrationServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -2997,9 +3650,12 @@ def test_parse_common_billing_account_path(): actual = DeveloperRegistrationServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = DeveloperRegistrationServiceClient.common_folder_path(folder) assert expected == actual @@ -3014,9 +3670,12 @@ def test_parse_common_folder_path(): actual = DeveloperRegistrationServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = DeveloperRegistrationServiceClient.common_organization_path(organization) assert expected == actual @@ -3031,9 +3690,12 @@ def test_parse_common_organization_path(): actual = DeveloperRegistrationServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = DeveloperRegistrationServiceClient.common_project_path(project) assert expected == actual @@ -3048,10 +3710,14 @@ def test_parse_common_project_path(): actual = DeveloperRegistrationServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = DeveloperRegistrationServiceClient.common_location_path(project, location) assert expected == actual @@ -3071,14 +3737,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.DeveloperRegistrationServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.DeveloperRegistrationServiceTransport, "_prep_wrapped_messages" + ) as prep: client = DeveloperRegistrationServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.DeveloperRegistrationServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.DeveloperRegistrationServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = DeveloperRegistrationServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3089,10 +3759,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = DeveloperRegistrationServiceClient( - 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() @@ -3101,10 +3772,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = DeveloperRegistrationServiceAsyncClient( - 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() @@ -3112,10 +3784,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = DeveloperRegistrationServiceClient( - 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() @@ -3123,13 +3796,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = DeveloperRegistrationServiceClient( - 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: @@ -3138,10 +3810,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (DeveloperRegistrationServiceClient, transports.DeveloperRegistrationServiceGrpcTransport), - (DeveloperRegistrationServiceAsyncClient, transports.DeveloperRegistrationServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + DeveloperRegistrationServiceClient, + transports.DeveloperRegistrationServiceGrpcTransport, + ), + ( + DeveloperRegistrationServiceAsyncClient, + transports.DeveloperRegistrationServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3156,7 +3838,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py index 94095b92c5dc..879df14cc9a9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_email_preferences_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,45 +22,43 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.email_preferences_service import EmailPreferencesServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.email_preferences_service import EmailPreferencesServiceClient -from google.shopping.merchant_accounts_v1.services.email_preferences_service import transports -from google.shopping.merchant_accounts_v1.types import emailpreferences -import google.auth - +from google.shopping.merchant_accounts_v1.services.email_preferences_service import ( + EmailPreferencesServiceAsyncClient, + EmailPreferencesServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import emailpreferences CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert EmailPreferencesServiceClient._get_default_mtls_endpoint(None) is None - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EmailPreferencesServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + EmailPreferencesServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + EmailPreferencesServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EmailPreferencesServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EmailPreferencesServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + assert EmailPreferencesServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (True, "auto", None) + assert EmailPreferencesServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + assert EmailPreferencesServiceClient._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: EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._read_environment_variables() == (False, "never", None) + assert EmailPreferencesServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "always", None) + assert EmailPreferencesServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", None) + assert EmailPreferencesServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, False) is None - assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + EmailPreferencesServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + EmailPreferencesServiceClient._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 ( + EmailPreferencesServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EmailPreferencesServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) +@mock.patch.object( + EmailPreferencesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceClient), +) +@mock.patch.object( + EmailPreferencesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert EmailPreferencesServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - assert EmailPreferencesServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EmailPreferencesServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == EmailPreferencesServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + EmailPreferencesServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - EmailPreferencesServiceClient._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." + EmailPreferencesServiceClient._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 EmailPreferencesServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EmailPreferencesServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EmailPreferencesServiceClient._get_universe_domain(None, None) == EmailPreferencesServiceClient._DEFAULT_UNIVERSE + assert ( + EmailPreferencesServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + EmailPreferencesServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + EmailPreferencesServiceClient._get_universe_domain(None, None) + == EmailPreferencesServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: EmailPreferencesServiceClient._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) @@ -215,7 +370,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") @@ -228,14 +384,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", [ - (EmailPreferencesServiceClient, "grpc"), - (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), - (EmailPreferencesServiceClient, "rest"), -]) -def test_email_preferences_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EmailPreferencesServiceClient, "grpc"), + (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), + (EmailPreferencesServiceClient, "rest"), + ], +) +def test_email_preferences_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) @@ -243,52 +407,70 @@ def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, "grpc"), - (transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EmailPreferencesServiceRestTransport, "rest"), -]) -def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, "grpc"), + (transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EmailPreferencesServiceRestTransport, "rest"), + ], +) +def test_email_preferences_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", [ - (EmailPreferencesServiceClient, "grpc"), - (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), - (EmailPreferencesServiceClient, "rest"), -]) -def test_email_preferences_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EmailPreferencesServiceClient, "grpc"), + (EmailPreferencesServiceAsyncClient, "grpc_asyncio"), + (EmailPreferencesServiceClient, "rest"), + ], +) +def test_email_preferences_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" ) @@ -304,30 +486,53 @@ def test_email_preferences_service_client_get_transport_class(): assert transport == transports.EmailPreferencesServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), -]) -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) -def test_email_preferences_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + "grpc", + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + EmailPreferencesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceClient), +) +@mock.patch.object( + EmailPreferencesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceAsyncClient), +) +def test_email_preferences_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(EmailPreferencesServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(EmailPreferencesServiceClient, "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(EmailPreferencesServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(EmailPreferencesServiceClient, "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( @@ -345,13 +550,15 @@ def test_email_preferences_service_client_client_options(client_class, transport # 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, @@ -363,7 +570,7 @@ def test_email_preferences_service_client_client_options(client_class, transport # 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( @@ -383,23 +590,33 @@ def test_email_preferences_service_client_client_options(client_class, transport 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", @@ -408,48 +625,102 @@ def test_email_preferences_service_client_client_options(client_class, transport 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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "true"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", "false"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "true"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + "grpc", + "true", + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + "grpc", + "false", + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceRestTransport, + "rest", + "true", + ), + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + EmailPreferencesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceClient), +) +@mock.patch.object( + EmailPreferencesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_email_preferences_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_email_preferences_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 @@ -468,12 +739,22 @@ def test_email_preferences_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 @@ -494,15 +775,22 @@ def test_email_preferences_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, @@ -512,19 +800,33 @@ def test_email_preferences_service_client_mtls_env_auto(client_class, transport_ ) -@pytest.mark.parametrize("client_class", [ - EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient -]) -@mock.patch.object(EmailPreferencesServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EmailPreferencesServiceAsyncClient)) -def test_email_preferences_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient] +) +@mock.patch.object( + EmailPreferencesServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EmailPreferencesServiceClient), +) +@mock.patch.object( + EmailPreferencesServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EmailPreferencesServiceAsyncClient), +) +def test_email_preferences_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 @@ -532,8 +834,12 @@ def test_email_preferences_service_client_get_mtls_endpoint_and_cert_source(clie 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 @@ -551,16 +857,28 @@ def test_email_preferences_service_client_get_mtls_endpoint_and_cert_source(clie # 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 @@ -570,34 +888,62 @@ def test_email_preferences_service_client_get_mtls_endpoint_and_cert_source(clie 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", [ - EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient -]) -@mock.patch.object(EmailPreferencesServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceClient)) -@mock.patch.object(EmailPreferencesServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EmailPreferencesServiceAsyncClient)) + +@pytest.mark.parametrize( + "client_class", [EmailPreferencesServiceClient, EmailPreferencesServiceAsyncClient] +) +@mock.patch.object( + EmailPreferencesServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceClient), +) +@mock.patch.object( + EmailPreferencesServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EmailPreferencesServiceAsyncClient), +) def test_email_preferences_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = EmailPreferencesServiceClient._DEFAULT_UNIVERSE - default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = EmailPreferencesServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = EmailPreferencesServiceClient._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", @@ -620,11 +966,19 @@ def test_email_preferences_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. @@ -632,27 +986,48 @@ def test_email_preferences_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", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc"), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest"), -]) -def test_email_preferences_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + "grpc", + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceRestTransport, + "rest", + ), + ], +) +def test_email_preferences_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, @@ -661,24 +1036,45 @@ def test_email_preferences_service_client_client_options_scopes(client_class, tr api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceRestTransport, "rest", None), -]) -def test_email_preferences_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", + [ + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceRestTransport, + "rest", + None, + ), + ], +) +def test_email_preferences_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, @@ -687,11 +1083,14 @@ def test_email_preferences_service_client_client_options_credentials_file(client api_audience=None, ) + def test_email_preferences_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = EmailPreferencesServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1105,38 @@ def test_email_preferences_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport, "grpc", grpc_helpers), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_email_preferences_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", + [ + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_email_preferences_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, @@ -749,9 +1163,7 @@ def test_email_preferences_service_client_create_channel_credentials_file(client 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, @@ -762,11 +1174,14 @@ def test_email_preferences_service_client_create_channel_credentials_file(client ) -@pytest.mark.parametrize("request_type", [ - emailpreferences.GetEmailPreferencesRequest, - dict, -]) -def test_get_email_preferences(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + emailpreferences.GetEmailPreferencesRequest, + dict, + ], +) +def test_get_email_preferences(request_type, transport: str = "grpc"): client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,11 +1193,11 @@ def test_get_email_preferences(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = emailpreferences.EmailPreferences( - name='name_value', + name="name_value", news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, ) response = client.get_email_preferences(request) @@ -795,8 +1210,10 @@ def test_get_email_preferences(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + assert response.name == "name_value" + assert ( + response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + ) def test_get_email_preferences_non_empty_request_with_auto_populated_field(): @@ -804,28 +1221,31 @@ def test_get_email_preferences_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = EmailPreferencesServiceClient( 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 = emailpreferences.GetEmailPreferencesRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_email_preferences), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_email_preferences(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == emailpreferences.GetEmailPreferencesRequest( - name='name_value', + name="name_value", ) + def test_get_email_preferences_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -840,12 +1260,19 @@ def test_get_email_preferences_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_email_preferences in client._transport._wrapped_methods + assert ( + client._transport.get_email_preferences + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_email_preferences + ] = mock_rpc request = {} client.get_email_preferences(request) @@ -858,8 +1285,11 @@ def test_get_email_preferences_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_email_preferences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_email_preferences_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: @@ -873,12 +1303,17 @@ async def test_get_email_preferences_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_email_preferences in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_email_preferences + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_email_preferences] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_email_preferences + ] = mock_rpc request = {} await client.get_email_preferences(request) @@ -892,8 +1327,12 @@ async def test_get_email_preferences_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.GetEmailPreferencesRequest): +async def test_get_email_preferences_async( + transport: str = "grpc_asyncio", + request_type=emailpreferences.GetEmailPreferencesRequest, +): client = EmailPreferencesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -905,13 +1344,15 @@ async def test_get_email_preferences_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences( + name="name_value", + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + ) response = await client.get_email_preferences(request) # Establish that the underlying gRPC stub method was called. @@ -922,14 +1363,17 @@ async def test_get_email_preferences_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + assert response.name == "name_value" + assert ( + response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + ) @pytest.mark.asyncio async def test_get_email_preferences_async_from_dict(): await test_get_email_preferences_async(request_type=dict) + def test_get_email_preferences_field_headers(): client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -939,12 +1383,12 @@ def test_get_email_preferences_field_headers(): # a field header. Set these to a non-empty value. request = emailpreferences.GetEmailPreferencesRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: call.return_value = emailpreferences.EmailPreferences() client.get_email_preferences(request) @@ -956,9 +1400,9 @@ def test_get_email_preferences_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 @@ -971,13 +1415,15 @@ async def test_get_email_preferences_field_headers_async(): # a field header. Set these to a non-empty value. request = emailpreferences.GetEmailPreferencesRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + type(client.transport.get_email_preferences), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences() + ) await client.get_email_preferences(request) # Establish that the underlying gRPC stub method was called. @@ -988,9 +1434,9 @@ async def test_get_email_preferences_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_email_preferences_flattened(): @@ -1000,14 +1446,14 @@ def test_get_email_preferences_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = emailpreferences.EmailPreferences() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_email_preferences( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1015,7 +1461,7 @@ def test_get_email_preferences_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 @@ -1029,9 +1475,10 @@ def test_get_email_preferences_flattened_error(): with pytest.raises(ValueError): client.get_email_preferences( emailpreferences.GetEmailPreferencesRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_email_preferences_flattened_async(): client = EmailPreferencesServiceAsyncClient( @@ -1040,16 +1487,18 @@ async def test_get_email_preferences_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = emailpreferences.EmailPreferences() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_email_preferences( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1057,9 +1506,10 @@ async def test_get_email_preferences_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_email_preferences_flattened_error_async(): client = EmailPreferencesServiceAsyncClient( @@ -1071,15 +1521,18 @@ async def test_get_email_preferences_flattened_error_async(): with pytest.raises(ValueError): await client.get_email_preferences( emailpreferences.GetEmailPreferencesRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - emailpreferences.UpdateEmailPreferencesRequest, - dict, -]) -def test_update_email_preferences(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + emailpreferences.UpdateEmailPreferencesRequest, + dict, + ], +) +def test_update_email_preferences(request_type, transport: str = "grpc"): client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1091,11 +1544,11 @@ def test_update_email_preferences(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = emailpreferences.EmailPreferences( - name='name_value', + name="name_value", news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, ) response = client.update_email_preferences(request) @@ -1108,8 +1561,10 @@ def test_update_email_preferences(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + assert response.name == "name_value" + assert ( + response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + ) def test_update_email_preferences_non_empty_request_with_auto_populated_field(): @@ -1117,25 +1572,26 @@ def test_update_email_preferences_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = EmailPreferencesServiceClient( 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 = emailpreferences.UpdateEmailPreferencesRequest( - ) + request = emailpreferences.UpdateEmailPreferencesRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_email_preferences), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_email_preferences(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == emailpreferences.UpdateEmailPreferencesRequest( - ) + assert args[0] == emailpreferences.UpdateEmailPreferencesRequest() + def test_update_email_preferences_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1151,12 +1607,19 @@ def test_update_email_preferences_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_email_preferences in client._transport._wrapped_methods + assert ( + client._transport.update_email_preferences + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_email_preferences + ] = mock_rpc request = {} client.update_email_preferences(request) @@ -1169,8 +1632,11 @@ def test_update_email_preferences_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_email_preferences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_email_preferences_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: @@ -1184,12 +1650,17 @@ async def test_update_email_preferences_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_email_preferences in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_email_preferences + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_email_preferences] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_email_preferences + ] = mock_rpc request = {} await client.update_email_preferences(request) @@ -1203,8 +1674,12 @@ async def test_update_email_preferences_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_email_preferences_async(transport: str = 'grpc_asyncio', request_type=emailpreferences.UpdateEmailPreferencesRequest): +async def test_update_email_preferences_async( + transport: str = "grpc_asyncio", + request_type=emailpreferences.UpdateEmailPreferencesRequest, +): client = EmailPreferencesServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1216,13 +1691,15 @@ async def test_update_email_preferences_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences( + name="name_value", + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + ) response = await client.update_email_preferences(request) # Establish that the underlying gRPC stub method was called. @@ -1233,14 +1710,17 @@ async def test_update_email_preferences_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + assert response.name == "name_value" + assert ( + response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + ) @pytest.mark.asyncio async def test_update_email_preferences_async_from_dict(): await test_update_email_preferences_async(request_type=dict) + def test_update_email_preferences_field_headers(): client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1250,12 +1730,12 @@ def test_update_email_preferences_field_headers(): # a field header. Set these to a non-empty value. request = emailpreferences.UpdateEmailPreferencesRequest() - request.email_preferences.name = 'name_value' + request.email_preferences.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: call.return_value = emailpreferences.EmailPreferences() client.update_email_preferences(request) @@ -1267,9 +1747,9 @@ def test_update_email_preferences_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'email_preferences.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "email_preferences.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1282,13 +1762,15 @@ async def test_update_email_preferences_field_headers_async(): # a field header. Set these to a non-empty value. request = emailpreferences.UpdateEmailPreferencesRequest() - request.email_preferences.name = 'name_value' + request.email_preferences.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + type(client.transport.update_email_preferences), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences() + ) await client.update_email_preferences(request) # Establish that the underlying gRPC stub method was called. @@ -1299,9 +1781,9 @@ async def test_update_email_preferences_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'email_preferences.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "email_preferences.name=name_value", + ) in kw["metadata"] def test_update_email_preferences_flattened(): @@ -1311,15 +1793,15 @@ def test_update_email_preferences_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = emailpreferences.EmailPreferences() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_email_preferences( - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + email_preferences=emailpreferences.EmailPreferences(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1327,10 +1809,10 @@ def test_update_email_preferences_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].email_preferences - mock_val = emailpreferences.EmailPreferences(name='name_value') + mock_val = emailpreferences.EmailPreferences(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1344,10 +1826,11 @@ def test_update_email_preferences_flattened_error(): with pytest.raises(ValueError): client.update_email_preferences( emailpreferences.UpdateEmailPreferencesRequest(), - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + email_preferences=emailpreferences.EmailPreferences(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_email_preferences_flattened_async(): client = EmailPreferencesServiceAsyncClient( @@ -1356,17 +1839,19 @@ async def test_update_email_preferences_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = emailpreferences.EmailPreferences() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_email_preferences( - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + email_preferences=emailpreferences.EmailPreferences(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1374,12 +1859,13 @@ async def test_update_email_preferences_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].email_preferences - mock_val = emailpreferences.EmailPreferences(name='name_value') + mock_val = emailpreferences.EmailPreferences(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_email_preferences_flattened_error_async(): client = EmailPreferencesServiceAsyncClient( @@ -1391,8 +1877,8 @@ async def test_update_email_preferences_flattened_error_async(): with pytest.raises(ValueError): await client.update_email_preferences( emailpreferences.UpdateEmailPreferencesRequest(), - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + email_preferences=emailpreferences.EmailPreferences(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1410,12 +1896,19 @@ def test_get_email_preferences_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_email_preferences in client._transport._wrapped_methods + assert ( + client._transport.get_email_preferences + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_email_preferences] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_email_preferences + ] = mock_rpc request = {} client.get_email_preferences(request) @@ -1430,55 +1923,60 @@ def test_get_email_preferences_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_email_preferences_rest_required_fields(request_type=emailpreferences.GetEmailPreferencesRequest): +def test_get_email_preferences_rest_required_fields( + request_type=emailpreferences.GetEmailPreferencesRequest, +): transport_class = transports.EmailPreferencesServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_email_preferences._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_email_preferences._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_email_preferences._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_email_preferences._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 = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = emailpreferences.EmailPreferences() # Mock the http request 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 @@ -1489,24 +1987,24 @@ def test_get_email_preferences_rest_required_fields(request_type=emailpreference return_value = emailpreferences.EmailPreferences.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_email_preferences(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_email_preferences_rest_unset_required_fields(): - transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EmailPreferencesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_email_preferences._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_email_preferences_rest_flattened(): @@ -1516,16 +2014,16 @@ def test_get_email_preferences_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 = emailpreferences.EmailPreferences() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + sample_request = {"name": "accounts/sample1/users/sample2/emailPreferences"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1535,7 +2033,7 @@ def test_get_email_preferences_rest_flattened(): # Convert return value to protobuf type return_value = emailpreferences.EmailPreferences.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1545,10 +2043,14 @@ def test_get_email_preferences_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/users/*/emailPreferences}" + % client.transport._host, + args[1], + ) -def test_get_email_preferences_rest_flattened_error(transport: str = 'rest'): +def test_get_email_preferences_rest_flattened_error(transport: str = "rest"): client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1559,7 +2061,7 @@ def test_get_email_preferences_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_email_preferences( emailpreferences.GetEmailPreferencesRequest(), - name='name_value', + name="name_value", ) @@ -1577,12 +2079,19 @@ def test_update_email_preferences_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_email_preferences in client._transport._wrapped_methods + assert ( + client._transport.update_email_preferences + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_email_preferences] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_email_preferences + ] = mock_rpc request = {} client.update_email_preferences(request) @@ -1597,54 +2106,59 @@ def test_update_email_preferences_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_email_preferences_rest_required_fields(request_type=emailpreferences.UpdateEmailPreferencesRequest): +def test_update_email_preferences_rest_required_fields( + request_type=emailpreferences.UpdateEmailPreferencesRequest, +): transport_class = transports.EmailPreferencesServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_email_preferences._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_email_preferences._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_email_preferences._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = emailpreferences.EmailPreferences() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -1654,24 +2168,32 @@ def test_update_email_preferences_rest_required_fields(request_type=emailprefere return_value = emailpreferences.EmailPreferences.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_email_preferences(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_email_preferences_rest_unset_required_fields(): - transport = transports.EmailPreferencesServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EmailPreferencesServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_email_preferences._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("emailPreferences", "updateMask", ))) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "emailPreferences", + "updateMask", + ) + ) + ) def test_update_email_preferences_rest_flattened(): @@ -1681,17 +2203,21 @@ def test_update_email_preferences_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 = emailpreferences.EmailPreferences() # get arguments that satisfy an http rule for this method - sample_request = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + sample_request = { + "email_preferences": { + "name": "accounts/sample1/users/sample2/emailPreferences" + } + } # get truthy value for each flattened field mock_args = dict( - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + email_preferences=emailpreferences.EmailPreferences(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -1701,7 +2227,7 @@ def test_update_email_preferences_rest_flattened(): # Convert return value to protobuf type return_value = emailpreferences.EmailPreferences.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1711,10 +2237,14 @@ def test_update_email_preferences_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{email_preferences.name=accounts/*/users/*/emailPreferences}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{email_preferences.name=accounts/*/users/*/emailPreferences}" + % client.transport._host, + args[1], + ) -def test_update_email_preferences_rest_flattened_error(transport: str = 'rest'): +def test_update_email_preferences_rest_flattened_error(transport: str = "rest"): client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1725,8 +2255,8 @@ def test_update_email_preferences_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_email_preferences( emailpreferences.UpdateEmailPreferencesRequest(), - email_preferences=emailpreferences.EmailPreferences(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + email_preferences=emailpreferences.EmailPreferences(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1768,8 +2298,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = EmailPreferencesServiceClient( - 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. @@ -1791,6 +2320,7 @@ def test_transport_instance(): client = EmailPreferencesServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EmailPreferencesServiceGrpcTransport( @@ -1805,18 +2335,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.EmailPreferencesServiceGrpcTransport, - transports.EmailPreferencesServiceGrpcAsyncIOTransport, - transports.EmailPreferencesServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + transports.EmailPreferencesServiceRestTransport, + ], +) 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 = EmailPreferencesServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1826,8 +2361,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1842,8 +2376,8 @@ def test_get_email_preferences_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: call.return_value = emailpreferences.EmailPreferences() client.get_email_preferences(request=None) @@ -1865,8 +2399,8 @@ def test_update_email_preferences_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: call.return_value = emailpreferences.EmailPreferences() client.update_email_preferences(request=None) @@ -1887,8 +2421,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = EmailPreferencesServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1904,13 +2437,15 @@ async def test_get_email_preferences_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences( + name="name_value", + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + ) await client.get_email_preferences(request=None) # Establish that the underlying stub method was called. @@ -1932,13 +2467,15 @@ async def test_update_email_preferences_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + emailpreferences.EmailPreferences( + name="name_value", + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + ) + ) await client.update_email_preferences(request=None) # Establish that the underlying stub method was called. @@ -1956,20 +2493,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_email_preferences_rest_bad_request(request_type=emailpreferences.GetEmailPreferencesRequest): +def test_get_email_preferences_rest_bad_request( + request_type=emailpreferences.GetEmailPreferencesRequest, +): client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + request_init = {"name": "accounts/sample1/users/sample2/emailPreferences"} 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() @@ -1978,26 +2518,28 @@ def test_get_email_preferences_rest_bad_request(request_type=emailpreferences.Ge client.get_email_preferences(request) -@pytest.mark.parametrize("request_type", [ - emailpreferences.GetEmailPreferencesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + emailpreferences.GetEmailPreferencesRequest, + dict, + ], +) def test_get_email_preferences_rest_call_success(request_type): client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2/emailPreferences'} + request_init = {"name": "accounts/sample1/users/sample2/emailPreferences"} request = request_type(**request_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 = emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + name="name_value", + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, ) # Wrap the value into a proper Response obj @@ -2007,34 +2549,47 @@ def test_get_email_preferences_rest_call_success(request_type): # Convert return value to protobuf type return_value = emailpreferences.EmailPreferences.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_email_preferences(request) # Establish that the response is the type that we expect. assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + assert response.name == "name_value" + assert ( + response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_email_preferences_rest_interceptors(null_interceptor): transport = transports.EmailPreferencesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EmailPreferencesServiceRestInterceptor(), + ) client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences") as post, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_get_email_preferences") 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.EmailPreferencesServiceRestInterceptor, "post_get_email_preferences" + ) as post, mock.patch.object( + transports.EmailPreferencesServiceRestInterceptor, + "post_get_email_preferences_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EmailPreferencesServiceRestInterceptor, "pre_get_email_preferences" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = emailpreferences.GetEmailPreferencesRequest.pb(emailpreferences.GetEmailPreferencesRequest()) + pb_message = emailpreferences.GetEmailPreferencesRequest.pb( + emailpreferences.GetEmailPreferencesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2045,11 +2600,13 @@ def test_get_email_preferences_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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) + return_value = emailpreferences.EmailPreferences.to_json( + emailpreferences.EmailPreferences() + ) req.return_value.content = return_value request = emailpreferences.GetEmailPreferencesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2057,27 +2614,38 @@ def test_get_email_preferences_rest_interceptors(null_interceptor): post.return_value = emailpreferences.EmailPreferences() post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata - client.get_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_email_preferences( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_email_preferences_rest_bad_request(request_type=emailpreferences.UpdateEmailPreferencesRequest): +def test_update_email_preferences_rest_bad_request( + request_type=emailpreferences.UpdateEmailPreferencesRequest, +): client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} + request_init = { + "email_preferences": {"name": "accounts/sample1/users/sample2/emailPreferences"} + } 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() @@ -2086,25 +2654,34 @@ def test_update_email_preferences_rest_bad_request(request_type=emailpreferences client.update_email_preferences(request) -@pytest.mark.parametrize("request_type", [ - emailpreferences.UpdateEmailPreferencesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + emailpreferences.UpdateEmailPreferencesRequest, + dict, + ], +) def test_update_email_preferences_rest_call_success(request_type): client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'email_preferences': {'name': 'accounts/sample1/users/sample2/emailPreferences'}} - request_init["email_preferences"] = {'name': 'accounts/sample1/users/sample2/emailPreferences', 'news_and_tips': 1} + request_init = { + "email_preferences": {"name": "accounts/sample1/users/sample2/emailPreferences"} + } + request_init["email_preferences"] = { + "name": "accounts/sample1/users/sample2/emailPreferences", + "news_and_tips": 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 = emailpreferences.UpdateEmailPreferencesRequest.meta.fields["email_preferences"] + test_field = emailpreferences.UpdateEmailPreferencesRequest.meta.fields[ + "email_preferences" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -2118,7 +2695,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 @@ -2132,7 +2709,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["email_preferences"].items(): # pragma: NO COVER + for field, value in request_init["email_preferences"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2147,12 +2724,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") @@ -2165,11 +2746,11 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = emailpreferences.EmailPreferences( - name='name_value', - news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, + name="name_value", + news_and_tips=emailpreferences.EmailPreferences.OptInState.OPTED_OUT, ) # Wrap the value into a proper Response obj @@ -2179,34 +2760,49 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = emailpreferences.EmailPreferences.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_email_preferences(request) # Establish that the response is the type that we expect. assert isinstance(response, emailpreferences.EmailPreferences) - assert response.name == 'name_value' - assert response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + assert response.name == "name_value" + assert ( + response.news_and_tips == emailpreferences.EmailPreferences.OptInState.OPTED_OUT + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_email_preferences_rest_interceptors(null_interceptor): transport = transports.EmailPreferencesServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EmailPreferencesServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EmailPreferencesServiceRestInterceptor(), + ) client = EmailPreferencesServiceClient(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.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences") as post, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "post_update_email_preferences_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.EmailPreferencesServiceRestInterceptor, "pre_update_email_preferences") 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.EmailPreferencesServiceRestInterceptor, + "post_update_email_preferences", + ) as post, mock.patch.object( + transports.EmailPreferencesServiceRestInterceptor, + "post_update_email_preferences_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EmailPreferencesServiceRestInterceptor, + "pre_update_email_preferences", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = emailpreferences.UpdateEmailPreferencesRequest.pb(emailpreferences.UpdateEmailPreferencesRequest()) + pb_message = emailpreferences.UpdateEmailPreferencesRequest.pb( + emailpreferences.UpdateEmailPreferencesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2217,11 +2813,13 @@ def test_update_email_preferences_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 = emailpreferences.EmailPreferences.to_json(emailpreferences.EmailPreferences()) + return_value = emailpreferences.EmailPreferences.to_json( + emailpreferences.EmailPreferences() + ) req.return_value.content = return_value request = emailpreferences.UpdateEmailPreferencesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2229,16 +2827,22 @@ def test_update_email_preferences_rest_interceptors(null_interceptor): post.return_value = emailpreferences.EmailPreferences() post_with_metadata.return_value = emailpreferences.EmailPreferences(), metadata - client.update_email_preferences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_email_preferences( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = EmailPreferencesServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2253,8 +2857,8 @@ def test_get_email_preferences_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_email_preferences), - '__call__') as call: + type(client.transport.get_email_preferences), "__call__" + ) as call: client.get_email_preferences(request=None) # Establish that the underlying stub method was called. @@ -2275,8 +2879,8 @@ def test_update_email_preferences_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_email_preferences), - '__call__') as call: + type(client.transport.update_email_preferences), "__call__" + ) as call: client.update_email_preferences(request=None) # Establish that the underlying stub method was called. @@ -2297,18 +2901,21 @@ def test_transport_grpc_default(): transports.EmailPreferencesServiceGrpcTransport, ) + def test_email_preferences_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EmailPreferencesServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_email_preferences_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.EmailPreferencesServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2317,8 +2924,8 @@ def test_email_preferences_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_email_preferences', - 'update_email_preferences', + "get_email_preferences", + "update_email_preferences", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2329,7 +2936,7 @@ def test_email_preferences_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2338,25 +2945,30 @@ def test_email_preferences_service_base_transport(): def test_email_preferences_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_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport._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_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EmailPreferencesServiceTransport( 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_email_preferences_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_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.email_preferences_service.transports.EmailPreferencesServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EmailPreferencesServiceTransport() @@ -2365,14 +2977,12 @@ def test_email_preferences_service_base_transport_with_adc(): def test_email_preferences_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) EmailPreferencesServiceClient() 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, ) @@ -2387,12 +2997,12 @@ def test_email_preferences_service_auth_adc(): def test_email_preferences_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", ) @@ -2406,48 +3016,47 @@ def test_email_preferences_service_transport_auth_adc(transport_class): ], ) def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, grpc_helpers), - (transports.EmailPreferencesServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.EmailPreferencesServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_email_preferences_service_transport_create_channel(transport_class, grpc_helpers): +def test_email_preferences_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, @@ -2458,9 +3067,15 @@ def test_email_preferences_service_transport_create_channel(transport_class, grp ) -@pytest.mark.parametrize("transport_class", [transports.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + ], +) def test_email_preferences_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2470,7 +3085,7 @@ def test_email_preferences_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", @@ -2491,61 +3106,77 @@ def test_email_preferences_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_email_preferences_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.EmailPreferencesServiceRestTransport ( - 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.EmailPreferencesServiceRestTransport( + 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_email_preferences_service_host_no_port(transport_name): client = EmailPreferencesServiceClient( 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_email_preferences_service_host_with_port(transport_name): client = EmailPreferencesServiceClient( 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_email_preferences_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2563,8 +3194,10 @@ def test_email_preferences_service_client_transport_session_collision(transport_ session1 = client1.transport.update_email_preferences._session session2 = client2.transport.update_email_preferences._session assert session1 != session2 + + def test_email_preferences_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.EmailPreferencesServiceGrpcTransport( @@ -2577,7 +3210,7 @@ def test_email_preferences_service_grpc_transport_channel(): def test_email_preferences_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.EmailPreferencesServiceGrpcAsyncIOTransport( @@ -2591,12 +3224,22 @@ def test_email_preferences_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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + ], +) def test_email_preferences_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 @@ -2605,7 +3248,7 @@ def test_email_preferences_service_transport_channel_mtls_with_client_cert_sourc 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", @@ -2635,17 +3278,23 @@ def test_email_preferences_service_transport_channel_mtls_with_client_cert_sourc # 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.EmailPreferencesServiceGrpcTransport, transports.EmailPreferencesServiceGrpcAsyncIOTransport]) -def test_email_preferences_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.EmailPreferencesServiceGrpcTransport, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + ], +) +def test_email_preferences_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() @@ -2676,7 +3325,10 @@ def test_email_preferences_service_transport_channel_mtls_with_adc( def test_email_preferences_path(): account = "squid" email = "clam" - expected = "accounts/{account}/users/{email}/emailPreferences".format(account=account, email=email, ) + expected = "accounts/{account}/users/{email}/emailPreferences".format( + account=account, + email=email, + ) actual = EmailPreferencesServiceClient.email_preferences_path(account, email) assert expected == actual @@ -2692,9 +3344,12 @@ def test_parse_email_preferences_path(): actual = EmailPreferencesServiceClient.parse_email_preferences_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = EmailPreferencesServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2709,9 +3364,12 @@ def test_parse_common_billing_account_path(): actual = EmailPreferencesServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = EmailPreferencesServiceClient.common_folder_path(folder) assert expected == actual @@ -2726,9 +3384,12 @@ def test_parse_common_folder_path(): actual = EmailPreferencesServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = EmailPreferencesServiceClient.common_organization_path(organization) assert expected == actual @@ -2743,9 +3404,12 @@ def test_parse_common_organization_path(): actual = EmailPreferencesServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = EmailPreferencesServiceClient.common_project_path(project) assert expected == actual @@ -2760,10 +3424,14 @@ def test_parse_common_project_path(): actual = EmailPreferencesServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = EmailPreferencesServiceClient.common_location_path(project, location) assert expected == actual @@ -2783,14 +3451,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.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.EmailPreferencesServiceTransport, "_prep_wrapped_messages" + ) as prep: client = EmailPreferencesServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.EmailPreferencesServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.EmailPreferencesServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = EmailPreferencesServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2801,10 +3473,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = EmailPreferencesServiceClient( - 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() @@ -2813,10 +3486,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = EmailPreferencesServiceAsyncClient( - 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() @@ -2824,10 +3498,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = EmailPreferencesServiceClient( - 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() @@ -2835,13 +3510,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = EmailPreferencesServiceClient( - 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: @@ -2850,10 +3524,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (EmailPreferencesServiceClient, transports.EmailPreferencesServiceGrpcTransport), - (EmailPreferencesServiceAsyncClient, transports.EmailPreferencesServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + EmailPreferencesServiceClient, + transports.EmailPreferencesServiceGrpcTransport, + ), + ( + EmailPreferencesServiceAsyncClient, + transports.EmailPreferencesServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2868,7 +3552,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py similarity index 68% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py index 42eb419c7ba8..6c362a5eb337 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_gbp_accounts_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,46 +22,44 @@ 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 empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import GbpAccountsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import GbpAccountsServiceClient -from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import pagers -from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import transports -from google.shopping.merchant_accounts_v1.types import gbpaccounts -import google.auth - +from google.shopping.merchant_accounts_v1.services.gbp_accounts_service import ( + GbpAccountsServiceAsyncClient, + GbpAccountsServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import gbpaccounts CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +74,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(): @@ -85,17 +86,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(): @@ -106,101 +117,241 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert GbpAccountsServiceClient._get_default_mtls_endpoint(None) is None - assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert GbpAccountsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + GbpAccountsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + GbpAccountsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + GbpAccountsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + GbpAccountsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + assert GbpAccountsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert GbpAccountsServiceClient._read_environment_variables() == (True, "auto", None) + assert GbpAccountsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + assert GbpAccountsServiceClient._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: GbpAccountsServiceClient._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 GbpAccountsServiceClient._read_environment_variables() == (False, "never", None) + assert GbpAccountsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "always", None) + assert GbpAccountsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert GbpAccountsServiceClient._read_environment_variables() == (False, "auto", None) + assert GbpAccountsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: GbpAccountsServiceClient._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 GbpAccountsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, False) is None - assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + GbpAccountsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + GbpAccountsServiceClient._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 ( + GbpAccountsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert GbpAccountsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +@mock.patch.object( + GbpAccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceClient), +) +@mock.patch.object( + GbpAccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert GbpAccountsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert GbpAccountsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT - assert GbpAccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + GbpAccountsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + GbpAccountsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GbpAccountsServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + GbpAccountsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GbpAccountsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == GbpAccountsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GbpAccountsServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + GbpAccountsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - GbpAccountsServiceClient._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." + GbpAccountsServiceClient._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 GbpAccountsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert GbpAccountsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert GbpAccountsServiceClient._get_universe_domain(None, None) == GbpAccountsServiceClient._DEFAULT_UNIVERSE + assert ( + GbpAccountsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + GbpAccountsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + GbpAccountsServiceClient._get_universe_domain(None, None) + == GbpAccountsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: GbpAccountsServiceClient._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) @@ -216,7 +367,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") @@ -229,14 +381,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", [ - (GbpAccountsServiceClient, "grpc"), - (GbpAccountsServiceAsyncClient, "grpc_asyncio"), - (GbpAccountsServiceClient, "rest"), -]) -def test_gbp_accounts_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (GbpAccountsServiceClient, "grpc"), + (GbpAccountsServiceAsyncClient, "grpc_asyncio"), + (GbpAccountsServiceClient, "rest"), + ], +) +def test_gbp_accounts_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) @@ -244,52 +404,70 @@ def test_gbp_accounts_service_client_from_service_account_info(client_class, tra 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.GbpAccountsServiceGrpcTransport, "grpc"), - (transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.GbpAccountsServiceRestTransport, "rest"), -]) -def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, "grpc"), + (transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GbpAccountsServiceRestTransport, "rest"), + ], +) +def test_gbp_accounts_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", [ - (GbpAccountsServiceClient, "grpc"), - (GbpAccountsServiceAsyncClient, "grpc_asyncio"), - (GbpAccountsServiceClient, "rest"), -]) -def test_gbp_accounts_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (GbpAccountsServiceClient, "grpc"), + (GbpAccountsServiceAsyncClient, "grpc_asyncio"), + (GbpAccountsServiceClient, "rest"), + ], +) +def test_gbp_accounts_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" ) @@ -305,30 +483,45 @@ def test_gbp_accounts_service_client_get_transport_class(): assert transport == transports.GbpAccountsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), -]) -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) -def test_gbp_accounts_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + GbpAccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceClient), +) +@mock.patch.object( + GbpAccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceAsyncClient), +) +def test_gbp_accounts_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(GbpAccountsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(GbpAccountsServiceClient, "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(GbpAccountsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(GbpAccountsServiceClient, "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( @@ -346,13 +539,15 @@ def test_gbp_accounts_service_client_client_options(client_class, transport_clas # 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, @@ -364,7 +559,7 @@ def test_gbp_accounts_service_client_client_options(client_class, transport_clas # 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( @@ -384,23 +579,33 @@ def test_gbp_accounts_service_client_client_options(client_class, transport_clas 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", @@ -409,48 +614,102 @@ def test_gbp_accounts_service_client_client_options(client_class, transport_clas 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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "true"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", "false"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "true"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceGrpcTransport, + "grpc", + "true", + ), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceGrpcTransport, + "grpc", + "false", + ), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceRestTransport, + "rest", + "true", + ), + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + GbpAccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceClient), +) +@mock.patch.object( + GbpAccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_gbp_accounts_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_gbp_accounts_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 @@ -469,12 +728,22 @@ def test_gbp_accounts_service_client_mtls_env_auto(client_class, transport_class # 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 @@ -495,15 +764,22 @@ def test_gbp_accounts_service_client_mtls_env_auto(client_class, transport_class ) # 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, @@ -513,19 +789,31 @@ def test_gbp_accounts_service_client_mtls_env_auto(client_class, transport_class ) -@pytest.mark.parametrize("client_class", [ - GbpAccountsServiceClient, GbpAccountsServiceAsyncClient -]) -@mock.patch.object(GbpAccountsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(GbpAccountsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [GbpAccountsServiceClient, GbpAccountsServiceAsyncClient] +) +@mock.patch.object( + GbpAccountsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GbpAccountsServiceClient), +) +@mock.patch.object( + GbpAccountsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GbpAccountsServiceAsyncClient), +) def test_gbp_accounts_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 @@ -533,8 +821,12 @@ def test_gbp_accounts_service_client_get_mtls_endpoint_and_cert_source(client_cl 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 @@ -552,16 +844,28 @@ def test_gbp_accounts_service_client_get_mtls_endpoint_and_cert_source(client_cl # 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 @@ -571,34 +875,62 @@ def test_gbp_accounts_service_client_get_mtls_endpoint_and_cert_source(client_cl 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", [ - GbpAccountsServiceClient, GbpAccountsServiceAsyncClient -]) -@mock.patch.object(GbpAccountsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceClient)) -@mock.patch.object(GbpAccountsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(GbpAccountsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [GbpAccountsServiceClient, GbpAccountsServiceAsyncClient] +) +@mock.patch.object( + GbpAccountsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceClient), +) +@mock.patch.object( + GbpAccountsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GbpAccountsServiceAsyncClient), +) def test_gbp_accounts_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = GbpAccountsServiceClient._DEFAULT_UNIVERSE - default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = GbpAccountsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = GbpAccountsServiceClient._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", @@ -621,11 +953,19 @@ def test_gbp_accounts_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. @@ -633,27 +973,40 @@ def test_gbp_accounts_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", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), -]) -def test_gbp_accounts_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc"), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest"), + ], +) +def test_gbp_accounts_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, @@ -662,24 +1015,45 @@ def test_gbp_accounts_service_client_client_options_scopes(client_class, transpo api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (GbpAccountsServiceClient, transports.GbpAccountsServiceRestTransport, "rest", None), -]) -def test_gbp_accounts_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", + [ + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_gbp_accounts_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, @@ -688,11 +1062,14 @@ def test_gbp_accounts_service_client_client_options_credentials_file(client_clas api_audience=None, ) + def test_gbp_accounts_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = GbpAccountsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1084,38 @@ def test_gbp_accounts_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport, "grpc", grpc_helpers), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_gbp_accounts_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", + [ + ( + GbpAccountsServiceClient, + transports.GbpAccountsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_gbp_accounts_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, @@ -750,9 +1142,7 @@ def test_gbp_accounts_service_client_create_channel_credentials_file(client_clas 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, @@ -763,11 +1153,14 @@ def test_gbp_accounts_service_client_create_channel_credentials_file(client_clas ) -@pytest.mark.parametrize("request_type", [ - gbpaccounts.ListGbpAccountsRequest, - dict, -]) -def test_list_gbp_accounts(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gbpaccounts.ListGbpAccountsRequest, + dict, + ], +) +def test_list_gbp_accounts(request_type, transport: str = "grpc"): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,11 +1172,11 @@ def test_list_gbp_accounts(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_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_gbp_accounts(request) @@ -795,7 +1188,7 @@ def test_list_gbp_accounts(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGbpAccountsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_gbp_accounts_non_empty_request_with_auto_populated_field(): @@ -803,30 +1196,33 @@ def test_list_gbp_accounts_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = GbpAccountsServiceClient( 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 = gbpaccounts.ListGbpAccountsRequest( - 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_gbp_accounts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_gbp_accounts), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_gbp_accounts(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gbpaccounts.ListGbpAccountsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_gbp_accounts_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -845,8 +1241,12 @@ def test_list_gbp_accounts_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_gbp_accounts] = 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_gbp_accounts + ] = mock_rpc request = {} client.list_gbp_accounts(request) @@ -859,8 +1259,11 @@ def test_list_gbp_accounts_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_gbp_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_gbp_accounts_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: @@ -874,12 +1277,17 @@ async def test_list_gbp_accounts_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_gbp_accounts in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_gbp_accounts + 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_gbp_accounts] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_gbp_accounts + ] = mock_rpc request = {} await client.list_gbp_accounts(request) @@ -893,8 +1301,11 @@ async def test_list_gbp_accounts_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_gbp_accounts_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.ListGbpAccountsRequest): +async def test_list_gbp_accounts_async( + transport: str = "grpc_asyncio", request_type=gbpaccounts.ListGbpAccountsRequest +): client = GbpAccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -906,12 +1317,14 @@ async def test_list_gbp_accounts_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.ListGbpAccountsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_gbp_accounts(request) # Establish that the underlying gRPC stub method was called. @@ -922,13 +1335,14 @@ async def test_list_gbp_accounts_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGbpAccountsAsyncPager) - 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_gbp_accounts_async_from_dict(): await test_list_gbp_accounts_async(request_type=dict) + def test_list_gbp_accounts_field_headers(): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -938,12 +1352,12 @@ def test_list_gbp_accounts_field_headers(): # a field header. Set these to a non-empty value. request = gbpaccounts.ListGbpAccountsRequest() - 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_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: call.return_value = gbpaccounts.ListGbpAccountsResponse() client.list_gbp_accounts(request) @@ -955,9 +1369,9 @@ def test_list_gbp_accounts_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 @@ -970,13 +1384,15 @@ async def test_list_gbp_accounts_field_headers_async(): # a field header. Set these to a non-empty value. request = gbpaccounts.ListGbpAccountsRequest() - 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_gbp_accounts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) + type(client.transport.list_gbp_accounts), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.ListGbpAccountsResponse() + ) await client.list_gbp_accounts(request) # Establish that the underlying gRPC stub method was called. @@ -987,9 +1403,9 @@ async def test_list_gbp_accounts_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_gbp_accounts_flattened(): @@ -999,14 +1415,14 @@ def test_list_gbp_accounts_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gbpaccounts.ListGbpAccountsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_gbp_accounts( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1014,7 +1430,7 @@ def test_list_gbp_accounts_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 @@ -1028,9 +1444,10 @@ def test_list_gbp_accounts_flattened_error(): with pytest.raises(ValueError): client.list_gbp_accounts( gbpaccounts.ListGbpAccountsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_gbp_accounts_flattened_async(): client = GbpAccountsServiceAsyncClient( @@ -1039,16 +1456,18 @@ async def test_list_gbp_accounts_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gbpaccounts.ListGbpAccountsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.ListGbpAccountsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_gbp_accounts( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1056,9 +1475,10 @@ async def test_list_gbp_accounts_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_gbp_accounts_flattened_error_async(): client = GbpAccountsServiceAsyncClient( @@ -1070,7 +1490,7 @@ async def test_list_gbp_accounts_flattened_error_async(): with pytest.raises(ValueError): await client.list_gbp_accounts( gbpaccounts.ListGbpAccountsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1082,8 +1502,8 @@ def test_list_gbp_accounts_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_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( gbpaccounts.ListGbpAccountsResponse( @@ -1092,17 +1512,17 @@ def test_list_gbp_accounts_pager(transport_name: str = "grpc"): gbpaccounts.GbpAccount(), gbpaccounts.GbpAccount(), ], - next_page_token='abc', + next_page_token="abc", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[], - next_page_token='def', + next_page_token="def", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ gbpaccounts.GbpAccount(), ], - next_page_token='ghi', + next_page_token="ghi", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ @@ -1117,9 +1537,7 @@ def test_list_gbp_accounts_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_gbp_accounts(request={}, retry=retry, timeout=timeout) @@ -1129,8 +1547,9 @@ def test_list_gbp_accounts_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, gbpaccounts.GbpAccount) - for i in results) + assert all(isinstance(i, gbpaccounts.GbpAccount) for i in results) + + def test_list_gbp_accounts_pages(transport_name: str = "grpc"): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1139,8 +1558,8 @@ def test_list_gbp_accounts_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_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( gbpaccounts.ListGbpAccountsResponse( @@ -1149,17 +1568,17 @@ def test_list_gbp_accounts_pages(transport_name: str = "grpc"): gbpaccounts.GbpAccount(), gbpaccounts.GbpAccount(), ], - next_page_token='abc', + next_page_token="abc", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[], - next_page_token='def', + next_page_token="def", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ gbpaccounts.GbpAccount(), ], - next_page_token='ghi', + next_page_token="ghi", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ @@ -1170,9 +1589,10 @@ def test_list_gbp_accounts_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_gbp_accounts(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_gbp_accounts_async_pager(): client = GbpAccountsServiceAsyncClient( @@ -1181,8 +1601,10 @@ async def test_list_gbp_accounts_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_gbp_accounts), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( gbpaccounts.ListGbpAccountsResponse( @@ -1191,17 +1613,17 @@ async def test_list_gbp_accounts_async_pager(): gbpaccounts.GbpAccount(), gbpaccounts.GbpAccount(), ], - next_page_token='abc', + next_page_token="abc", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[], - next_page_token='def', + next_page_token="def", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ gbpaccounts.GbpAccount(), ], - next_page_token='ghi', + next_page_token="ghi", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ @@ -1211,15 +1633,16 @@ async def test_list_gbp_accounts_async_pager(): ), RuntimeError, ) - async_pager = await client.list_gbp_accounts(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_gbp_accounts( + 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, gbpaccounts.GbpAccount) - for i in responses) + assert all(isinstance(i, gbpaccounts.GbpAccount) for i in responses) @pytest.mark.asyncio @@ -1230,8 +1653,10 @@ async def test_list_gbp_accounts_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_gbp_accounts), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( gbpaccounts.ListGbpAccountsResponse( @@ -1240,17 +1665,17 @@ async def test_list_gbp_accounts_async_pages(): gbpaccounts.GbpAccount(), gbpaccounts.GbpAccount(), ], - next_page_token='abc', + next_page_token="abc", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[], - next_page_token='def', + next_page_token="def", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ gbpaccounts.GbpAccount(), ], - next_page_token='ghi', + next_page_token="ghi", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ @@ -1263,18 +1688,22 @@ async def test_list_gbp_accounts_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_gbp_accounts(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", [ - gbpaccounts.LinkGbpAccountRequest, - dict, -]) -def test_link_gbp_account(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + gbpaccounts.LinkGbpAccountRequest, + dict, + ], +) +def test_link_gbp_account(request_type, transport: str = "grpc"): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1285,12 +1714,9 @@ def test_link_gbp_account(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = gbpaccounts.LinkGbpAccountResponse( - ) + call.return_value = gbpaccounts.LinkGbpAccountResponse() response = client.link_gbp_account(request) # Establish that the underlying gRPC stub method was called. @@ -1308,30 +1734,31 @@ def test_link_gbp_account_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = GbpAccountsServiceClient( 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 = gbpaccounts.LinkGbpAccountRequest( - parent='parent_value', - gbp_email='gbp_email_value', + parent="parent_value", + gbp_email="gbp_email_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.link_gbp_account(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gbpaccounts.LinkGbpAccountRequest( - parent='parent_value', - gbp_email='gbp_email_value', + parent="parent_value", + gbp_email="gbp_email_value", ) + def test_link_gbp_account_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1350,8 +1777,12 @@ def test_link_gbp_account_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.link_gbp_account + ] = mock_rpc request = {} client.link_gbp_account(request) @@ -1364,8 +1795,11 @@ def test_link_gbp_account_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_link_gbp_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_link_gbp_account_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: @@ -1379,12 +1813,17 @@ async def test_link_gbp_account_async_use_cached_wrapped_rpc(transport: str = "g wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.link_gbp_account in client._client._transport._wrapped_methods + assert ( + client._client._transport.link_gbp_account + 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.link_gbp_account] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.link_gbp_account + ] = mock_rpc request = {} await client.link_gbp_account(request) @@ -1398,8 +1837,11 @@ async def test_link_gbp_account_async_use_cached_wrapped_rpc(transport: str = "g assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_link_gbp_account_async(transport: str = 'grpc_asyncio', request_type=gbpaccounts.LinkGbpAccountRequest): +async def test_link_gbp_account_async( + transport: str = "grpc_asyncio", request_type=gbpaccounts.LinkGbpAccountRequest +): client = GbpAccountsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1410,12 +1852,11 @@ async def test_link_gbp_account_async(transport: str = 'grpc_asyncio', request_t request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.LinkGbpAccountResponse() + ) response = await client.link_gbp_account(request) # Establish that the underlying gRPC stub method was called. @@ -1432,6 +1873,7 @@ async def test_link_gbp_account_async(transport: str = 'grpc_asyncio', request_t async def test_link_gbp_account_async_from_dict(): await test_link_gbp_account_async(request_type=dict) + def test_link_gbp_account_field_headers(): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1441,12 +1883,10 @@ def test_link_gbp_account_field_headers(): # a field header. Set these to a non-empty value. request = gbpaccounts.LinkGbpAccountRequest() - 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.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: call.return_value = gbpaccounts.LinkGbpAccountResponse() client.link_gbp_account(request) @@ -1458,9 +1898,9 @@ def test_link_gbp_account_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 @@ -1473,13 +1913,13 @@ async def test_link_gbp_account_field_headers_async(): # a field header. Set these to a non-empty value. request = gbpaccounts.LinkGbpAccountRequest() - 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.link_gbp_account), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.LinkGbpAccountResponse() + ) await client.link_gbp_account(request) # Establish that the underlying gRPC stub method was called. @@ -1490,9 +1930,9 @@ async def test_link_gbp_account_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_link_gbp_account_flattened(): @@ -1501,15 +1941,13 @@ def test_link_gbp_account_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gbpaccounts.LinkGbpAccountResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.link_gbp_account( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1517,7 +1955,7 @@ def test_link_gbp_account_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 @@ -1531,9 +1969,10 @@ def test_link_gbp_account_flattened_error(): with pytest.raises(ValueError): client.link_gbp_account( gbpaccounts.LinkGbpAccountRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_link_gbp_account_flattened_async(): client = GbpAccountsServiceAsyncClient( @@ -1541,17 +1980,17 @@ async def test_link_gbp_account_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gbpaccounts.LinkGbpAccountResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.LinkGbpAccountResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.link_gbp_account( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1559,9 +1998,10 @@ async def test_link_gbp_account_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_link_gbp_account_flattened_error_async(): client = GbpAccountsServiceAsyncClient( @@ -1573,7 +2013,7 @@ async def test_link_gbp_account_flattened_error_async(): with pytest.raises(ValueError): await client.link_gbp_account( gbpaccounts.LinkGbpAccountRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1595,8 +2035,12 @@ def test_list_gbp_accounts_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_gbp_accounts] = 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_gbp_accounts + ] = mock_rpc request = {} client.list_gbp_accounts(request) @@ -1611,57 +2055,67 @@ def test_list_gbp_accounts_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_gbp_accounts_rest_required_fields(request_type=gbpaccounts.ListGbpAccountsRequest): +def test_list_gbp_accounts_rest_required_fields( + request_type=gbpaccounts.ListGbpAccountsRequest, +): transport_class = transports.GbpAccountsServiceRestTransport 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_gbp_accounts._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_gbp_accounts._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_gbp_accounts._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_gbp_accounts._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 = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gbpaccounts.ListGbpAccountsResponse() # Mock the http request 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 @@ -1672,24 +2126,32 @@ def test_list_gbp_accounts_rest_required_fields(request_type=gbpaccounts.ListGbp return_value = gbpaccounts.ListGbpAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_gbp_accounts(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_gbp_accounts_rest_unset_required_fields(): - transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.GbpAccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_gbp_accounts._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_gbp_accounts_rest_flattened(): @@ -1699,16 +2161,16 @@ def test_list_gbp_accounts_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 = gbpaccounts.ListGbpAccountsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1718,7 +2180,7 @@ def test_list_gbp_accounts_rest_flattened(): # Convert return value to protobuf type return_value = gbpaccounts.ListGbpAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1728,10 +2190,13 @@ def test_list_gbp_accounts_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/gbpAccounts" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/gbpAccounts" % client.transport._host, + args[1], + ) -def test_list_gbp_accounts_rest_flattened_error(transport: str = 'rest'): +def test_list_gbp_accounts_rest_flattened_error(transport: str = "rest"): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1742,20 +2207,20 @@ def test_list_gbp_accounts_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_gbp_accounts( gbpaccounts.ListGbpAccountsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_gbp_accounts_rest_pager(transport: str = 'rest'): +def test_list_gbp_accounts_rest_pager(transport: str = "rest"): client = GbpAccountsServiceClient( 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 = ( gbpaccounts.ListGbpAccountsResponse( @@ -1764,17 +2229,17 @@ def test_list_gbp_accounts_rest_pager(transport: str = 'rest'): gbpaccounts.GbpAccount(), gbpaccounts.GbpAccount(), ], - next_page_token='abc', + next_page_token="abc", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[], - next_page_token='def', + next_page_token="def", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ gbpaccounts.GbpAccount(), ], - next_page_token='ghi', + next_page_token="ghi", ), gbpaccounts.ListGbpAccountsResponse( gbp_accounts=[ @@ -1787,24 +2252,25 @@ def test_list_gbp_accounts_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(gbpaccounts.ListGbpAccountsResponse.to_json(x) for x in response) + response = tuple( + gbpaccounts.ListGbpAccountsResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_gbp_accounts(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, gbpaccounts.GbpAccount) - for i in results) + assert all(isinstance(i, gbpaccounts.GbpAccount) for i in results) pages = list(client.list_gbp_accounts(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 @@ -1826,8 +2292,12 @@ def test_link_gbp_account_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_gbp_account] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.link_gbp_account + ] = mock_rpc request = {} client.link_gbp_account(request) @@ -1842,7 +2312,9 @@ def test_link_gbp_account_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_link_gbp_account_rest_required_fields(request_type=gbpaccounts.LinkGbpAccountRequest): +def test_link_gbp_account_rest_required_fields( + request_type=gbpaccounts.LinkGbpAccountRequest, +): transport_class = transports.GbpAccountsServiceRestTransport request_init = {} @@ -1850,53 +2322,56 @@ def test_link_gbp_account_rest_required_fields(request_type=gbpaccounts.LinkGbpA request_init["gbp_email"] = "" 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()).link_gbp_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).link_gbp_account._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["gbpEmail"] = 'gbp_email_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["gbpEmail"] = "gbp_email_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_gbp_account._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).link_gbp_account._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" assert "gbpEmail" in jsonified_request - assert jsonified_request["gbpEmail"] == 'gbp_email_value' + assert jsonified_request["gbpEmail"] == "gbp_email_value" client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gbpaccounts.LinkGbpAccountResponse() # Mock the http request 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() @@ -1906,24 +2381,32 @@ def test_link_gbp_account_rest_required_fields(request_type=gbpaccounts.LinkGbpA return_value = gbpaccounts.LinkGbpAccountResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.link_gbp_account(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_link_gbp_account_rest_unset_required_fields(): - transport = transports.GbpAccountsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.GbpAccountsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.link_gbp_account._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "gbpEmail", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "gbpEmail", + ) + ) + ) def test_link_gbp_account_rest_flattened(): @@ -1933,16 +2416,16 @@ def test_link_gbp_account_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 = gbpaccounts.LinkGbpAccountResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1952,7 +2435,7 @@ def test_link_gbp_account_rest_flattened(): # Convert return value to protobuf type return_value = gbpaccounts.LinkGbpAccountResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._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 +2445,14 @@ def test_link_gbp_account_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/gbpAccounts:linkGbpAccount" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/gbpAccounts:linkGbpAccount" + % client.transport._host, + args[1], + ) -def test_link_gbp_account_rest_flattened_error(transport: str = 'rest'): +def test_link_gbp_account_rest_flattened_error(transport: str = "rest"): client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1976,7 +2463,7 @@ def test_link_gbp_account_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.link_gbp_account( gbpaccounts.LinkGbpAccountRequest(), - parent='parent_value', + parent="parent_value", ) @@ -2018,8 +2505,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = GbpAccountsServiceClient( - 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. @@ -2041,6 +2527,7 @@ def test_transport_instance(): client = GbpAccountsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.GbpAccountsServiceGrpcTransport( @@ -2055,18 +2542,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.GbpAccountsServiceGrpcTransport, - transports.GbpAccountsServiceGrpcAsyncIOTransport, - transports.GbpAccountsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + transports.GbpAccountsServiceRestTransport, + ], +) 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 = GbpAccountsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2076,8 +2568,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2092,8 +2583,8 @@ def test_list_gbp_accounts_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: call.return_value = gbpaccounts.ListGbpAccountsResponse() client.list_gbp_accounts(request=None) @@ -2114,9 +2605,7 @@ def test_link_gbp_account_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: call.return_value = gbpaccounts.LinkGbpAccountResponse() client.link_gbp_account(request=None) @@ -2137,8 +2626,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = GbpAccountsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2154,12 +2642,14 @@ async def test_list_gbp_accounts_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.ListGbpAccountsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_gbp_accounts(request=None) # Establish that the underlying stub method was called. @@ -2180,12 +2670,11 @@ async def test_link_gbp_account_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gbpaccounts.LinkGbpAccountResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gbpaccounts.LinkGbpAccountResponse() + ) await client.link_gbp_account(request=None) # Establish that the underlying stub method was called. @@ -2203,20 +2692,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_list_gbp_accounts_rest_bad_request(request_type=gbpaccounts.ListGbpAccountsRequest): +def test_list_gbp_accounts_rest_bad_request( + request_type=gbpaccounts.ListGbpAccountsRequest, +): client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -2225,25 +2717,27 @@ def test_list_gbp_accounts_rest_bad_request(request_type=gbpaccounts.ListGbpAcco client.list_gbp_accounts(request) -@pytest.mark.parametrize("request_type", [ - gbpaccounts.ListGbpAccountsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gbpaccounts.ListGbpAccountsRequest, + dict, + ], +) def test_list_gbp_accounts_rest_call_success(request_type): client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gbpaccounts.ListGbpAccountsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -2253,33 +2747,44 @@ def test_list_gbp_accounts_rest_call_success(request_type): # Convert return value to protobuf type return_value = gbpaccounts.ListGbpAccountsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_gbp_accounts(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListGbpAccountsPager) - 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_gbp_accounts_rest_interceptors(null_interceptor): transport = transports.GbpAccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.GbpAccountsServiceRestInterceptor(), + ) client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts") as post, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_list_gbp_accounts") 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.GbpAccountsServiceRestInterceptor, "post_list_gbp_accounts" + ) as post, mock.patch.object( + transports.GbpAccountsServiceRestInterceptor, + "post_list_gbp_accounts_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GbpAccountsServiceRestInterceptor, "pre_list_gbp_accounts" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gbpaccounts.ListGbpAccountsRequest.pb(gbpaccounts.ListGbpAccountsRequest()) + pb_message = gbpaccounts.ListGbpAccountsRequest.pb( + gbpaccounts.ListGbpAccountsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2290,39 +2795,53 @@ def test_list_gbp_accounts_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 = gbpaccounts.ListGbpAccountsResponse.to_json(gbpaccounts.ListGbpAccountsResponse()) + return_value = gbpaccounts.ListGbpAccountsResponse.to_json( + gbpaccounts.ListGbpAccountsResponse() + ) req.return_value.content = return_value request = gbpaccounts.ListGbpAccountsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = gbpaccounts.ListGbpAccountsResponse() - post_with_metadata.return_value = gbpaccounts.ListGbpAccountsResponse(), metadata + post_with_metadata.return_value = ( + gbpaccounts.ListGbpAccountsResponse(), + metadata, + ) - client.list_gbp_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_gbp_accounts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_link_gbp_account_rest_bad_request(request_type=gbpaccounts.LinkGbpAccountRequest): +def test_link_gbp_account_rest_bad_request( + request_type=gbpaccounts.LinkGbpAccountRequest, +): client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -2331,25 +2850,26 @@ def test_link_gbp_account_rest_bad_request(request_type=gbpaccounts.LinkGbpAccou client.link_gbp_account(request) -@pytest.mark.parametrize("request_type", [ - gbpaccounts.LinkGbpAccountRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gbpaccounts.LinkGbpAccountRequest, + dict, + ], +) def test_link_gbp_account_rest_call_success(request_type): client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = gbpaccounts.LinkGbpAccountResponse( - ) + return_value = gbpaccounts.LinkGbpAccountResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -2358,7 +2878,7 @@ def test_link_gbp_account_rest_call_success(request_type): # Convert return value to protobuf type return_value = gbpaccounts.LinkGbpAccountResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.link_gbp_account(request) @@ -2371,19 +2891,30 @@ def test_link_gbp_account_rest_call_success(request_type): def test_link_gbp_account_rest_interceptors(null_interceptor): transport = transports.GbpAccountsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.GbpAccountsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.GbpAccountsServiceRestInterceptor(), + ) client = GbpAccountsServiceClient(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.GbpAccountsServiceRestInterceptor, "post_link_gbp_account") as post, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "post_link_gbp_account_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.GbpAccountsServiceRestInterceptor, "pre_link_gbp_account") 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.GbpAccountsServiceRestInterceptor, "post_link_gbp_account" + ) as post, mock.patch.object( + transports.GbpAccountsServiceRestInterceptor, + "post_link_gbp_account_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GbpAccountsServiceRestInterceptor, "pre_link_gbp_account" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gbpaccounts.LinkGbpAccountRequest.pb(gbpaccounts.LinkGbpAccountRequest()) + pb_message = gbpaccounts.LinkGbpAccountRequest.pb( + gbpaccounts.LinkGbpAccountRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2394,11 +2925,13 @@ def test_link_gbp_account_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 = gbpaccounts.LinkGbpAccountResponse.to_json(gbpaccounts.LinkGbpAccountResponse()) + return_value = gbpaccounts.LinkGbpAccountResponse.to_json( + gbpaccounts.LinkGbpAccountResponse() + ) req.return_value.content = return_value request = gbpaccounts.LinkGbpAccountRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2406,16 +2939,22 @@ def test_link_gbp_account_rest_interceptors(null_interceptor): post.return_value = gbpaccounts.LinkGbpAccountResponse() post_with_metadata.return_value = gbpaccounts.LinkGbpAccountResponse(), metadata - client.link_gbp_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.link_gbp_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = GbpAccountsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2430,8 +2969,8 @@ def test_list_gbp_accounts_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_gbp_accounts), - '__call__') as call: + type(client.transport.list_gbp_accounts), "__call__" + ) as call: client.list_gbp_accounts(request=None) # Establish that the underlying stub method was called. @@ -2451,9 +2990,7 @@ def test_link_gbp_account_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.link_gbp_account), - '__call__') as call: + with mock.patch.object(type(client.transport.link_gbp_account), "__call__") as call: client.link_gbp_account(request=None) # Establish that the underlying stub method was called. @@ -2474,18 +3011,21 @@ def test_transport_grpc_default(): transports.GbpAccountsServiceGrpcTransport, ) + def test_gbp_accounts_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.GbpAccountsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_gbp_accounts_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.GbpAccountsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2494,8 +3034,8 @@ def test_gbp_accounts_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'list_gbp_accounts', - 'link_gbp_account', + "list_gbp_accounts", + "link_gbp_account", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2506,7 +3046,7 @@ def test_gbp_accounts_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2515,25 +3055,30 @@ def test_gbp_accounts_service_base_transport(): def test_gbp_accounts_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_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._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_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GbpAccountsServiceTransport( 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_gbp_accounts_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_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.gbp_accounts_service.transports.GbpAccountsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.GbpAccountsServiceTransport() @@ -2542,14 +3087,12 @@ def test_gbp_accounts_service_base_transport_with_adc(): def test_gbp_accounts_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) GbpAccountsServiceClient() 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, ) @@ -2564,12 +3107,12 @@ def test_gbp_accounts_service_auth_adc(): def test_gbp_accounts_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", ) @@ -2583,48 +3126,45 @@ def test_gbp_accounts_service_transport_auth_adc(transport_class): ], ) def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, grpc_helpers), - (transports.GbpAccountsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.GbpAccountsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_gbp_accounts_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, @@ -2635,9 +3175,15 @@ def test_gbp_accounts_service_transport_create_channel(transport_class, grpc_hel ) -@pytest.mark.parametrize("transport_class", [transports.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + ], +) def test_gbp_accounts_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2647,7 +3193,7 @@ def test_gbp_accounts_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", @@ -2668,61 +3214,77 @@ def test_gbp_accounts_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_gbp_accounts_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.GbpAccountsServiceRestTransport ( - 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.GbpAccountsServiceRestTransport( + 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_gbp_accounts_service_host_no_port(transport_name): client = GbpAccountsServiceClient( 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_gbp_accounts_service_host_with_port(transport_name): client = GbpAccountsServiceClient( 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_gbp_accounts_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2740,8 +3302,10 @@ def test_gbp_accounts_service_client_transport_session_collision(transport_name) session1 = client1.transport.link_gbp_account._session session2 = client2.transport.link_gbp_account._session assert session1 != session2 + + def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport( @@ -2754,7 +3318,7 @@ def test_gbp_accounts_service_grpc_transport_channel(): def test_gbp_accounts_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.GbpAccountsServiceGrpcAsyncIOTransport( @@ -2768,12 +3332,22 @@ def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + ], +) def test_gbp_accounts_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 @@ -2782,7 +3356,7 @@ def test_gbp_accounts_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", @@ -2812,17 +3386,23 @@ def test_gbp_accounts_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.GbpAccountsServiceGrpcTransport, transports.GbpAccountsServiceGrpcAsyncIOTransport]) -def test_gbp_accounts_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.GbpAccountsServiceGrpcTransport, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + ], +) +def test_gbp_accounts_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() @@ -2852,7 +3432,9 @@ def test_gbp_accounts_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = GbpAccountsServiceClient.account_path(account) assert expected == actual @@ -2867,10 +3449,14 @@ def test_parse_account_path(): actual = GbpAccountsServiceClient.parse_account_path(path) assert expected == actual + def test_gbp_account_path(): account = "whelk" gbp_account = "octopus" - expected = "accounts/{account}/gbpAccounts/{gbp_account}".format(account=account, gbp_account=gbp_account, ) + expected = "accounts/{account}/gbpAccounts/{gbp_account}".format( + account=account, + gbp_account=gbp_account, + ) actual = GbpAccountsServiceClient.gbp_account_path(account, gbp_account) assert expected == actual @@ -2886,9 +3472,12 @@ def test_parse_gbp_account_path(): actual = GbpAccountsServiceClient.parse_gbp_account_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 = GbpAccountsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2903,9 +3492,12 @@ def test_parse_common_billing_account_path(): actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_folder_path(folder) assert expected == actual @@ -2920,9 +3512,12 @@ def test_parse_common_folder_path(): actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_organization_path(organization) assert expected == actual @@ -2937,9 +3532,12 @@ def test_parse_common_organization_path(): actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_project_path(project) assert expected == actual @@ -2954,10 +3552,14 @@ def test_parse_common_project_path(): actual = GbpAccountsServiceClient.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 = GbpAccountsServiceClient.common_location_path(project, location) assert expected == actual @@ -2977,14 +3579,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.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.GbpAccountsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = GbpAccountsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.GbpAccountsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.GbpAccountsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = GbpAccountsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2995,10 +3601,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = GbpAccountsServiceClient( - 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() @@ -3007,10 +3614,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = GbpAccountsServiceAsyncClient( - 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() @@ -3018,10 +3626,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = GbpAccountsServiceClient( - 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() @@ -3029,13 +3638,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = GbpAccountsServiceClient( - 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: @@ -3044,10 +3652,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport), - (GbpAccountsServiceAsyncClient, transports.GbpAccountsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (GbpAccountsServiceClient, transports.GbpAccountsServiceGrpcTransport), + ( + GbpAccountsServiceAsyncClient, + transports.GbpAccountsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3062,7 +3677,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py similarity index 69% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py index cae1a8c9f93f..d72223761f4e 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_homepage_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_homepage_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,46 +22,44 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.homepage_service import HomepageServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.homepage_service import HomepageServiceClient -from google.shopping.merchant_accounts_v1.services.homepage_service import transports -from google.shopping.merchant_accounts_v1.types import homepage -from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage -import google.auth - +from google.shopping.merchant_accounts_v1.services.homepage_service import ( + HomepageServiceAsyncClient, + HomepageServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import homepage as gsma_homepage +from google.shopping.merchant_accounts_v1.types import homepage CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +74,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(): @@ -85,17 +86,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(): @@ -106,101 +117,228 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert HomepageServiceClient._get_default_mtls_endpoint(None) is None - assert HomepageServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert HomepageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + HomepageServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + HomepageServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + HomepageServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HomepageServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HomepageServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + def test__read_environment_variables(): assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert HomepageServiceClient._read_environment_variables() == (True, "auto", None) + assert HomepageServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + assert HomepageServiceClient._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: HomepageServiceClient._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 HomepageServiceClient._read_environment_variables() == (False, "never", None) + assert HomepageServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert HomepageServiceClient._read_environment_variables() == (False, "always", None) + assert HomepageServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert HomepageServiceClient._read_environment_variables() == (False, "auto", None) + assert HomepageServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: HomepageServiceClient._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 HomepageServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, False) is None - assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + HomepageServiceClient._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 ( + HomepageServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + HomepageServiceClient._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 HomepageServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert HomepageServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +@mock.patch.object( + HomepageServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceClient), +) +@mock.patch.object( + HomepageServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = HomepageServiceClient._DEFAULT_UNIVERSE - default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert HomepageServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - assert HomepageServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT - assert HomepageServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert HomepageServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + HomepageServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + HomepageServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HomepageServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + HomepageServiceClient._get_api_endpoint(None, None, default_universe, "always") + == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HomepageServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == HomepageServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HomepageServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + HomepageServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - HomepageServiceClient._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." + HomepageServiceClient._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 HomepageServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert HomepageServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert HomepageServiceClient._get_universe_domain(None, None) == HomepageServiceClient._DEFAULT_UNIVERSE + assert ( + HomepageServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + HomepageServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + HomepageServiceClient._get_universe_domain(None, None) + == HomepageServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: HomepageServiceClient._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) @@ -216,7 +354,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") @@ -229,14 +368,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", [ - (HomepageServiceClient, "grpc"), - (HomepageServiceAsyncClient, "grpc_asyncio"), - (HomepageServiceClient, "rest"), -]) -def test_homepage_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (HomepageServiceClient, "grpc"), + (HomepageServiceAsyncClient, "grpc_asyncio"), + (HomepageServiceClient, "rest"), + ], +) +def test_homepage_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) @@ -244,52 +391,70 @@ def test_homepage_service_client_from_service_account_info(client_class, transpo 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.HomepageServiceGrpcTransport, "grpc"), - (transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.HomepageServiceRestTransport, "rest"), -]) -def test_homepage_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.HomepageServiceGrpcTransport, "grpc"), + (transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.HomepageServiceRestTransport, "rest"), + ], +) +def test_homepage_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", [ - (HomepageServiceClient, "grpc"), - (HomepageServiceAsyncClient, "grpc_asyncio"), - (HomepageServiceClient, "rest"), -]) -def test_homepage_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (HomepageServiceClient, "grpc"), + (HomepageServiceAsyncClient, "grpc_asyncio"), + (HomepageServiceClient, "rest"), + ], +) +def test_homepage_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" ) @@ -305,30 +470,45 @@ def test_homepage_service_client_get_transport_class(): assert transport == transports.HomepageServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), -]) -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) -def test_homepage_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + ( + HomepageServiceAsyncClient, + transports.HomepageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + HomepageServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceClient), +) +@mock.patch.object( + HomepageServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceAsyncClient), +) +def test_homepage_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(HomepageServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(HomepageServiceClient, "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(HomepageServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(HomepageServiceClient, "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( @@ -346,13 +526,15 @@ def test_homepage_service_client_client_options(client_class, transport_class, t # 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, @@ -364,7 +546,7 @@ def test_homepage_service_client_client_options(client_class, transport_class, t # 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( @@ -384,23 +566,33 @@ def test_homepage_service_client_client_options(client_class, transport_class, t 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", @@ -409,48 +601,102 @@ def test_homepage_service_client_client_options(client_class, transport_class, t 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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "true"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", "false"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "true"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + HomepageServiceClient, + transports.HomepageServiceGrpcTransport, + "grpc", + "true", + ), + ( + HomepageServiceAsyncClient, + transports.HomepageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + HomepageServiceClient, + transports.HomepageServiceGrpcTransport, + "grpc", + "false", + ), + ( + HomepageServiceAsyncClient, + transports.HomepageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + HomepageServiceClient, + transports.HomepageServiceRestTransport, + "rest", + "true", + ), + ( + HomepageServiceClient, + transports.HomepageServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + HomepageServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceClient), +) +@mock.patch.object( + HomepageServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_homepage_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_homepage_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 @@ -469,12 +715,22 @@ def test_homepage_service_client_mtls_env_auto(client_class, transport_class, tr # 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 @@ -495,15 +751,22 @@ def test_homepage_service_client_mtls_env_auto(client_class, transport_class, tr ) # 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, @@ -513,19 +776,31 @@ def test_homepage_service_client_mtls_env_auto(client_class, transport_class, tr ) -@pytest.mark.parametrize("client_class", [ - HomepageServiceClient, HomepageServiceAsyncClient -]) -@mock.patch.object(HomepageServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HomepageServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [HomepageServiceClient, HomepageServiceAsyncClient] +) +@mock.patch.object( + HomepageServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(HomepageServiceClient), +) +@mock.patch.object( + HomepageServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(HomepageServiceAsyncClient), +) def test_homepage_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 @@ -533,8 +808,12 @@ def test_homepage_service_client_get_mtls_endpoint_and_cert_source(client_class) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -552,16 +831,28 @@ def test_homepage_service_client_get_mtls_endpoint_and_cert_source(client_class) # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -571,34 +862,62 @@ def test_homepage_service_client_get_mtls_endpoint_and_cert_source(client_class) with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # 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", [ - HomepageServiceClient, HomepageServiceAsyncClient -]) -@mock.patch.object(HomepageServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceClient)) -@mock.patch.object(HomepageServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(HomepageServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [HomepageServiceClient, HomepageServiceAsyncClient] +) +@mock.patch.object( + HomepageServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceClient), +) +@mock.patch.object( + HomepageServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HomepageServiceAsyncClient), +) def test_homepage_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = HomepageServiceClient._DEFAULT_UNIVERSE - default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = HomepageServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = HomepageServiceClient._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", @@ -621,11 +940,19 @@ def test_homepage_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. @@ -633,27 +960,40 @@ def test_homepage_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", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), -]) -def test_homepage_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc"), + ( + HomepageServiceAsyncClient, + transports.HomepageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest"), + ], +) +def test_homepage_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, @@ -662,24 +1002,40 @@ def test_homepage_service_client_client_options_scopes(client_class, transport_c api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", None), -]) -def test_homepage_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", + [ + ( + HomepageServiceClient, + transports.HomepageServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + HomepageServiceAsyncClient, + transports.HomepageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (HomepageServiceClient, transports.HomepageServiceRestTransport, "rest", None), + ], +) +def test_homepage_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, @@ -688,11 +1044,14 @@ def test_homepage_service_client_client_options_credentials_file(client_class, t api_audience=None, ) + def test_homepage_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = HomepageServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1066,38 @@ def test_homepage_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport, "grpc", grpc_helpers), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_homepage_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", + [ + ( + HomepageServiceClient, + transports.HomepageServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + HomepageServiceAsyncClient, + transports.HomepageServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_homepage_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, @@ -750,9 +1124,7 @@ def test_homepage_service_client_create_channel_credentials_file(client_class, t 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, @@ -763,11 +1135,14 @@ def test_homepage_service_client_create_channel_credentials_file(client_class, t ) -@pytest.mark.parametrize("request_type", [ - homepage.GetHomepageRequest, - dict, -]) -def test_get_homepage(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + homepage.GetHomepageRequest, + dict, + ], +) +def test_get_homepage(request_type, transport: str = "grpc"): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,13 +1153,11 @@ def test_get_homepage(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = homepage.Homepage( - name='name_value', - uri='uri_value', + name="name_value", + uri="uri_value", claimed=True, ) response = client.get_homepage(request) @@ -797,8 +1170,8 @@ def test_get_homepage(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -807,28 +1180,29 @@ def test_get_homepage_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = HomepageServiceClient( 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 = homepage.GetHomepageRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_homepage(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == homepage.GetHomepageRequest( - name='name_value', + name="name_value", ) + def test_get_homepage_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -847,7 +1221,9 @@ def test_get_homepage_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc request = {} client.get_homepage(request) @@ -861,8 +1237,11 @@ def test_get_homepage_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_homepage_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_homepage_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: @@ -876,12 +1255,17 @@ async def test_get_homepage_async_use_cached_wrapped_rpc(transport: str = "grpc_ wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_homepage in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_homepage + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_homepage] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_homepage + ] = mock_rpc request = {} await client.get_homepage(request) @@ -895,8 +1279,11 @@ async def test_get_homepage_async_use_cached_wrapped_rpc(transport: str = "grpc_ assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.GetHomepageRequest): +async def test_get_homepage_async( + transport: str = "grpc_asyncio", request_type=homepage.GetHomepageRequest +): client = HomepageServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -907,15 +1294,15 @@ async def test_get_homepage_async(transport: str = 'grpc_asyncio', request_type= request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) response = await client.get_homepage(request) # Establish that the underlying gRPC stub method was called. @@ -926,8 +1313,8 @@ async def test_get_homepage_async(transport: str = 'grpc_asyncio', request_type= # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -935,6 +1322,7 @@ async def test_get_homepage_async(transport: str = 'grpc_asyncio', request_type= async def test_get_homepage_async_from_dict(): await test_get_homepage_async(request_type=dict) + def test_get_homepage_field_headers(): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -944,12 +1332,10 @@ def test_get_homepage_field_headers(): # a field header. Set these to a non-empty value. request = homepage.GetHomepageRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: call.return_value = homepage.Homepage() client.get_homepage(request) @@ -961,9 +1347,9 @@ def test_get_homepage_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 @@ -976,12 +1362,10 @@ async def test_get_homepage_field_headers_async(): # a field header. Set these to a non-empty value. request = homepage.GetHomepageRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) await client.get_homepage(request) @@ -993,9 +1377,9 @@ async def test_get_homepage_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_homepage_flattened(): @@ -1004,15 +1388,13 @@ def test_get_homepage_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = homepage.Homepage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_homepage( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1020,7 +1402,7 @@ def test_get_homepage_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 @@ -1034,9 +1416,10 @@ def test_get_homepage_flattened_error(): with pytest.raises(ValueError): client.get_homepage( homepage.GetHomepageRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_homepage_flattened_async(): client = HomepageServiceAsyncClient( @@ -1044,9 +1427,7 @@ async def test_get_homepage_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = homepage.Homepage() @@ -1054,7 +1435,7 @@ async def test_get_homepage_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_homepage( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1062,9 +1443,10 @@ async def test_get_homepage_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_homepage_flattened_error_async(): client = HomepageServiceAsyncClient( @@ -1076,15 +1458,18 @@ async def test_get_homepage_flattened_error_async(): with pytest.raises(ValueError): await client.get_homepage( homepage.GetHomepageRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gsma_homepage.UpdateHomepageRequest, - dict, -]) -def test_update_homepage(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gsma_homepage.UpdateHomepageRequest, + dict, + ], +) +def test_update_homepage(request_type, transport: str = "grpc"): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1095,13 +1480,11 @@ def test_update_homepage(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_homepage.Homepage( - name='name_value', - uri='uri_value', + name="name_value", + uri="uri_value", claimed=True, ) response = client.update_homepage(request) @@ -1114,8 +1497,8 @@ def test_update_homepage(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, gsma_homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -1124,25 +1507,24 @@ def test_update_homepage_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = HomepageServiceClient( 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 = gsma_homepage.UpdateHomepageRequest( - ) + request = gsma_homepage.UpdateHomepageRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_homepage(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gsma_homepage.UpdateHomepageRequest( - ) + assert args[0] == gsma_homepage.UpdateHomepageRequest() + def test_update_homepage_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1162,7 +1544,9 @@ def test_update_homepage_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc request = {} client.update_homepage(request) @@ -1176,8 +1560,11 @@ def test_update_homepage_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_homepage_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_homepage_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: @@ -1191,12 +1578,17 @@ async def test_update_homepage_async_use_cached_wrapped_rpc(transport: str = "gr wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_homepage in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_homepage + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_homepage] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_homepage + ] = mock_rpc request = {} await client.update_homepage(request) @@ -1210,8 +1602,11 @@ async def test_update_homepage_async_use_cached_wrapped_rpc(transport: str = "gr assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_homepage_async(transport: str = 'grpc_asyncio', request_type=gsma_homepage.UpdateHomepageRequest): +async def test_update_homepage_async( + transport: str = "grpc_asyncio", request_type=gsma_homepage.UpdateHomepageRequest +): client = HomepageServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1222,15 +1617,15 @@ async def test_update_homepage_async(transport: str = 'grpc_asyncio', request_ty request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) response = await client.update_homepage(request) # Establish that the underlying gRPC stub method was called. @@ -1241,8 +1636,8 @@ async def test_update_homepage_async(transport: str = 'grpc_asyncio', request_ty # Establish that the response is the type that we expect. assert isinstance(response, gsma_homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -1250,6 +1645,7 @@ async def test_update_homepage_async(transport: str = 'grpc_asyncio', request_ty async def test_update_homepage_async_from_dict(): await test_update_homepage_async(request_type=dict) + def test_update_homepage_field_headers(): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1259,12 +1655,10 @@ def test_update_homepage_field_headers(): # a field header. Set these to a non-empty value. request = gsma_homepage.UpdateHomepageRequest() - request.homepage.name = 'name_value' + request.homepage.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: call.return_value = gsma_homepage.Homepage() client.update_homepage(request) @@ -1276,9 +1670,9 @@ def test_update_homepage_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'homepage.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "homepage.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1291,13 +1685,13 @@ async def test_update_homepage_field_headers_async(): # a field header. Set these to a non-empty value. request = gsma_homepage.UpdateHomepageRequest() - request.homepage.name = 'name_value' + request.homepage.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_homepage.Homepage() + ) await client.update_homepage(request) # Establish that the underlying gRPC stub method was called. @@ -1308,9 +1702,9 @@ async def test_update_homepage_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'homepage.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "homepage.name=name_value", + ) in kw["metadata"] def test_update_homepage_flattened(): @@ -1319,16 +1713,14 @@ def test_update_homepage_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_homepage.Homepage() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_homepage( - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + homepage=gsma_homepage.Homepage(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1336,10 +1728,10 @@ def test_update_homepage_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].homepage - mock_val = gsma_homepage.Homepage(name='name_value') + mock_val = gsma_homepage.Homepage(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1353,10 +1745,11 @@ def test_update_homepage_flattened_error(): with pytest.raises(ValueError): client.update_homepage( gsma_homepage.UpdateHomepageRequest(), - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + homepage=gsma_homepage.Homepage(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_homepage_flattened_async(): client = HomepageServiceAsyncClient( @@ -1364,18 +1757,18 @@ async def test_update_homepage_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_homepage.Homepage() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_homepage.Homepage() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_homepage( - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + homepage=gsma_homepage.Homepage(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1383,12 +1776,13 @@ async def test_update_homepage_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].homepage - mock_val = gsma_homepage.Homepage(name='name_value') + mock_val = gsma_homepage.Homepage(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_homepage_flattened_error_async(): client = HomepageServiceAsyncClient( @@ -1400,16 +1794,19 @@ async def test_update_homepage_flattened_error_async(): with pytest.raises(ValueError): await client.update_homepage( gsma_homepage.UpdateHomepageRequest(), - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + homepage=gsma_homepage.Homepage(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - homepage.ClaimHomepageRequest, - dict, -]) -def test_claim_homepage(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + homepage.ClaimHomepageRequest, + dict, + ], +) +def test_claim_homepage(request_type, transport: str = "grpc"): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1420,13 +1817,11 @@ def test_claim_homepage(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = homepage.Homepage( - name='name_value', - uri='uri_value', + name="name_value", + uri="uri_value", claimed=True, ) response = client.claim_homepage(request) @@ -1439,8 +1834,8 @@ def test_claim_homepage(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -1449,28 +1844,29 @@ def test_claim_homepage_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = HomepageServiceClient( 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 = homepage.ClaimHomepageRequest( - 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.claim_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.claim_homepage(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == homepage.ClaimHomepageRequest( - name='name_value', + name="name_value", ) + def test_claim_homepage_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1489,7 +1885,9 @@ def test_claim_homepage_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc request = {} client.claim_homepage(request) @@ -1503,8 +1901,11 @@ def test_claim_homepage_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_claim_homepage_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_claim_homepage_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: @@ -1518,12 +1919,17 @@ async def test_claim_homepage_async_use_cached_wrapped_rpc(transport: str = "grp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.claim_homepage in client._client._transport._wrapped_methods + assert ( + client._client._transport.claim_homepage + 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.claim_homepage] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.claim_homepage + ] = mock_rpc request = {} await client.claim_homepage(request) @@ -1537,8 +1943,11 @@ async def test_claim_homepage_async_use_cached_wrapped_rpc(transport: str = "grp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_claim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.ClaimHomepageRequest): +async def test_claim_homepage_async( + transport: str = "grpc_asyncio", request_type=homepage.ClaimHomepageRequest +): client = HomepageServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1549,15 +1958,15 @@ async def test_claim_homepage_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) response = await client.claim_homepage(request) # Establish that the underlying gRPC stub method was called. @@ -1568,8 +1977,8 @@ async def test_claim_homepage_async(transport: str = 'grpc_asyncio', request_typ # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -1577,6 +1986,7 @@ async def test_claim_homepage_async(transport: str = 'grpc_asyncio', request_typ async def test_claim_homepage_async_from_dict(): await test_claim_homepage_async(request_type=dict) + def test_claim_homepage_field_headers(): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1586,12 +1996,10 @@ def test_claim_homepage_field_headers(): # a field header. Set these to a non-empty value. request = homepage.ClaimHomepageRequest() - 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.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: call.return_value = homepage.Homepage() client.claim_homepage(request) @@ -1603,9 +2011,9 @@ def test_claim_homepage_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 @@ -1618,12 +2026,10 @@ async def test_claim_homepage_field_headers_async(): # a field header. Set these to a non-empty value. request = homepage.ClaimHomepageRequest() - 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.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) await client.claim_homepage(request) @@ -1635,16 +2041,19 @@ async def test_claim_homepage_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"] -@pytest.mark.parametrize("request_type", [ - homepage.UnclaimHomepageRequest, - dict, -]) -def test_unclaim_homepage(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + homepage.UnclaimHomepageRequest, + dict, + ], +) +def test_unclaim_homepage(request_type, transport: str = "grpc"): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1655,13 +2064,11 @@ def test_unclaim_homepage(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = homepage.Homepage( - name='name_value', - uri='uri_value', + name="name_value", + uri="uri_value", claimed=True, ) response = client.unclaim_homepage(request) @@ -1674,8 +2081,8 @@ def test_unclaim_homepage(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -1684,28 +2091,29 @@ def test_unclaim_homepage_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = HomepageServiceClient( 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 = homepage.UnclaimHomepageRequest( - 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.unclaim_homepage), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.unclaim_homepage(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == homepage.UnclaimHomepageRequest( - name='name_value', + name="name_value", ) + def test_unclaim_homepage_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1724,8 +2132,12 @@ def test_unclaim_homepage_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.unclaim_homepage + ] = mock_rpc request = {} client.unclaim_homepage(request) @@ -1738,8 +2150,11 @@ def test_unclaim_homepage_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_unclaim_homepage_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_unclaim_homepage_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: @@ -1753,12 +2168,17 @@ async def test_unclaim_homepage_async_use_cached_wrapped_rpc(transport: str = "g wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.unclaim_homepage in client._client._transport._wrapped_methods + assert ( + client._client._transport.unclaim_homepage + 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.unclaim_homepage] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.unclaim_homepage + ] = mock_rpc request = {} await client.unclaim_homepage(request) @@ -1772,8 +2192,11 @@ async def test_unclaim_homepage_async_use_cached_wrapped_rpc(transport: str = "g assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_type=homepage.UnclaimHomepageRequest): +async def test_unclaim_homepage_async( + transport: str = "grpc_asyncio", request_type=homepage.UnclaimHomepageRequest +): client = HomepageServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1784,15 +2207,15 @@ async def test_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_t request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) response = await client.unclaim_homepage(request) # Establish that the underlying gRPC stub method was called. @@ -1803,8 +2226,8 @@ async def test_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_t # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -1812,6 +2235,7 @@ async def test_unclaim_homepage_async(transport: str = 'grpc_asyncio', request_t async def test_unclaim_homepage_async_from_dict(): await test_unclaim_homepage_async(request_type=dict) + def test_unclaim_homepage_field_headers(): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1821,12 +2245,10 @@ def test_unclaim_homepage_field_headers(): # a field header. Set these to a non-empty value. request = homepage.UnclaimHomepageRequest() - 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.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: call.return_value = homepage.Homepage() client.unclaim_homepage(request) @@ -1838,9 +2260,9 @@ def test_unclaim_homepage_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 @@ -1853,12 +2275,10 @@ async def test_unclaim_homepage_field_headers_async(): # a field header. Set these to a non-empty value. request = homepage.UnclaimHomepageRequest() - 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.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage()) await client.unclaim_homepage(request) @@ -1870,9 +2290,9 @@ async def test_unclaim_homepage_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_homepage_rest_use_cached_wrapped_rpc(): @@ -1893,7 +2313,9 @@ def test_get_homepage_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_homepage] = mock_rpc request = {} @@ -1916,48 +2338,51 @@ def test_get_homepage_rest_required_fields(request_type=homepage.GetHomepageRequ request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_homepage._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_homepage._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 = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = homepage.Homepage() # Mock the http request 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 @@ -1968,24 +2393,24 @@ def test_get_homepage_rest_required_fields(request_type=homepage.GetHomepageRequ return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_homepage(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_homepage_rest_flattened(): @@ -1995,16 +2420,16 @@ def test_get_homepage_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 = homepage.Homepage() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/homepage'} + sample_request = {"name": "accounts/sample1/homepage"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2014,7 +2439,7 @@ def test_get_homepage_rest_flattened(): # Convert return value to protobuf type return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2024,10 +2449,13 @@ def test_get_homepage_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/homepage}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/homepage}" % client.transport._host, + args[1], + ) -def test_get_homepage_rest_flattened_error(transport: str = 'rest'): +def test_get_homepage_rest_flattened_error(transport: str = "rest"): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2038,7 +2466,7 @@ def test_get_homepage_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_homepage( homepage.GetHomepageRequest(), - name='name_value', + name="name_value", ) @@ -2060,7 +2488,9 @@ def test_update_homepage_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_homepage] = mock_rpc request = {} @@ -2076,54 +2506,59 @@ def test_update_homepage_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_homepage_rest_required_fields(request_type=gsma_homepage.UpdateHomepageRequest): +def test_update_homepage_rest_required_fields( + request_type=gsma_homepage.UpdateHomepageRequest, +): transport_class = transports.HomepageServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_homepage._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_homepage._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gsma_homepage.Homepage() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2133,24 +2568,24 @@ def test_update_homepage_rest_required_fields(request_type=gsma_homepage.UpdateH return_value = gsma_homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_homepage(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("homepage", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("homepage",))) def test_update_homepage_rest_flattened(): @@ -2160,17 +2595,17 @@ def test_update_homepage_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 = gsma_homepage.Homepage() # get arguments that satisfy an http rule for this method - sample_request = {'homepage': {'name': 'accounts/sample1/homepage'}} + sample_request = {"homepage": {"name": "accounts/sample1/homepage"}} # get truthy value for each flattened field mock_args = dict( - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + homepage=gsma_homepage.Homepage(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -2180,7 +2615,7 @@ def test_update_homepage_rest_flattened(): # Convert return value to protobuf type return_value = gsma_homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2190,10 +2625,14 @@ def test_update_homepage_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{homepage.name=accounts/*/homepage}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{homepage.name=accounts/*/homepage}" + % client.transport._host, + args[1], + ) -def test_update_homepage_rest_flattened_error(transport: str = 'rest'): +def test_update_homepage_rest_flattened_error(transport: str = "rest"): client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2204,8 +2643,8 @@ def test_update_homepage_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_homepage( gsma_homepage.UpdateHomepageRequest(), - homepage=gsma_homepage.Homepage(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + homepage=gsma_homepage.Homepage(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2227,7 +2666,9 @@ def test_claim_homepage_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.claim_homepage] = mock_rpc request = {} @@ -2243,57 +2684,62 @@ def test_claim_homepage_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_claim_homepage_rest_required_fields(request_type=homepage.ClaimHomepageRequest): +def test_claim_homepage_rest_required_fields( + request_type=homepage.ClaimHomepageRequest, +): transport_class = transports.HomepageServiceRestTransport 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()).claim_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).claim_homepage._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()).claim_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).claim_homepage._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 = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = homepage.Homepage() # Mock the http request 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() @@ -2303,24 +2749,24 @@ def test_claim_homepage_rest_required_fields(request_type=homepage.ClaimHomepage return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.claim_homepage(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_claim_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.claim_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_unclaim_homepage_rest_use_cached_wrapped_rpc(): @@ -2341,8 +2787,12 @@ def test_unclaim_homepage_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.unclaim_homepage] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.unclaim_homepage + ] = mock_rpc request = {} client.unclaim_homepage(request) @@ -2357,57 +2807,62 @@ def test_unclaim_homepage_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_unclaim_homepage_rest_required_fields(request_type=homepage.UnclaimHomepageRequest): +def test_unclaim_homepage_rest_required_fields( + request_type=homepage.UnclaimHomepageRequest, +): transport_class = transports.HomepageServiceRestTransport 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()).unclaim_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).unclaim_homepage._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()).unclaim_homepage._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).unclaim_homepage._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 = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = homepage.Homepage() # Mock the http request 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() @@ -2417,24 +2872,24 @@ def test_unclaim_homepage_rest_required_fields(request_type=homepage.UnclaimHome return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.unclaim_homepage(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_unclaim_homepage_rest_unset_required_fields(): - transport = transports.HomepageServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.HomepageServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.unclaim_homepage._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_credentials_transport_error(): @@ -2475,8 +2930,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = HomepageServiceClient( - 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. @@ -2498,6 +2952,7 @@ def test_transport_instance(): client = HomepageServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.HomepageServiceGrpcTransport( @@ -2512,18 +2967,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.HomepageServiceGrpcTransport, - transports.HomepageServiceGrpcAsyncIOTransport, - transports.HomepageServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + transports.HomepageServiceRestTransport, + ], +) 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 = HomepageServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2533,8 +2993,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2548,9 +3007,7 @@ def test_get_homepage_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: call.return_value = homepage.Homepage() client.get_homepage(request=None) @@ -2571,9 +3028,7 @@ def test_update_homepage_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: call.return_value = gsma_homepage.Homepage() client.update_homepage(request=None) @@ -2594,9 +3049,7 @@ def test_claim_homepage_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: call.return_value = homepage.Homepage() client.claim_homepage(request=None) @@ -2617,9 +3070,7 @@ def test_unclaim_homepage_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: call.return_value = homepage.Homepage() client.unclaim_homepage(request=None) @@ -2640,8 +3091,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = HomepageServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2656,15 +3106,15 @@ async def test_get_homepage_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) await client.get_homepage(request=None) # Establish that the underlying stub method was called. @@ -2685,15 +3135,15 @@ async def test_update_homepage_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) await client.update_homepage(request=None) # Establish that the underlying stub method was called. @@ -2714,15 +3164,15 @@ async def test_claim_homepage_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) await client.claim_homepage(request=None) # Establish that the underlying stub method was called. @@ -2743,15 +3193,15 @@ async def test_unclaim_homepage_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + homepage.Homepage( + name="name_value", + uri="uri_value", + claimed=True, + ) + ) await client.unclaim_homepage(request=None) # Establish that the underlying stub method was called. @@ -2771,18 +3221,19 @@ def test_transport_kind_rest(): def test_get_homepage_rest_bad_request(request_type=homepage.GetHomepageRequest): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} + request_init = {"name": "accounts/sample1/homepage"} 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() @@ -2791,27 +3242,29 @@ def test_get_homepage_rest_bad_request(request_type=homepage.GetHomepageRequest) client.get_homepage(request) -@pytest.mark.parametrize("request_type", [ - homepage.GetHomepageRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + homepage.GetHomepageRequest, + dict, + ], +) def test_get_homepage_rest_call_success(request_type): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} + request_init = {"name": "accounts/sample1/homepage"} request = request_type(**request_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 = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, + name="name_value", + uri="uri_value", + claimed=True, ) # Wrap the value into a proper Response obj @@ -2821,15 +3274,15 @@ def test_get_homepage_rest_call_success(request_type): # Convert return value to protobuf type return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_homepage(request) # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -2837,15 +3290,23 @@ def test_get_homepage_rest_call_success(request_type): def test_get_homepage_rest_interceptors(null_interceptor): transport = transports.HomepageServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.HomepageServiceRestInterceptor(), + ) client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_get_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_get_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_get_homepage") 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.HomepageServiceRestInterceptor, "post_get_homepage" + ) as post, mock.patch.object( + transports.HomepageServiceRestInterceptor, "post_get_homepage_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.HomepageServiceRestInterceptor, "pre_get_homepage" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -2864,7 +3325,7 @@ def test_get_homepage_rest_interceptors(null_interceptor): req.return_value.content = return_value request = homepage.GetHomepageRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2872,27 +3333,36 @@ def test_get_homepage_rest_interceptors(null_interceptor): post.return_value = homepage.Homepage() post_with_metadata.return_value = homepage.Homepage(), metadata - client.get_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_homepage( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_homepage_rest_bad_request(request_type=gsma_homepage.UpdateHomepageRequest): +def test_update_homepage_rest_bad_request( + request_type=gsma_homepage.UpdateHomepageRequest, +): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} + request_init = {"homepage": {"name": "accounts/sample1/homepage"}} 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() @@ -2901,19 +3371,25 @@ def test_update_homepage_rest_bad_request(request_type=gsma_homepage.UpdateHomep client.update_homepage(request) -@pytest.mark.parametrize("request_type", [ - gsma_homepage.UpdateHomepageRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gsma_homepage.UpdateHomepageRequest, + dict, + ], +) def test_update_homepage_rest_call_success(request_type): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'homepage': {'name': 'accounts/sample1/homepage'}} - request_init["homepage"] = {'name': 'accounts/sample1/homepage', 'uri': 'uri_value', 'claimed': True} + request_init = {"homepage": {"name": "accounts/sample1/homepage"}} + request_init["homepage"] = { + "name": "accounts/sample1/homepage", + "uri": "uri_value", + "claimed": True, + } # 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 @@ -2933,7 +3409,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 @@ -2947,7 +3423,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["homepage"].items(): # pragma: NO COVER + for field, value in request_init["homepage"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2962,12 +3438,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") @@ -2980,12 +3460,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 = gsma_homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, + name="name_value", + uri="uri_value", + claimed=True, ) # Wrap the value into a proper Response obj @@ -2995,15 +3475,15 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gsma_homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_homepage(request) # Establish that the response is the type that we expect. assert isinstance(response, gsma_homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -3011,19 +3491,29 @@ def get_message_fields(field): def test_update_homepage_rest_interceptors(null_interceptor): transport = transports.HomepageServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.HomepageServiceRestInterceptor(), + ) client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_update_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_update_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_update_homepage") 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.HomepageServiceRestInterceptor, "post_update_homepage" + ) as post, mock.patch.object( + transports.HomepageServiceRestInterceptor, "post_update_homepage_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.HomepageServiceRestInterceptor, "pre_update_homepage" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gsma_homepage.UpdateHomepageRequest.pb(gsma_homepage.UpdateHomepageRequest()) + pb_message = gsma_homepage.UpdateHomepageRequest.pb( + gsma_homepage.UpdateHomepageRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3038,7 +3528,7 @@ def test_update_homepage_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gsma_homepage.UpdateHomepageRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3046,7 +3536,13 @@ def test_update_homepage_rest_interceptors(null_interceptor): post.return_value = gsma_homepage.Homepage() post_with_metadata.return_value = gsma_homepage.Homepage(), metadata - client.update_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_homepage( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3055,18 +3551,19 @@ def test_update_homepage_rest_interceptors(null_interceptor): def test_claim_homepage_rest_bad_request(request_type=homepage.ClaimHomepageRequest): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} + request_init = {"name": "accounts/sample1/homepage"} 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() @@ -3075,27 +3572,29 @@ def test_claim_homepage_rest_bad_request(request_type=homepage.ClaimHomepageRequ client.claim_homepage(request) -@pytest.mark.parametrize("request_type", [ - homepage.ClaimHomepageRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + homepage.ClaimHomepageRequest, + dict, + ], +) def test_claim_homepage_rest_call_success(request_type): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} + request_init = {"name": "accounts/sample1/homepage"} request = request_type(**request_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 = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, + name="name_value", + uri="uri_value", + claimed=True, ) # Wrap the value into a proper Response obj @@ -3105,15 +3604,15 @@ def test_claim_homepage_rest_call_success(request_type): # Convert return value to protobuf type return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.claim_homepage(request) # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -3121,15 +3620,23 @@ def test_claim_homepage_rest_call_success(request_type): def test_claim_homepage_rest_interceptors(null_interceptor): transport = transports.HomepageServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.HomepageServiceRestInterceptor(), + ) client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_claim_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_claim_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_claim_homepage") 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.HomepageServiceRestInterceptor, "post_claim_homepage" + ) as post, mock.patch.object( + transports.HomepageServiceRestInterceptor, "post_claim_homepage_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.HomepageServiceRestInterceptor, "pre_claim_homepage" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3148,7 +3655,7 @@ def test_claim_homepage_rest_interceptors(null_interceptor): req.return_value.content = return_value request = homepage.ClaimHomepageRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3156,27 +3663,36 @@ def test_claim_homepage_rest_interceptors(null_interceptor): post.return_value = homepage.Homepage() post_with_metadata.return_value = homepage.Homepage(), metadata - client.claim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.claim_homepage( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_unclaim_homepage_rest_bad_request(request_type=homepage.UnclaimHomepageRequest): +def test_unclaim_homepage_rest_bad_request( + request_type=homepage.UnclaimHomepageRequest, +): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} + request_init = {"name": "accounts/sample1/homepage"} 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() @@ -3185,27 +3701,29 @@ def test_unclaim_homepage_rest_bad_request(request_type=homepage.UnclaimHomepage client.unclaim_homepage(request) -@pytest.mark.parametrize("request_type", [ - homepage.UnclaimHomepageRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + homepage.UnclaimHomepageRequest, + dict, + ], +) def test_unclaim_homepage_rest_call_success(request_type): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/homepage'} + request_init = {"name": "accounts/sample1/homepage"} request = request_type(**request_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 = homepage.Homepage( - name='name_value', - uri='uri_value', - claimed=True, + name="name_value", + uri="uri_value", + claimed=True, ) # Wrap the value into a proper Response obj @@ -3215,15 +3733,15 @@ def test_unclaim_homepage_rest_call_success(request_type): # Convert return value to protobuf type return_value = homepage.Homepage.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.unclaim_homepage(request) # Establish that the response is the type that we expect. assert isinstance(response, homepage.Homepage) - assert response.name == 'name_value' - assert response.uri == 'uri_value' + assert response.name == "name_value" + assert response.uri == "uri_value" assert response.claimed is True @@ -3231,19 +3749,29 @@ def test_unclaim_homepage_rest_call_success(request_type): def test_unclaim_homepage_rest_interceptors(null_interceptor): transport = transports.HomepageServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.HomepageServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.HomepageServiceRestInterceptor(), + ) client = HomepageServiceClient(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.HomepageServiceRestInterceptor, "post_unclaim_homepage") as post, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "post_unclaim_homepage_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.HomepageServiceRestInterceptor, "pre_unclaim_homepage") 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.HomepageServiceRestInterceptor, "post_unclaim_homepage" + ) as post, mock.patch.object( + transports.HomepageServiceRestInterceptor, "post_unclaim_homepage_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.HomepageServiceRestInterceptor, "pre_unclaim_homepage" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = homepage.UnclaimHomepageRequest.pb(homepage.UnclaimHomepageRequest()) + pb_message = homepage.UnclaimHomepageRequest.pb( + homepage.UnclaimHomepageRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3258,7 +3786,7 @@ def test_unclaim_homepage_rest_interceptors(null_interceptor): req.return_value.content = return_value request = homepage.UnclaimHomepageRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3266,16 +3794,22 @@ def test_unclaim_homepage_rest_interceptors(null_interceptor): post.return_value = homepage.Homepage() post_with_metadata.return_value = homepage.Homepage(), metadata - client.unclaim_homepage(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.unclaim_homepage( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = HomepageServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -3289,9 +3823,7 @@ def test_get_homepage_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.get_homepage), "__call__") as call: client.get_homepage(request=None) # Establish that the underlying stub method was called. @@ -3311,9 +3843,7 @@ def test_update_homepage_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.update_homepage), "__call__") as call: client.update_homepage(request=None) # Establish that the underlying stub method was called. @@ -3333,9 +3863,7 @@ def test_claim_homepage_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.claim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.claim_homepage), "__call__") as call: client.claim_homepage(request=None) # Establish that the underlying stub method was called. @@ -3355,9 +3883,7 @@ def test_unclaim_homepage_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unclaim_homepage), - '__call__') as call: + with mock.patch.object(type(client.transport.unclaim_homepage), "__call__") as call: client.unclaim_homepage(request=None) # Establish that the underlying stub method was called. @@ -3378,18 +3904,21 @@ def test_transport_grpc_default(): transports.HomepageServiceGrpcTransport, ) + def test_homepage_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.HomepageServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_homepage_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.HomepageServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3398,10 +3927,10 @@ def test_homepage_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_homepage', - 'update_homepage', - 'claim_homepage', - 'unclaim_homepage', + "get_homepage", + "update_homepage", + "claim_homepage", + "unclaim_homepage", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3412,7 +3941,7 @@ def test_homepage_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3421,25 +3950,30 @@ def test_homepage_service_base_transport(): def test_homepage_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_accounts_v1.services.homepage_service.transports.HomepageServiceTransport._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_accounts_v1.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.HomepageServiceTransport( 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_homepage_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_accounts_v1.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.homepage_service.transports.HomepageServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.HomepageServiceTransport() @@ -3448,14 +3982,12 @@ def test_homepage_service_base_transport_with_adc(): def test_homepage_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) HomepageServiceClient() 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, ) @@ -3470,12 +4002,12 @@ def test_homepage_service_auth_adc(): def test_homepage_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", ) @@ -3489,48 +4021,45 @@ def test_homepage_service_transport_auth_adc(transport_class): ], ) def test_homepage_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.HomepageServiceGrpcTransport, grpc_helpers), - (transports.HomepageServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.HomepageServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_homepage_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, @@ -3541,10 +4070,14 @@ def test_homepage_service_transport_create_channel(transport_class, grpc_helpers ) -@pytest.mark.parametrize("transport_class", [transports.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) -def test_homepage_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + ], +) +def test_homepage_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -3553,7 +4086,7 @@ def test_homepage_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", @@ -3574,61 +4107,77 @@ def test_homepage_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_homepage_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.HomepageServiceRestTransport ( - 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.HomepageServiceRestTransport( + 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_homepage_service_host_no_port(transport_name): client = HomepageServiceClient( 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_homepage_service_host_with_port(transport_name): client = HomepageServiceClient( 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_homepage_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3652,8 +4201,10 @@ def test_homepage_service_client_transport_session_collision(transport_name): session1 = client1.transport.unclaim_homepage._session session2 = client2.transport.unclaim_homepage._session assert session1 != session2 + + def test_homepage_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.HomepageServiceGrpcTransport( @@ -3666,7 +4217,7 @@ def test_homepage_service_grpc_transport_channel(): def test_homepage_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.HomepageServiceGrpcAsyncIOTransport( @@ -3680,12 +4231,22 @@ def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + ], +) def test_homepage_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 @@ -3694,7 +4255,7 @@ def test_homepage_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", @@ -3724,17 +4285,23 @@ def test_homepage_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.HomepageServiceGrpcTransport, transports.HomepageServiceGrpcAsyncIOTransport]) -def test_homepage_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.HomepageServiceGrpcTransport, + transports.HomepageServiceGrpcAsyncIOTransport, + ], +) +def test_homepage_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() @@ -3764,7 +4331,9 @@ def test_homepage_service_transport_channel_mtls_with_adc( def test_homepage_path(): account = "squid" - expected = "accounts/{account}/homepage".format(account=account, ) + expected = "accounts/{account}/homepage".format( + account=account, + ) actual = HomepageServiceClient.homepage_path(account) assert expected == actual @@ -3779,9 +4348,12 @@ def test_parse_homepage_path(): actual = HomepageServiceClient.parse_homepage_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = HomepageServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -3796,9 +4368,12 @@ def test_parse_common_billing_account_path(): actual = HomepageServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = HomepageServiceClient.common_folder_path(folder) assert expected == actual @@ -3813,9 +4388,12 @@ def test_parse_common_folder_path(): actual = HomepageServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = HomepageServiceClient.common_organization_path(organization) assert expected == actual @@ -3830,9 +4408,12 @@ def test_parse_common_organization_path(): actual = HomepageServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = HomepageServiceClient.common_project_path(project) assert expected == actual @@ -3847,10 +4428,14 @@ def test_parse_common_project_path(): actual = HomepageServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = HomepageServiceClient.common_location_path(project, location) assert expected == actual @@ -3870,14 +4455,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.HomepageServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.HomepageServiceTransport, "_prep_wrapped_messages" + ) as prep: client = HomepageServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.HomepageServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.HomepageServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = HomepageServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3888,10 +4477,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = HomepageServiceClient( - 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() @@ -3900,10 +4490,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = HomepageServiceAsyncClient( - 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() @@ -3911,10 +4502,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = HomepageServiceClient( - 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() @@ -3922,13 +4514,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = HomepageServiceClient( - 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: @@ -3937,10 +4528,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (HomepageServiceClient, transports.HomepageServiceGrpcTransport), - (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (HomepageServiceClient, transports.HomepageServiceGrpcTransport), + (HomepageServiceAsyncClient, transports.HomepageServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3955,7 +4550,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py index fb6cf03df6a2..b9acd384b6af 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_lfp_providers_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,46 +22,44 @@ 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 empty_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.lfp_providers_service import LfpProvidersServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.lfp_providers_service import LfpProvidersServiceClient -from google.shopping.merchant_accounts_v1.services.lfp_providers_service import pagers -from google.shopping.merchant_accounts_v1.services.lfp_providers_service import transports -from google.shopping.merchant_accounts_v1.types import lfpproviders -import google.auth - +from google.shopping.merchant_accounts_v1.services.lfp_providers_service import ( + LfpProvidersServiceAsyncClient, + LfpProvidersServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import lfpproviders CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +74,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(): @@ -85,17 +86,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(): @@ -106,101 +117,243 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert LfpProvidersServiceClient._get_default_mtls_endpoint(None) is None - assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert LfpProvidersServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + LfpProvidersServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + LfpProvidersServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LfpProvidersServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LfpProvidersServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + assert LfpProvidersServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert LfpProvidersServiceClient._read_environment_variables() == (True, "auto", None) + assert LfpProvidersServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + assert LfpProvidersServiceClient._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: LfpProvidersServiceClient._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 LfpProvidersServiceClient._read_environment_variables() == (False, "never", None) + assert LfpProvidersServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "always", None) + assert LfpProvidersServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert LfpProvidersServiceClient._read_environment_variables() == (False, "auto", None) + assert LfpProvidersServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: LfpProvidersServiceClient._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 LfpProvidersServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, False) is None - assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + LfpProvidersServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + LfpProvidersServiceClient._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 ( + LfpProvidersServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert LfpProvidersServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) +@mock.patch.object( + LfpProvidersServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceClient), +) +@mock.patch.object( + LfpProvidersServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert LfpProvidersServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpProvidersServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT - assert LfpProvidersServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert LfpProvidersServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + LfpProvidersServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + LfpProvidersServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + LfpProvidersServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + LfpProvidersServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + LfpProvidersServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == LfpProvidersServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + LfpProvidersServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + LfpProvidersServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - LfpProvidersServiceClient._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." + LfpProvidersServiceClient._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 LfpProvidersServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert LfpProvidersServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert LfpProvidersServiceClient._get_universe_domain(None, None) == LfpProvidersServiceClient._DEFAULT_UNIVERSE + assert ( + LfpProvidersServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + LfpProvidersServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + LfpProvidersServiceClient._get_universe_domain(None, None) + == LfpProvidersServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: LfpProvidersServiceClient._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) @@ -216,7 +369,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") @@ -229,14 +383,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", [ - (LfpProvidersServiceClient, "grpc"), - (LfpProvidersServiceAsyncClient, "grpc_asyncio"), - (LfpProvidersServiceClient, "rest"), -]) -def test_lfp_providers_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (LfpProvidersServiceClient, "grpc"), + (LfpProvidersServiceAsyncClient, "grpc_asyncio"), + (LfpProvidersServiceClient, "rest"), + ], +) +def test_lfp_providers_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) @@ -244,52 +406,70 @@ def test_lfp_providers_service_client_from_service_account_info(client_class, tr 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.LfpProvidersServiceGrpcTransport, "grpc"), - (transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.LfpProvidersServiceRestTransport, "rest"), -]) -def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, "grpc"), + (transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.LfpProvidersServiceRestTransport, "rest"), + ], +) +def test_lfp_providers_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", [ - (LfpProvidersServiceClient, "grpc"), - (LfpProvidersServiceAsyncClient, "grpc_asyncio"), - (LfpProvidersServiceClient, "rest"), -]) -def test_lfp_providers_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (LfpProvidersServiceClient, "grpc"), + (LfpProvidersServiceAsyncClient, "grpc_asyncio"), + (LfpProvidersServiceClient, "rest"), + ], +) +def test_lfp_providers_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" ) @@ -305,30 +485,53 @@ def test_lfp_providers_service_client_get_transport_class(): assert transport == transports.LfpProvidersServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), -]) -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) -def test_lfp_providers_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceGrpcTransport, + "grpc", + ), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + LfpProvidersServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceClient), +) +@mock.patch.object( + LfpProvidersServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceAsyncClient), +) +def test_lfp_providers_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(LfpProvidersServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(LfpProvidersServiceClient, "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(LfpProvidersServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(LfpProvidersServiceClient, "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( @@ -346,13 +549,15 @@ def test_lfp_providers_service_client_client_options(client_class, transport_cla # 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, @@ -364,7 +569,7 @@ def test_lfp_providers_service_client_client_options(client_class, transport_cla # 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( @@ -384,23 +589,33 @@ def test_lfp_providers_service_client_client_options(client_class, transport_cla 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", @@ -409,48 +624,102 @@ def test_lfp_providers_service_client_client_options(client_class, transport_cla 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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "true"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", "false"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "true"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceGrpcTransport, + "grpc", + "true", + ), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceGrpcTransport, + "grpc", + "false", + ), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceRestTransport, + "rest", + "true", + ), + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + LfpProvidersServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceClient), +) +@mock.patch.object( + LfpProvidersServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_lfp_providers_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_lfp_providers_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 @@ -469,12 +738,22 @@ def test_lfp_providers_service_client_mtls_env_auto(client_class, transport_clas # 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 @@ -495,15 +774,22 @@ def test_lfp_providers_service_client_mtls_env_auto(client_class, transport_clas ) # 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, @@ -513,19 +799,31 @@ def test_lfp_providers_service_client_mtls_env_auto(client_class, transport_clas ) -@pytest.mark.parametrize("client_class", [ - LfpProvidersServiceClient, LfpProvidersServiceAsyncClient -]) -@mock.patch.object(LfpProvidersServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(LfpProvidersServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [LfpProvidersServiceClient, LfpProvidersServiceAsyncClient] +) +@mock.patch.object( + LfpProvidersServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LfpProvidersServiceClient), +) +@mock.patch.object( + LfpProvidersServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LfpProvidersServiceAsyncClient), +) def test_lfp_providers_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 @@ -533,8 +831,12 @@ def test_lfp_providers_service_client_get_mtls_endpoint_and_cert_source(client_c 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 @@ -552,16 +854,28 @@ def test_lfp_providers_service_client_get_mtls_endpoint_and_cert_source(client_c # 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 @@ -571,34 +885,62 @@ def test_lfp_providers_service_client_get_mtls_endpoint_and_cert_source(client_c 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", [ - LfpProvidersServiceClient, LfpProvidersServiceAsyncClient -]) -@mock.patch.object(LfpProvidersServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceClient)) -@mock.patch.object(LfpProvidersServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(LfpProvidersServiceAsyncClient)) + +@pytest.mark.parametrize( + "client_class", [LfpProvidersServiceClient, LfpProvidersServiceAsyncClient] +) +@mock.patch.object( + LfpProvidersServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceClient), +) +@mock.patch.object( + LfpProvidersServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(LfpProvidersServiceAsyncClient), +) def test_lfp_providers_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = LfpProvidersServiceClient._DEFAULT_UNIVERSE - default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = LfpProvidersServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = LfpProvidersServiceClient._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", @@ -621,11 +963,19 @@ def test_lfp_providers_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. @@ -633,27 +983,48 @@ def test_lfp_providers_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", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc"), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest"), -]) -def test_lfp_providers_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceGrpcTransport, + "grpc", + ), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceRestTransport, + "rest", + ), + ], +) +def test_lfp_providers_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, @@ -662,24 +1033,45 @@ def test_lfp_providers_service_client_client_options_scopes(client_class, transp api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (LfpProvidersServiceClient, transports.LfpProvidersServiceRestTransport, "rest", None), -]) -def test_lfp_providers_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", + [ + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceRestTransport, + "rest", + None, + ), + ], +) +def test_lfp_providers_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, @@ -688,11 +1080,14 @@ def test_lfp_providers_service_client_client_options_credentials_file(client_cla api_audience=None, ) + def test_lfp_providers_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = LfpProvidersServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1102,38 @@ def test_lfp_providers_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport, "grpc", grpc_helpers), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_lfp_providers_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", + [ + ( + LfpProvidersServiceClient, + transports.LfpProvidersServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_lfp_providers_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, @@ -750,9 +1160,7 @@ def test_lfp_providers_service_client_create_channel_credentials_file(client_cla 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, @@ -763,11 +1171,14 @@ def test_lfp_providers_service_client_create_channel_credentials_file(client_cla ) -@pytest.mark.parametrize("request_type", [ - lfpproviders.FindLfpProvidersRequest, - dict, -]) -def test_find_lfp_providers(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + lfpproviders.FindLfpProvidersRequest, + dict, + ], +) +def test_find_lfp_providers(request_type, transport: str = "grpc"): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,11 +1190,11 @@ def test_find_lfp_providers(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.find_lfp_providers(request) @@ -795,7 +1206,7 @@ def test_find_lfp_providers(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.FindLfpProvidersPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_find_lfp_providers_non_empty_request_with_auto_populated_field(): @@ -803,30 +1214,33 @@ def test_find_lfp_providers_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = LfpProvidersServiceClient( 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 = lfpproviders.FindLfpProvidersRequest( - 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.find_lfp_providers), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.find_lfp_providers), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.find_lfp_providers(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == lfpproviders.FindLfpProvidersRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_find_lfp_providers_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -841,12 +1255,18 @@ def test_find_lfp_providers_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.find_lfp_providers in client._transport._wrapped_methods + assert ( + client._transport.find_lfp_providers in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.find_lfp_providers + ] = mock_rpc request = {} client.find_lfp_providers(request) @@ -859,8 +1279,11 @@ def test_find_lfp_providers_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_find_lfp_providers_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_find_lfp_providers_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: @@ -874,12 +1297,17 @@ async def test_find_lfp_providers_async_use_cached_wrapped_rpc(transport: str = wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.find_lfp_providers in client._client._transport._wrapped_methods + assert ( + client._client._transport.find_lfp_providers + 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.find_lfp_providers] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.find_lfp_providers + ] = mock_rpc request = {} await client.find_lfp_providers(request) @@ -893,8 +1321,11 @@ async def test_find_lfp_providers_async_use_cached_wrapped_rpc(transport: str = assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_find_lfp_providers_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.FindLfpProvidersRequest): +async def test_find_lfp_providers_async( + transport: str = "grpc_asyncio", request_type=lfpproviders.FindLfpProvidersRequest +): client = LfpProvidersServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -906,12 +1337,14 @@ async def test_find_lfp_providers_async(transport: str = 'grpc_asyncio', request # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.FindLfpProvidersResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.find_lfp_providers(request) # Establish that the underlying gRPC stub method was called. @@ -922,13 +1355,14 @@ async def test_find_lfp_providers_async(transport: str = 'grpc_asyncio', request # Establish that the response is the type that we expect. assert isinstance(response, pagers.FindLfpProvidersAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio async def test_find_lfp_providers_async_from_dict(): await test_find_lfp_providers_async(request_type=dict) + def test_find_lfp_providers_field_headers(): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -938,12 +1372,12 @@ def test_find_lfp_providers_field_headers(): # a field header. Set these to a non-empty value. request = lfpproviders.FindLfpProvidersRequest() - 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.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: call.return_value = lfpproviders.FindLfpProvidersResponse() client.find_lfp_providers(request) @@ -955,9 +1389,9 @@ def test_find_lfp_providers_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 @@ -970,13 +1404,15 @@ async def test_find_lfp_providers_field_headers_async(): # a field header. Set these to a non-empty value. request = lfpproviders.FindLfpProvidersRequest() - 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.find_lfp_providers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) + type(client.transport.find_lfp_providers), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.FindLfpProvidersResponse() + ) await client.find_lfp_providers(request) # Establish that the underlying gRPC stub method was called. @@ -987,9 +1423,9 @@ async def test_find_lfp_providers_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_find_lfp_providers_flattened(): @@ -999,14 +1435,14 @@ def test_find_lfp_providers_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = lfpproviders.FindLfpProvidersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.find_lfp_providers( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1014,7 +1450,7 @@ def test_find_lfp_providers_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 @@ -1028,9 +1464,10 @@ def test_find_lfp_providers_flattened_error(): with pytest.raises(ValueError): client.find_lfp_providers( lfpproviders.FindLfpProvidersRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_find_lfp_providers_flattened_async(): client = LfpProvidersServiceAsyncClient( @@ -1039,16 +1476,18 @@ async def test_find_lfp_providers_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = lfpproviders.FindLfpProvidersResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.FindLfpProvidersResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.find_lfp_providers( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1056,9 +1495,10 @@ async def test_find_lfp_providers_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_find_lfp_providers_flattened_error_async(): client = LfpProvidersServiceAsyncClient( @@ -1070,7 +1510,7 @@ async def test_find_lfp_providers_flattened_error_async(): with pytest.raises(ValueError): await client.find_lfp_providers( lfpproviders.FindLfpProvidersRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1082,8 +1522,8 @@ def test_find_lfp_providers_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( lfpproviders.FindLfpProvidersResponse( @@ -1092,17 +1532,17 @@ def test_find_lfp_providers_pager(transport_name: str = "grpc"): lfpproviders.LfpProvider(), lfpproviders.LfpProvider(), ], - next_page_token='abc', + next_page_token="abc", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[], - next_page_token='def', + next_page_token="def", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ lfpproviders.LfpProvider(), ], - next_page_token='ghi', + next_page_token="ghi", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ @@ -1117,9 +1557,7 @@ def test_find_lfp_providers_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.find_lfp_providers(request={}, retry=retry, timeout=timeout) @@ -1129,8 +1567,9 @@ def test_find_lfp_providers_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, lfpproviders.LfpProvider) - for i in results) + assert all(isinstance(i, lfpproviders.LfpProvider) for i in results) + + def test_find_lfp_providers_pages(transport_name: str = "grpc"): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1139,8 +1578,8 @@ def test_find_lfp_providers_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( lfpproviders.FindLfpProvidersResponse( @@ -1149,17 +1588,17 @@ def test_find_lfp_providers_pages(transport_name: str = "grpc"): lfpproviders.LfpProvider(), lfpproviders.LfpProvider(), ], - next_page_token='abc', + next_page_token="abc", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[], - next_page_token='def', + next_page_token="def", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ lfpproviders.LfpProvider(), ], - next_page_token='ghi', + next_page_token="ghi", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ @@ -1170,9 +1609,10 @@ def test_find_lfp_providers_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.find_lfp_providers(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_find_lfp_providers_async_pager(): client = LfpProvidersServiceAsyncClient( @@ -1181,8 +1621,10 @@ async def test_find_lfp_providers_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.find_lfp_providers), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( lfpproviders.FindLfpProvidersResponse( @@ -1191,17 +1633,17 @@ async def test_find_lfp_providers_async_pager(): lfpproviders.LfpProvider(), lfpproviders.LfpProvider(), ], - next_page_token='abc', + next_page_token="abc", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[], - next_page_token='def', + next_page_token="def", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ lfpproviders.LfpProvider(), ], - next_page_token='ghi', + next_page_token="ghi", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ @@ -1211,15 +1653,16 @@ async def test_find_lfp_providers_async_pager(): ), RuntimeError, ) - async_pager = await client.find_lfp_providers(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.find_lfp_providers( + 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, lfpproviders.LfpProvider) - for i in responses) + assert all(isinstance(i, lfpproviders.LfpProvider) for i in responses) @pytest.mark.asyncio @@ -1230,8 +1673,10 @@ async def test_find_lfp_providers_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.find_lfp_providers), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( lfpproviders.FindLfpProvidersResponse( @@ -1240,17 +1685,17 @@ async def test_find_lfp_providers_async_pages(): lfpproviders.LfpProvider(), lfpproviders.LfpProvider(), ], - next_page_token='abc', + next_page_token="abc", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[], - next_page_token='def', + next_page_token="def", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ lfpproviders.LfpProvider(), ], - next_page_token='ghi', + next_page_token="ghi", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ @@ -1263,18 +1708,22 @@ async def test_find_lfp_providers_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.find_lfp_providers(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", [ - lfpproviders.LinkLfpProviderRequest, - dict, -]) -def test_link_lfp_provider(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + lfpproviders.LinkLfpProviderRequest, + dict, + ], +) +def test_link_lfp_provider(request_type, transport: str = "grpc"): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1286,11 +1735,10 @@ def test_link_lfp_provider(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = lfpproviders.LinkLfpProviderResponse( - ) + call.return_value = lfpproviders.LinkLfpProviderResponse() response = client.link_lfp_provider(request) # Establish that the underlying gRPC stub method was called. @@ -1308,30 +1756,33 @@ def test_link_lfp_provider_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = LfpProvidersServiceClient( 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 = lfpproviders.LinkLfpProviderRequest( - name='name_value', - external_account_id='external_account_id_value', + name="name_value", + external_account_id="external_account_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.link_lfp_provider), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.link_lfp_provider(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == lfpproviders.LinkLfpProviderRequest( - name='name_value', - external_account_id='external_account_id_value', + name="name_value", + external_account_id="external_account_id_value", ) + def test_link_lfp_provider_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1350,8 +1801,12 @@ def test_link_lfp_provider_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.link_lfp_provider + ] = mock_rpc request = {} client.link_lfp_provider(request) @@ -1364,8 +1819,11 @@ def test_link_lfp_provider_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_link_lfp_provider_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_link_lfp_provider_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: @@ -1379,12 +1837,17 @@ async def test_link_lfp_provider_async_use_cached_wrapped_rpc(transport: str = " wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.link_lfp_provider in client._client._transport._wrapped_methods + assert ( + client._client._transport.link_lfp_provider + 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.link_lfp_provider] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.link_lfp_provider + ] = mock_rpc request = {} await client.link_lfp_provider(request) @@ -1398,8 +1861,11 @@ async def test_link_lfp_provider_async_use_cached_wrapped_rpc(transport: str = " assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_link_lfp_provider_async(transport: str = 'grpc_asyncio', request_type=lfpproviders.LinkLfpProviderRequest): +async def test_link_lfp_provider_async( + transport: str = "grpc_asyncio", request_type=lfpproviders.LinkLfpProviderRequest +): client = LfpProvidersServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1411,11 +1877,12 @@ async def test_link_lfp_provider_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.LinkLfpProviderResponse() + ) response = await client.link_lfp_provider(request) # Establish that the underlying gRPC stub method was called. @@ -1432,6 +1899,7 @@ async def test_link_lfp_provider_async(transport: str = 'grpc_asyncio', request_ async def test_link_lfp_provider_async_from_dict(): await test_link_lfp_provider_async(request_type=dict) + def test_link_lfp_provider_field_headers(): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1441,12 +1909,12 @@ def test_link_lfp_provider_field_headers(): # a field header. Set these to a non-empty value. request = lfpproviders.LinkLfpProviderRequest() - 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.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: call.return_value = lfpproviders.LinkLfpProviderResponse() client.link_lfp_provider(request) @@ -1458,9 +1926,9 @@ def test_link_lfp_provider_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 @@ -1473,13 +1941,15 @@ async def test_link_lfp_provider_field_headers_async(): # a field header. Set these to a non-empty value. request = lfpproviders.LinkLfpProviderRequest() - 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.link_lfp_provider), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) + type(client.transport.link_lfp_provider), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.LinkLfpProviderResponse() + ) await client.link_lfp_provider(request) # Establish that the underlying gRPC stub method was called. @@ -1490,9 +1960,9 @@ async def test_link_lfp_provider_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_link_lfp_provider_flattened(): @@ -1502,14 +1972,14 @@ def test_link_lfp_provider_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = lfpproviders.LinkLfpProviderResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.link_lfp_provider( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1517,7 +1987,7 @@ def test_link_lfp_provider_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 @@ -1531,9 +2001,10 @@ def test_link_lfp_provider_flattened_error(): with pytest.raises(ValueError): client.link_lfp_provider( lfpproviders.LinkLfpProviderRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_link_lfp_provider_flattened_async(): client = LfpProvidersServiceAsyncClient( @@ -1542,16 +2013,18 @@ async def test_link_lfp_provider_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = lfpproviders.LinkLfpProviderResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.LinkLfpProviderResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.link_lfp_provider( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1559,9 +2032,10 @@ async def test_link_lfp_provider_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_link_lfp_provider_flattened_error_async(): client = LfpProvidersServiceAsyncClient( @@ -1573,7 +2047,7 @@ async def test_link_lfp_provider_flattened_error_async(): with pytest.raises(ValueError): await client.link_lfp_provider( lfpproviders.LinkLfpProviderRequest(), - name='name_value', + name="name_value", ) @@ -1591,12 +2065,18 @@ def test_find_lfp_providers_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.find_lfp_providers in client._transport._wrapped_methods + assert ( + client._transport.find_lfp_providers in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.find_lfp_providers] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.find_lfp_providers + ] = mock_rpc request = {} client.find_lfp_providers(request) @@ -1611,57 +2091,67 @@ def test_find_lfp_providers_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_find_lfp_providers_rest_required_fields(request_type=lfpproviders.FindLfpProvidersRequest): +def test_find_lfp_providers_rest_required_fields( + request_type=lfpproviders.FindLfpProvidersRequest, +): transport_class = transports.LfpProvidersServiceRestTransport 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()).find_lfp_providers._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).find_lfp_providers._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()).find_lfp_providers._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).find_lfp_providers._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 = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = lfpproviders.FindLfpProvidersResponse() # Mock the http request 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 @@ -1672,24 +2162,32 @@ def test_find_lfp_providers_rest_required_fields(request_type=lfpproviders.FindL return_value = lfpproviders.FindLfpProvidersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.find_lfp_providers(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_find_lfp_providers_rest_unset_required_fields(): - transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.LfpProvidersServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.find_lfp_providers._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) def test_find_lfp_providers_rest_flattened(): @@ -1699,16 +2197,16 @@ def test_find_lfp_providers_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 = lfpproviders.FindLfpProvidersResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1/omnichannelSettings/sample2'} + sample_request = {"parent": "accounts/sample1/omnichannelSettings/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1718,7 +2216,7 @@ def test_find_lfp_providers_rest_flattened(): # Convert return value to protobuf type return_value = lfpproviders.FindLfpProvidersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1728,10 +2226,14 @@ def test_find_lfp_providers_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*/omnichannelSettings/*}/lfpProviders:find" + % client.transport._host, + args[1], + ) -def test_find_lfp_providers_rest_flattened_error(transport: str = 'rest'): +def test_find_lfp_providers_rest_flattened_error(transport: str = "rest"): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1742,20 +2244,20 @@ def test_find_lfp_providers_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.find_lfp_providers( lfpproviders.FindLfpProvidersRequest(), - parent='parent_value', + parent="parent_value", ) -def test_find_lfp_providers_rest_pager(transport: str = 'rest'): +def test_find_lfp_providers_rest_pager(transport: str = "rest"): client = LfpProvidersServiceClient( 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 = ( lfpproviders.FindLfpProvidersResponse( @@ -1764,17 +2266,17 @@ def test_find_lfp_providers_rest_pager(transport: str = 'rest'): lfpproviders.LfpProvider(), lfpproviders.LfpProvider(), ], - next_page_token='abc', + next_page_token="abc", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[], - next_page_token='def', + next_page_token="def", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ lfpproviders.LfpProvider(), ], - next_page_token='ghi', + next_page_token="ghi", ), lfpproviders.FindLfpProvidersResponse( lfp_providers=[ @@ -1787,24 +2289,25 @@ def test_find_lfp_providers_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(lfpproviders.FindLfpProvidersResponse.to_json(x) for x in response) + response = tuple( + lfpproviders.FindLfpProvidersResponse.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/omnichannelSettings/sample2'} + sample_request = {"parent": "accounts/sample1/omnichannelSettings/sample2"} pager = client.find_lfp_providers(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, lfpproviders.LfpProvider) - for i in results) + assert all(isinstance(i, lfpproviders.LfpProvider) for i in results) pages = list(client.find_lfp_providers(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 @@ -1826,8 +2329,12 @@ def test_link_lfp_provider_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.link_lfp_provider] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.link_lfp_provider + ] = mock_rpc request = {} client.link_lfp_provider(request) @@ -1842,7 +2349,9 @@ def test_link_lfp_provider_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_link_lfp_provider_rest_required_fields(request_type=lfpproviders.LinkLfpProviderRequest): +def test_link_lfp_provider_rest_required_fields( + request_type=lfpproviders.LinkLfpProviderRequest, +): transport_class = transports.LfpProvidersServiceRestTransport request_init = {} @@ -1850,53 +2359,56 @@ def test_link_lfp_provider_rest_required_fields(request_type=lfpproviders.LinkLf request_init["external_account_id"] = "" 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()).link_lfp_provider._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).link_lfp_provider._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["externalAccountId"] = 'external_account_id_value' + jsonified_request["name"] = "name_value" + jsonified_request["externalAccountId"] = "external_account_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).link_lfp_provider._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).link_lfp_provider._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" assert "externalAccountId" in jsonified_request - assert jsonified_request["externalAccountId"] == 'external_account_id_value' + assert jsonified_request["externalAccountId"] == "external_account_id_value" client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = lfpproviders.LinkLfpProviderResponse() # Mock the http request 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() @@ -1906,24 +2418,32 @@ def test_link_lfp_provider_rest_required_fields(request_type=lfpproviders.LinkLf return_value = lfpproviders.LinkLfpProviderResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.link_lfp_provider(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_link_lfp_provider_rest_unset_required_fields(): - transport = transports.LfpProvidersServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.LfpProvidersServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.link_lfp_provider._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "externalAccountId", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "externalAccountId", + ) + ) + ) def test_link_lfp_provider_rest_flattened(): @@ -1933,16 +2453,18 @@ def test_link_lfp_provider_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 = lfpproviders.LinkLfpProviderResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/sample3'} + sample_request = { + "name": "accounts/sample1/omnichannelSettings/sample2/lfpProviders/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1952,7 +2474,7 @@ def test_link_lfp_provider_rest_flattened(): # Convert return value to protobuf type return_value = lfpproviders.LinkLfpProviderResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._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 +2484,14 @@ def test_link_lfp_provider_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/omnichannelSettings/*/lfpProviders/*}:linkLfpProvider" + % client.transport._host, + args[1], + ) -def test_link_lfp_provider_rest_flattened_error(transport: str = 'rest'): +def test_link_lfp_provider_rest_flattened_error(transport: str = "rest"): client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1976,7 +2502,7 @@ def test_link_lfp_provider_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.link_lfp_provider( lfpproviders.LinkLfpProviderRequest(), - name='name_value', + name="name_value", ) @@ -2018,8 +2544,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = LfpProvidersServiceClient( - 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. @@ -2041,6 +2566,7 @@ def test_transport_instance(): client = LfpProvidersServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.LfpProvidersServiceGrpcTransport( @@ -2055,18 +2581,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.LfpProvidersServiceGrpcTransport, - transports.LfpProvidersServiceGrpcAsyncIOTransport, - transports.LfpProvidersServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + transports.LfpProvidersServiceRestTransport, + ], +) 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 = LfpProvidersServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2076,8 +2607,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2092,8 +2622,8 @@ def test_find_lfp_providers_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: call.return_value = lfpproviders.FindLfpProvidersResponse() client.find_lfp_providers(request=None) @@ -2115,8 +2645,8 @@ def test_link_lfp_provider_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: call.return_value = lfpproviders.LinkLfpProviderResponse() client.link_lfp_provider(request=None) @@ -2137,8 +2667,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = LfpProvidersServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2154,12 +2683,14 @@ async def test_find_lfp_providers_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.FindLfpProvidersResponse( + next_page_token="next_page_token_value", + ) + ) await client.find_lfp_providers(request=None) # Establish that the underlying stub method was called. @@ -2181,11 +2712,12 @@ async def test_link_lfp_provider_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(lfpproviders.LinkLfpProviderResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lfpproviders.LinkLfpProviderResponse() + ) await client.link_lfp_provider(request=None) # Establish that the underlying stub method was called. @@ -2203,20 +2735,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_find_lfp_providers_rest_bad_request(request_type=lfpproviders.FindLfpProvidersRequest): +def test_find_lfp_providers_rest_bad_request( + request_type=lfpproviders.FindLfpProvidersRequest, +): client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/omnichannelSettings/sample2'} + request_init = {"parent": "accounts/sample1/omnichannelSettings/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() @@ -2225,25 +2760,27 @@ def test_find_lfp_providers_rest_bad_request(request_type=lfpproviders.FindLfpPr client.find_lfp_providers(request) -@pytest.mark.parametrize("request_type", [ - lfpproviders.FindLfpProvidersRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + lfpproviders.FindLfpProvidersRequest, + dict, + ], +) def test_find_lfp_providers_rest_call_success(request_type): client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1/omnichannelSettings/sample2'} + request_init = {"parent": "accounts/sample1/omnichannelSettings/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 = lfpproviders.FindLfpProvidersResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -2253,33 +2790,44 @@ def test_find_lfp_providers_rest_call_success(request_type): # Convert return value to protobuf type return_value = lfpproviders.FindLfpProvidersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.find_lfp_providers(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.FindLfpProvidersPager) - 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_find_lfp_providers_rest_interceptors(null_interceptor): transport = transports.LfpProvidersServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.LfpProvidersServiceRestInterceptor(), + ) client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers") as post, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_find_lfp_providers") 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.LfpProvidersServiceRestInterceptor, "post_find_lfp_providers" + ) as post, mock.patch.object( + transports.LfpProvidersServiceRestInterceptor, + "post_find_lfp_providers_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.LfpProvidersServiceRestInterceptor, "pre_find_lfp_providers" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = lfpproviders.FindLfpProvidersRequest.pb(lfpproviders.FindLfpProvidersRequest()) + pb_message = lfpproviders.FindLfpProvidersRequest.pb( + lfpproviders.FindLfpProvidersRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2290,39 +2838,55 @@ def test_find_lfp_providers_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 = lfpproviders.FindLfpProvidersResponse.to_json(lfpproviders.FindLfpProvidersResponse()) + return_value = lfpproviders.FindLfpProvidersResponse.to_json( + lfpproviders.FindLfpProvidersResponse() + ) req.return_value.content = return_value request = lfpproviders.FindLfpProvidersRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = lfpproviders.FindLfpProvidersResponse() - post_with_metadata.return_value = lfpproviders.FindLfpProvidersResponse(), metadata + post_with_metadata.return_value = ( + lfpproviders.FindLfpProvidersResponse(), + metadata, + ) - client.find_lfp_providers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.find_lfp_providers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_link_lfp_provider_rest_bad_request(request_type=lfpproviders.LinkLfpProviderRequest): +def test_link_lfp_provider_rest_bad_request( + request_type=lfpproviders.LinkLfpProviderRequest, +): client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/sample3'} + request_init = { + "name": "accounts/sample1/omnichannelSettings/sample2/lfpProviders/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() @@ -2331,25 +2895,28 @@ def test_link_lfp_provider_rest_bad_request(request_type=lfpproviders.LinkLfpPro client.link_lfp_provider(request) -@pytest.mark.parametrize("request_type", [ - lfpproviders.LinkLfpProviderRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + lfpproviders.LinkLfpProviderRequest, + dict, + ], +) def test_link_lfp_provider_rest_call_success(request_type): client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2/lfpProviders/sample3'} + request_init = { + "name": "accounts/sample1/omnichannelSettings/sample2/lfpProviders/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 = lfpproviders.LinkLfpProviderResponse( - ) + return_value = lfpproviders.LinkLfpProviderResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -2358,7 +2925,7 @@ def test_link_lfp_provider_rest_call_success(request_type): # Convert return value to protobuf type return_value = lfpproviders.LinkLfpProviderResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.link_lfp_provider(request) @@ -2371,19 +2938,30 @@ def test_link_lfp_provider_rest_call_success(request_type): def test_link_lfp_provider_rest_interceptors(null_interceptor): transport = transports.LfpProvidersServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.LfpProvidersServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.LfpProvidersServiceRestInterceptor(), + ) client = LfpProvidersServiceClient(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.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider") as post, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.LfpProvidersServiceRestInterceptor, "pre_link_lfp_provider") 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.LfpProvidersServiceRestInterceptor, "post_link_lfp_provider" + ) as post, mock.patch.object( + transports.LfpProvidersServiceRestInterceptor, + "post_link_lfp_provider_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.LfpProvidersServiceRestInterceptor, "pre_link_lfp_provider" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = lfpproviders.LinkLfpProviderRequest.pb(lfpproviders.LinkLfpProviderRequest()) + pb_message = lfpproviders.LinkLfpProviderRequest.pb( + lfpproviders.LinkLfpProviderRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2394,28 +2972,39 @@ def test_link_lfp_provider_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 = lfpproviders.LinkLfpProviderResponse.to_json(lfpproviders.LinkLfpProviderResponse()) + return_value = lfpproviders.LinkLfpProviderResponse.to_json( + lfpproviders.LinkLfpProviderResponse() + ) req.return_value.content = return_value request = lfpproviders.LinkLfpProviderRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = lfpproviders.LinkLfpProviderResponse() - post_with_metadata.return_value = lfpproviders.LinkLfpProviderResponse(), metadata + post_with_metadata.return_value = ( + lfpproviders.LinkLfpProviderResponse(), + metadata, + ) - client.link_lfp_provider(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.link_lfp_provider( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = LfpProvidersServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2430,8 +3019,8 @@ def test_find_lfp_providers_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.find_lfp_providers), - '__call__') as call: + type(client.transport.find_lfp_providers), "__call__" + ) as call: client.find_lfp_providers(request=None) # Establish that the underlying stub method was called. @@ -2452,8 +3041,8 @@ def test_link_lfp_provider_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.link_lfp_provider), - '__call__') as call: + type(client.transport.link_lfp_provider), "__call__" + ) as call: client.link_lfp_provider(request=None) # Establish that the underlying stub method was called. @@ -2474,18 +3063,21 @@ def test_transport_grpc_default(): transports.LfpProvidersServiceGrpcTransport, ) + def test_lfp_providers_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.LfpProvidersServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_lfp_providers_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.LfpProvidersServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2494,8 +3086,8 @@ def test_lfp_providers_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'find_lfp_providers', - 'link_lfp_provider', + "find_lfp_providers", + "link_lfp_provider", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2506,7 +3098,7 @@ def test_lfp_providers_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2515,25 +3107,30 @@ def test_lfp_providers_service_base_transport(): def test_lfp_providers_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_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport._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_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LfpProvidersServiceTransport( 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_lfp_providers_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_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.lfp_providers_service.transports.LfpProvidersServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.LfpProvidersServiceTransport() @@ -2542,14 +3139,12 @@ def test_lfp_providers_service_base_transport_with_adc(): def test_lfp_providers_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) LfpProvidersServiceClient() 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, ) @@ -2564,12 +3159,12 @@ def test_lfp_providers_service_auth_adc(): def test_lfp_providers_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", ) @@ -2583,48 +3178,45 @@ def test_lfp_providers_service_transport_auth_adc(transport_class): ], ) def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, grpc_helpers), - (transports.LfpProvidersServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.LfpProvidersServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_lfp_providers_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, @@ -2635,9 +3227,15 @@ def test_lfp_providers_service_transport_create_channel(transport_class, grpc_he ) -@pytest.mark.parametrize("transport_class", [transports.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + ], +) def test_lfp_providers_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2647,7 +3245,7 @@ def test_lfp_providers_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", @@ -2668,61 +3266,77 @@ def test_lfp_providers_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_lfp_providers_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.LfpProvidersServiceRestTransport ( - 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.LfpProvidersServiceRestTransport( + 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_lfp_providers_service_host_no_port(transport_name): client = LfpProvidersServiceClient( 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_lfp_providers_service_host_with_port(transport_name): client = LfpProvidersServiceClient( 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_lfp_providers_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2740,8 +3354,10 @@ def test_lfp_providers_service_client_transport_session_collision(transport_name session1 = client1.transport.link_lfp_provider._session session2 = client2.transport.link_lfp_provider._session assert session1 != session2 + + def test_lfp_providers_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.LfpProvidersServiceGrpcTransport( @@ -2754,7 +3370,7 @@ def test_lfp_providers_service_grpc_transport_channel(): def test_lfp_providers_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.LfpProvidersServiceGrpcAsyncIOTransport( @@ -2768,12 +3384,22 @@ def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + ], +) def test_lfp_providers_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 @@ -2782,7 +3408,7 @@ def test_lfp_providers_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", @@ -2812,17 +3438,23 @@ def test_lfp_providers_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.LfpProvidersServiceGrpcTransport, transports.LfpProvidersServiceGrpcAsyncIOTransport]) -def test_lfp_providers_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.LfpProvidersServiceGrpcTransport, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + ], +) +def test_lfp_providers_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() @@ -2854,8 +3486,14 @@ def test_lfp_provider_path(): account = "squid" omnichannel_setting = "clam" lfp_provider = "whelk" - expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format(account=account, omnichannel_setting=omnichannel_setting, lfp_provider=lfp_provider, ) - actual = LfpProvidersServiceClient.lfp_provider_path(account, omnichannel_setting, lfp_provider) + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}/lfpProviders/{lfp_provider}".format( + account=account, + omnichannel_setting=omnichannel_setting, + lfp_provider=lfp_provider, + ) + actual = LfpProvidersServiceClient.lfp_provider_path( + account, omnichannel_setting, lfp_provider + ) assert expected == actual @@ -2871,11 +3509,17 @@ def test_parse_lfp_provider_path(): actual = LfpProvidersServiceClient.parse_lfp_provider_path(path) assert expected == actual + def test_omnichannel_setting_path(): account = "cuttlefish" omnichannel_setting = "mussel" - expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) - actual = LfpProvidersServiceClient.omnichannel_setting_path(account, omnichannel_setting) + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format( + account=account, + omnichannel_setting=omnichannel_setting, + ) + actual = LfpProvidersServiceClient.omnichannel_setting_path( + account, omnichannel_setting + ) assert expected == actual @@ -2890,9 +3534,12 @@ def test_parse_omnichannel_setting_path(): actual = LfpProvidersServiceClient.parse_omnichannel_setting_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = LfpProvidersServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2907,9 +3554,12 @@ def test_parse_common_billing_account_path(): actual = LfpProvidersServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = LfpProvidersServiceClient.common_folder_path(folder) assert expected == actual @@ -2924,9 +3574,12 @@ def test_parse_common_folder_path(): actual = LfpProvidersServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = LfpProvidersServiceClient.common_organization_path(organization) assert expected == actual @@ -2941,9 +3594,12 @@ def test_parse_common_organization_path(): actual = LfpProvidersServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = LfpProvidersServiceClient.common_project_path(project) assert expected == actual @@ -2958,10 +3614,14 @@ def test_parse_common_project_path(): actual = LfpProvidersServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = LfpProvidersServiceClient.common_location_path(project, location) assert expected == actual @@ -2981,14 +3641,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.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.LfpProvidersServiceTransport, "_prep_wrapped_messages" + ) as prep: client = LfpProvidersServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.LfpProvidersServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.LfpProvidersServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = LfpProvidersServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2999,10 +3663,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = LfpProvidersServiceClient( - 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() @@ -3011,10 +3676,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = LfpProvidersServiceAsyncClient( - 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() @@ -3022,10 +3688,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = LfpProvidersServiceClient( - 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() @@ -3033,13 +3700,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = LfpProvidersServiceClient( - 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: @@ -3048,10 +3714,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport), - (LfpProvidersServiceAsyncClient, transports.LfpProvidersServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (LfpProvidersServiceClient, transports.LfpProvidersServiceGrpcTransport), + ( + LfpProvidersServiceAsyncClient, + transports.LfpProvidersServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3066,7 +3739,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py similarity index 69% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py index 5ba89b473386..037a4b46c142 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_omnichannel_settings_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,46 +22,44 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import OmnichannelSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import OmnichannelSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import pagers -from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import transports -from google.shopping.merchant_accounts_v1.types import omnichannelsettings -import google.auth - +from google.shopping.merchant_accounts_v1.services.omnichannel_settings_service import ( + OmnichannelSettingsServiceAsyncClient, + OmnichannelSettingsServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import omnichannelsettings CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +74,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(): @@ -85,17 +86,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(): @@ -106,101 +117,249 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OmnichannelSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OmnichannelSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OmnichannelSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OmnichannelSettingsServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + OmnichannelSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert OmnichannelSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (True, "auto", None) + assert OmnichannelSettingsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert OmnichannelSettingsServiceClient._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: OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._read_environment_variables() == (False, "never", None) + assert OmnichannelSettingsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "always", None) + assert OmnichannelSettingsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert OmnichannelSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, False) is None - assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + OmnichannelSettingsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + OmnichannelSettingsServiceClient._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 ( + OmnichannelSettingsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert OmnichannelSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +@mock.patch.object( + OmnichannelSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceClient), +) +@mock.patch.object( + OmnichannelSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert OmnichannelSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert OmnichannelSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == OmnichannelSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + OmnichannelSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - OmnichannelSettingsServiceClient._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." + OmnichannelSettingsServiceClient._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 OmnichannelSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert OmnichannelSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert OmnichannelSettingsServiceClient._get_universe_domain(None, None) == OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + assert ( + OmnichannelSettingsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + OmnichannelSettingsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + OmnichannelSettingsServiceClient._get_universe_domain(None, None) + == OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: OmnichannelSettingsServiceClient._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) @@ -216,7 +375,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") @@ -229,14 +389,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", [ - (OmnichannelSettingsServiceClient, "grpc"), - (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, "rest"), -]) -def test_omnichannel_settings_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (OmnichannelSettingsServiceClient, "grpc"), + (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, "rest"), + ], +) +def test_omnichannel_settings_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) @@ -244,52 +412,70 @@ def test_omnichannel_settings_service_client_from_service_account_info(client_cl 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.OmnichannelSettingsServiceGrpcTransport, "grpc"), - (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.OmnichannelSettingsServiceRestTransport, "rest"), -]) -def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, "grpc"), + (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OmnichannelSettingsServiceRestTransport, "rest"), + ], +) +def test_omnichannel_settings_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", [ - (OmnichannelSettingsServiceClient, "grpc"), - (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, "rest"), -]) -def test_omnichannel_settings_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (OmnichannelSettingsServiceClient, "grpc"), + (OmnichannelSettingsServiceAsyncClient, "grpc_asyncio"), + (OmnichannelSettingsServiceClient, "rest"), + ], +) +def test_omnichannel_settings_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" ) @@ -305,30 +491,57 @@ def test_omnichannel_settings_service_client_get_transport_class(): assert transport == transports.OmnichannelSettingsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) -def test_omnichannel_settings_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + "grpc", + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + OmnichannelSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceClient), +) +@mock.patch.object( + OmnichannelSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient), +) +def test_omnichannel_settings_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(OmnichannelSettingsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + OmnichannelSettingsServiceClient, "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(OmnichannelSettingsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + OmnichannelSettingsServiceClient, "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( @@ -346,13 +559,15 @@ def test_omnichannel_settings_service_client_client_options(client_class, transp # 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, @@ -364,7 +579,7 @@ def test_omnichannel_settings_service_client_client_options(client_class, transp # 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( @@ -384,23 +599,33 @@ def test_omnichannel_settings_service_client_client_options(client_class, transp 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", @@ -409,48 +634,102 @@ def test_omnichannel_settings_service_client_client_options(client_class, transp 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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "true"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", "false"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "true"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + "grpc", + "true", + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + "grpc", + "false", + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceRestTransport, + "rest", + "true", + ), + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + OmnichannelSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceClient), +) +@mock.patch.object( + OmnichannelSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_omnichannel_settings_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_omnichannel_settings_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 @@ -469,12 +748,22 @@ def test_omnichannel_settings_service_client_mtls_env_auto(client_class, transpo # 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 @@ -495,15 +784,22 @@ def test_omnichannel_settings_service_client_mtls_env_auto(client_class, transpo ) # 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, @@ -513,19 +809,34 @@ def test_omnichannel_settings_service_client_mtls_env_auto(client_class, transpo ) -@pytest.mark.parametrize("client_class", [ - OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OmnichannelSettingsServiceAsyncClient)) -def test_omnichannel_settings_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient], +) +@mock.patch.object( + OmnichannelSettingsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OmnichannelSettingsServiceClient), +) +@mock.patch.object( + OmnichannelSettingsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OmnichannelSettingsServiceAsyncClient), +) +def test_omnichannel_settings_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 @@ -533,8 +844,12 @@ def test_omnichannel_settings_service_client_get_mtls_endpoint_and_cert_source(c 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 @@ -552,16 +867,28 @@ def test_omnichannel_settings_service_client_get_mtls_endpoint_and_cert_source(c # 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 @@ -571,34 +898,65 @@ def test_omnichannel_settings_service_client_get_mtls_endpoint_and_cert_source(c 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", [ - OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient -]) -@mock.patch.object(OmnichannelSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceClient)) -@mock.patch.object(OmnichannelSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [OmnichannelSettingsServiceClient, OmnichannelSettingsServiceAsyncClient], +) +@mock.patch.object( + OmnichannelSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceClient), +) +@mock.patch.object( + OmnichannelSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OmnichannelSettingsServiceAsyncClient), +) def test_omnichannel_settings_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = OmnichannelSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = OmnichannelSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = OmnichannelSettingsServiceClient._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", @@ -621,11 +979,19 @@ def test_omnichannel_settings_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. @@ -633,27 +999,48 @@ def test_omnichannel_settings_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", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc"), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest"), -]) -def test_omnichannel_settings_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + "grpc", + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceRestTransport, + "rest", + ), + ], +) +def test_omnichannel_settings_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, @@ -662,24 +1049,45 @@ def test_omnichannel_settings_service_client_client_options_scopes(client_class, api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceRestTransport, "rest", None), -]) -def test_omnichannel_settings_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", + [ + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_omnichannel_settings_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, @@ -688,11 +1096,14 @@ def test_omnichannel_settings_service_client_client_options_credentials_file(cli api_audience=None, ) + def test_omnichannel_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = OmnichannelSettingsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1118,38 @@ def test_omnichannel_settings_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_omnichannel_settings_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", + [ + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_omnichannel_settings_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, @@ -750,9 +1176,7 @@ def test_omnichannel_settings_service_client_create_channel_credentials_file(cli 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, @@ -763,11 +1187,14 @@ def test_omnichannel_settings_service_client_create_channel_credentials_file(cli ) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.GetOmnichannelSettingRequest, - dict, -]) -def test_get_omnichannel_setting(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.GetOmnichannelSettingRequest, + dict, + ], +) +def test_get_omnichannel_setting(request_type, transport: str = "grpc"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,12 +1206,12 @@ def test_get_omnichannel_setting(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, ) response = client.get_omnichannel_setting(request) @@ -797,8 +1224,8 @@ def test_get_omnichannel_setting(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -807,28 +1234,31 @@ def test_get_omnichannel_setting_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OmnichannelSettingsServiceClient( 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 = omnichannelsettings.GetOmnichannelSettingRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_omnichannel_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == omnichannelsettings.GetOmnichannelSettingRequest( - name='name_value', + name="name_value", ) + def test_get_omnichannel_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -843,12 +1273,19 @@ def test_get_omnichannel_setting_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_omnichannel_setting in client._transport._wrapped_methods + assert ( + client._transport.get_omnichannel_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_omnichannel_setting + ] = mock_rpc request = {} client.get_omnichannel_setting(request) @@ -861,8 +1298,11 @@ def test_get_omnichannel_setting_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_omnichannel_setting_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_omnichannel_setting_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: @@ -876,12 +1316,17 @@ async def test_get_omnichannel_setting_async_use_cached_wrapped_rpc(transport: s wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_omnichannel_setting in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_omnichannel_setting + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_omnichannel_setting] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_omnichannel_setting + ] = mock_rpc request = {} await client.get_omnichannel_setting(request) @@ -895,8 +1340,12 @@ async def test_get_omnichannel_setting_async_use_cached_wrapped_rpc(transport: s assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.GetOmnichannelSettingRequest): +async def test_get_omnichannel_setting_async( + transport: str = "grpc_asyncio", + request_type=omnichannelsettings.GetOmnichannelSettingRequest, +): client = OmnichannelSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -908,14 +1357,16 @@ async def test_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', re # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting( + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + ) response = await client.get_omnichannel_setting(request) # Establish that the underlying gRPC stub method was called. @@ -926,8 +1377,8 @@ async def test_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', re # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -935,6 +1386,7 @@ async def test_get_omnichannel_setting_async(transport: str = 'grpc_asyncio', re async def test_get_omnichannel_setting_async_from_dict(): await test_get_omnichannel_setting_async(request_type=dict) + def test_get_omnichannel_setting_field_headers(): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -944,12 +1396,12 @@ def test_get_omnichannel_setting_field_headers(): # a field header. Set these to a non-empty value. request = omnichannelsettings.GetOmnichannelSettingRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: call.return_value = omnichannelsettings.OmnichannelSetting() client.get_omnichannel_setting(request) @@ -961,9 +1413,9 @@ def test_get_omnichannel_setting_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 @@ -976,13 +1428,15 @@ async def test_get_omnichannel_setting_field_headers_async(): # a field header. Set these to a non-empty value. request = omnichannelsettings.GetOmnichannelSettingRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting() + ) await client.get_omnichannel_setting(request) # Establish that the underlying gRPC stub method was called. @@ -993,9 +1447,9 @@ async def test_get_omnichannel_setting_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_omnichannel_setting_flattened(): @@ -1005,14 +1459,14 @@ def test_get_omnichannel_setting_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_omnichannel_setting( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1020,7 +1474,7 @@ def test_get_omnichannel_setting_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 @@ -1034,9 +1488,10 @@ def test_get_omnichannel_setting_flattened_error(): with pytest.raises(ValueError): client.get_omnichannel_setting( omnichannelsettings.GetOmnichannelSettingRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_omnichannel_setting_flattened_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -1045,16 +1500,18 @@ async def test_get_omnichannel_setting_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_omnichannel_setting( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1062,9 +1519,10 @@ async def test_get_omnichannel_setting_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_omnichannel_setting_flattened_error_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -1076,15 +1534,18 @@ async def test_get_omnichannel_setting_flattened_error_async(): with pytest.raises(ValueError): await client.get_omnichannel_setting( omnichannelsettings.GetOmnichannelSettingRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.ListOmnichannelSettingsRequest, - dict, -]) -def test_list_omnichannel_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.ListOmnichannelSettingsRequest, + dict, + ], +) +def test_list_omnichannel_settings(request_type, transport: str = "grpc"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1096,11 +1557,11 @@ def test_list_omnichannel_settings(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_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_omnichannel_settings(request) @@ -1112,7 +1573,7 @@ def test_list_omnichannel_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListOmnichannelSettingsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_omnichannel_settings_non_empty_request_with_auto_populated_field(): @@ -1120,30 +1581,33 @@ def test_list_omnichannel_settings_non_empty_request_with_auto_populated_field() # automatically populated, according to AIP-4235, with non-empty requests. client = OmnichannelSettingsServiceClient( 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 = omnichannelsettings.ListOmnichannelSettingsRequest( - 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_omnichannel_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_omnichannel_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == omnichannelsettings.ListOmnichannelSettingsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_omnichannel_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1158,12 +1622,19 @@ def test_list_omnichannel_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_omnichannel_settings in client._transport._wrapped_methods + assert ( + client._transport.list_omnichannel_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_omnichannel_settings] = 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_omnichannel_settings + ] = mock_rpc request = {} client.list_omnichannel_settings(request) @@ -1176,8 +1647,11 @@ def test_list_omnichannel_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_omnichannel_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_omnichannel_settings_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: @@ -1191,12 +1665,17 @@ async def test_list_omnichannel_settings_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_omnichannel_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_omnichannel_settings + 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_omnichannel_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_omnichannel_settings + ] = mock_rpc request = {} await client.list_omnichannel_settings(request) @@ -1210,8 +1689,12 @@ async def test_list_omnichannel_settings_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_omnichannel_settings_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.ListOmnichannelSettingsRequest): +async def test_list_omnichannel_settings_async( + transport: str = "grpc_asyncio", + request_type=omnichannelsettings.ListOmnichannelSettingsRequest, +): client = OmnichannelSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1223,12 +1706,14 @@ async def test_list_omnichannel_settings_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_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_omnichannel_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1239,13 +1724,14 @@ async def test_list_omnichannel_settings_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListOmnichannelSettingsAsyncPager) - 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_omnichannel_settings_async_from_dict(): await test_list_omnichannel_settings_async(request_type=dict) + def test_list_omnichannel_settings_field_headers(): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1255,12 +1741,12 @@ def test_list_omnichannel_settings_field_headers(): # a field header. Set these to a non-empty value. request = omnichannelsettings.ListOmnichannelSettingsRequest() - 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_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() client.list_omnichannel_settings(request) @@ -1272,9 +1758,9 @@ def test_list_omnichannel_settings_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 @@ -1287,13 +1773,15 @@ async def test_list_omnichannel_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = omnichannelsettings.ListOmnichannelSettingsRequest() - 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_omnichannel_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.ListOmnichannelSettingsResponse() + ) await client.list_omnichannel_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1304,9 +1792,9 @@ async def test_list_omnichannel_settings_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_omnichannel_settings_flattened(): @@ -1316,14 +1804,14 @@ def test_list_omnichannel_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_omnichannel_settings( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1331,7 +1819,7 @@ def test_list_omnichannel_settings_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 @@ -1345,9 +1833,10 @@ def test_list_omnichannel_settings_flattened_error(): with pytest.raises(ValueError): client.list_omnichannel_settings( omnichannelsettings.ListOmnichannelSettingsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_omnichannel_settings_flattened_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -1356,16 +1845,18 @@ async def test_list_omnichannel_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.ListOmnichannelSettingsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_omnichannel_settings( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1373,9 +1864,10 @@ async def test_list_omnichannel_settings_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_omnichannel_settings_flattened_error_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -1387,7 +1879,7 @@ async def test_list_omnichannel_settings_flattened_error_async(): with pytest.raises(ValueError): await client.list_omnichannel_settings( omnichannelsettings.ListOmnichannelSettingsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1399,8 +1891,8 @@ def test_list_omnichannel_settings_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_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( omnichannelsettings.ListOmnichannelSettingsResponse( @@ -1409,17 +1901,17 @@ def test_list_omnichannel_settings_pager(transport_name: str = "grpc"): omnichannelsettings.OmnichannelSetting(), omnichannelsettings.OmnichannelSetting(), ], - next_page_token='abc', + next_page_token="abc", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[], - next_page_token='def', + next_page_token="def", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ omnichannelsettings.OmnichannelSetting(), ], - next_page_token='ghi', + next_page_token="ghi", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ @@ -1434,11 +1926,11 @@ def test_list_omnichannel_settings_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_omnichannel_settings( + request={}, retry=retry, timeout=timeout ) - pager = client.list_omnichannel_settings(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -1446,8 +1938,11 @@ def test_list_omnichannel_settings_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, omnichannelsettings.OmnichannelSetting) - for i in results) + assert all( + isinstance(i, omnichannelsettings.OmnichannelSetting) for i in results + ) + + def test_list_omnichannel_settings_pages(transport_name: str = "grpc"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1456,8 +1951,8 @@ def test_list_omnichannel_settings_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_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( omnichannelsettings.ListOmnichannelSettingsResponse( @@ -1466,17 +1961,17 @@ def test_list_omnichannel_settings_pages(transport_name: str = "grpc"): omnichannelsettings.OmnichannelSetting(), omnichannelsettings.OmnichannelSetting(), ], - next_page_token='abc', + next_page_token="abc", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[], - next_page_token='def', + next_page_token="def", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ omnichannelsettings.OmnichannelSetting(), ], - next_page_token='ghi', + next_page_token="ghi", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ @@ -1487,9 +1982,10 @@ def test_list_omnichannel_settings_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_omnichannel_settings(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_omnichannel_settings_async_pager(): client = OmnichannelSettingsServiceAsyncClient( @@ -1498,8 +1994,10 @@ async def test_list_omnichannel_settings_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_omnichannel_settings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( omnichannelsettings.ListOmnichannelSettingsResponse( @@ -1508,17 +2006,17 @@ async def test_list_omnichannel_settings_async_pager(): omnichannelsettings.OmnichannelSetting(), omnichannelsettings.OmnichannelSetting(), ], - next_page_token='abc', + next_page_token="abc", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[], - next_page_token='def', + next_page_token="def", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ omnichannelsettings.OmnichannelSetting(), ], - next_page_token='ghi', + next_page_token="ghi", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ @@ -1528,15 +2026,18 @@ async def test_list_omnichannel_settings_async_pager(): ), RuntimeError, ) - async_pager = await client.list_omnichannel_settings(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_omnichannel_settings( + 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, omnichannelsettings.OmnichannelSetting) - for i in responses) + assert all( + isinstance(i, omnichannelsettings.OmnichannelSetting) for i in responses + ) @pytest.mark.asyncio @@ -1547,8 +2048,10 @@ async def test_list_omnichannel_settings_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_omnichannel_settings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( omnichannelsettings.ListOmnichannelSettingsResponse( @@ -1557,17 +2060,17 @@ async def test_list_omnichannel_settings_async_pages(): omnichannelsettings.OmnichannelSetting(), omnichannelsettings.OmnichannelSetting(), ], - next_page_token='abc', + next_page_token="abc", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[], - next_page_token='def', + next_page_token="def", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ omnichannelsettings.OmnichannelSetting(), ], - next_page_token='ghi', + next_page_token="ghi", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ @@ -1580,18 +2083,22 @@ async def test_list_omnichannel_settings_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_omnichannel_settings(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", [ - omnichannelsettings.CreateOmnichannelSettingRequest, - dict, -]) -def test_create_omnichannel_setting(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.CreateOmnichannelSettingRequest, + dict, + ], +) +def test_create_omnichannel_setting(request_type, transport: str = "grpc"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1603,12 +2110,12 @@ def test_create_omnichannel_setting(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, ) response = client.create_omnichannel_setting(request) @@ -1621,8 +2128,8 @@ def test_create_omnichannel_setting(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -1631,28 +2138,31 @@ def test_create_omnichannel_setting_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = OmnichannelSettingsServiceClient( 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 = omnichannelsettings.CreateOmnichannelSettingRequest( - 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.create_omnichannel_setting), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_omnichannel_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == omnichannelsettings.CreateOmnichannelSettingRequest( - parent='parent_value', + parent="parent_value", ) + def test_create_omnichannel_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1667,12 +2177,19 @@ def test_create_omnichannel_setting_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_omnichannel_setting in client._transport._wrapped_methods + assert ( + client._transport.create_omnichannel_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_omnichannel_setting + ] = mock_rpc request = {} client.create_omnichannel_setting(request) @@ -1685,8 +2202,11 @@ def test_create_omnichannel_setting_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_omnichannel_setting_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_omnichannel_setting_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: @@ -1700,12 +2220,17 @@ async def test_create_omnichannel_setting_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_omnichannel_setting in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_omnichannel_setting + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_omnichannel_setting] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_omnichannel_setting + ] = mock_rpc request = {} await client.create_omnichannel_setting(request) @@ -1719,8 +2244,12 @@ async def test_create_omnichannel_setting_async_use_cached_wrapped_rpc(transport assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.CreateOmnichannelSettingRequest): +async def test_create_omnichannel_setting_async( + transport: str = "grpc_asyncio", + request_type=omnichannelsettings.CreateOmnichannelSettingRequest, +): client = OmnichannelSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1732,14 +2261,16 @@ async def test_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting( + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + ) response = await client.create_omnichannel_setting(request) # Establish that the underlying gRPC stub method was called. @@ -1750,8 +2281,8 @@ async def test_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -1759,6 +2290,7 @@ async def test_create_omnichannel_setting_async(transport: str = 'grpc_asyncio', async def test_create_omnichannel_setting_async_from_dict(): await test_create_omnichannel_setting_async(request_type=dict) + def test_create_omnichannel_setting_field_headers(): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1768,12 +2300,12 @@ def test_create_omnichannel_setting_field_headers(): # a field header. Set these to a non-empty value. request = omnichannelsettings.CreateOmnichannelSettingRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: call.return_value = omnichannelsettings.OmnichannelSetting() client.create_omnichannel_setting(request) @@ -1785,9 +2317,9 @@ def test_create_omnichannel_setting_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 @@ -1800,13 +2332,15 @@ async def test_create_omnichannel_setting_field_headers_async(): # a field header. Set these to a non-empty value. request = omnichannelsettings.CreateOmnichannelSettingRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting() + ) await client.create_omnichannel_setting(request) # Establish that the underlying gRPC stub method was called. @@ -1817,9 +2351,9 @@ async def test_create_omnichannel_setting_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_omnichannel_setting_flattened(): @@ -1829,15 +2363,17 @@ def test_create_omnichannel_setting_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_omnichannel_setting( - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + parent="parent_value", + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), ) # Establish that the underlying call was made with the expected @@ -1845,10 +2381,10 @@ def test_create_omnichannel_setting_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + mock_val = omnichannelsettings.OmnichannelSetting(name="name_value") assert arg == mock_val @@ -1862,10 +2398,13 @@ def test_create_omnichannel_setting_flattened_error(): with pytest.raises(ValueError): client.create_omnichannel_setting( omnichannelsettings.CreateOmnichannelSettingRequest(), - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + parent="parent_value", + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), ) + @pytest.mark.asyncio async def test_create_omnichannel_setting_flattened_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -1874,17 +2413,21 @@ async def test_create_omnichannel_setting_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_omnichannel_setting( - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + parent="parent_value", + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), ) # Establish that the underlying call was made with the expected @@ -1892,12 +2435,13 @@ async def test_create_omnichannel_setting_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + mock_val = omnichannelsettings.OmnichannelSetting(name="name_value") assert arg == mock_val + @pytest.mark.asyncio async def test_create_omnichannel_setting_flattened_error_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -1909,16 +2453,21 @@ async def test_create_omnichannel_setting_flattened_error_async(): with pytest.raises(ValueError): await client.create_omnichannel_setting( omnichannelsettings.CreateOmnichannelSettingRequest(), - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + parent="parent_value", + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), ) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.UpdateOmnichannelSettingRequest, - dict, -]) -def test_update_omnichannel_setting(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.UpdateOmnichannelSettingRequest, + dict, + ], +) +def test_update_omnichannel_setting(request_type, transport: str = "grpc"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1930,12 +2479,12 @@ def test_update_omnichannel_setting(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, ) response = client.update_omnichannel_setting(request) @@ -1948,8 +2497,8 @@ def test_update_omnichannel_setting(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -1958,25 +2507,26 @@ def test_update_omnichannel_setting_non_empty_request_with_auto_populated_field( # automatically populated, according to AIP-4235, with non-empty requests. client = OmnichannelSettingsServiceClient( 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 = omnichannelsettings.UpdateOmnichannelSettingRequest( - ) + request = omnichannelsettings.UpdateOmnichannelSettingRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_omnichannel_setting(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == omnichannelsettings.UpdateOmnichannelSettingRequest( - ) + assert args[0] == omnichannelsettings.UpdateOmnichannelSettingRequest() + def test_update_omnichannel_setting_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1992,12 +2542,19 @@ def test_update_omnichannel_setting_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_omnichannel_setting in client._transport._wrapped_methods + assert ( + client._transport.update_omnichannel_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_omnichannel_setting + ] = mock_rpc request = {} client.update_omnichannel_setting(request) @@ -2010,8 +2567,11 @@ def test_update_omnichannel_setting_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_omnichannel_setting_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_omnichannel_setting_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: @@ -2025,12 +2585,17 @@ async def test_update_omnichannel_setting_async_use_cached_wrapped_rpc(transport wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_omnichannel_setting in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_omnichannel_setting + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_omnichannel_setting] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_omnichannel_setting + ] = mock_rpc request = {} await client.update_omnichannel_setting(request) @@ -2044,8 +2609,12 @@ async def test_update_omnichannel_setting_async_use_cached_wrapped_rpc(transport assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): +async def test_update_omnichannel_setting_async( + transport: str = "grpc_asyncio", + request_type=omnichannelsettings.UpdateOmnichannelSettingRequest, +): client = OmnichannelSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2057,14 +2626,16 @@ async def test_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting( + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + ) response = await client.update_omnichannel_setting(request) # Establish that the underlying gRPC stub method was called. @@ -2075,8 +2646,8 @@ async def test_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -2084,6 +2655,7 @@ async def test_update_omnichannel_setting_async(transport: str = 'grpc_asyncio', async def test_update_omnichannel_setting_async_from_dict(): await test_update_omnichannel_setting_async(request_type=dict) + def test_update_omnichannel_setting_field_headers(): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2093,12 +2665,12 @@ def test_update_omnichannel_setting_field_headers(): # a field header. Set these to a non-empty value. request = omnichannelsettings.UpdateOmnichannelSettingRequest() - request.omnichannel_setting.name = 'name_value' + request.omnichannel_setting.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: call.return_value = omnichannelsettings.OmnichannelSetting() client.update_omnichannel_setting(request) @@ -2110,9 +2682,9 @@ def test_update_omnichannel_setting_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'omnichannel_setting.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "omnichannel_setting.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2125,13 +2697,15 @@ async def test_update_omnichannel_setting_field_headers_async(): # a field header. Set these to a non-empty value. request = omnichannelsettings.UpdateOmnichannelSettingRequest() - request.omnichannel_setting.name = 'name_value' + request.omnichannel_setting.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting() + ) await client.update_omnichannel_setting(request) # Establish that the underlying gRPC stub method was called. @@ -2142,9 +2716,9 @@ async def test_update_omnichannel_setting_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'omnichannel_setting.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "omnichannel_setting.name=name_value", + ) in kw["metadata"] def test_update_omnichannel_setting_flattened(): @@ -2154,15 +2728,17 @@ def test_update_omnichannel_setting_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_omnichannel_setting( - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2170,10 +2746,10 @@ def test_update_omnichannel_setting_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + mock_val = omnichannelsettings.OmnichannelSetting(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -2187,10 +2763,13 @@ def test_update_omnichannel_setting_flattened_error(): with pytest.raises(ValueError): client.update_omnichannel_setting( omnichannelsettings.UpdateOmnichannelSettingRequest(), - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_omnichannel_setting_flattened_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -2199,17 +2778,21 @@ async def test_update_omnichannel_setting_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.OmnichannelSetting() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_omnichannel_setting( - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2217,12 +2800,13 @@ async def test_update_omnichannel_setting_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].omnichannel_setting - mock_val = omnichannelsettings.OmnichannelSetting(name='name_value') + mock_val = omnichannelsettings.OmnichannelSetting(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_omnichannel_setting_flattened_error_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -2234,16 +2818,21 @@ async def test_update_omnichannel_setting_flattened_error_async(): with pytest.raises(ValueError): await client.update_omnichannel_setting( omnichannelsettings.UpdateOmnichannelSettingRequest(), - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.RequestInventoryVerificationRequest, - dict, -]) -def test_request_inventory_verification(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.RequestInventoryVerificationRequest, + dict, + ], +) +def test_request_inventory_verification(request_type, transport: str = "grpc"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2255,11 +2844,10 @@ def test_request_inventory_verification(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = omnichannelsettings.RequestInventoryVerificationResponse( - ) + call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() response = client.request_inventory_verification(request) # Establish that the underlying gRPC stub method was called. @@ -2269,7 +2857,9 @@ def test_request_inventory_verification(request_type, transport: str = 'grpc'): assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + assert isinstance( + response, omnichannelsettings.RequestInventoryVerificationResponse + ) def test_request_inventory_verification_non_empty_request_with_auto_populated_field(): @@ -2277,28 +2867,31 @@ def test_request_inventory_verification_non_empty_request_with_auto_populated_fi # automatically populated, according to AIP-4235, with non-empty requests. client = OmnichannelSettingsServiceClient( 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 = omnichannelsettings.RequestInventoryVerificationRequest( - 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.request_inventory_verification), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.request_inventory_verification), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.request_inventory_verification(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == omnichannelsettings.RequestInventoryVerificationRequest( - name='name_value', + name="name_value", ) + def test_request_inventory_verification_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2313,12 +2906,19 @@ def test_request_inventory_verification_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.request_inventory_verification in client._transport._wrapped_methods + assert ( + client._transport.request_inventory_verification + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.request_inventory_verification + ] = mock_rpc request = {} client.request_inventory_verification(request) @@ -2331,8 +2931,11 @@ def test_request_inventory_verification_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_request_inventory_verification_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_request_inventory_verification_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: @@ -2346,12 +2949,17 @@ async def test_request_inventory_verification_async_use_cached_wrapped_rpc(trans wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.request_inventory_verification in client._client._transport._wrapped_methods + assert ( + client._client._transport.request_inventory_verification + 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.request_inventory_verification] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.request_inventory_verification + ] = mock_rpc request = {} await client.request_inventory_verification(request) @@ -2365,8 +2973,12 @@ async def test_request_inventory_verification_async_use_cached_wrapped_rpc(trans assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_request_inventory_verification_async(transport: str = 'grpc_asyncio', request_type=omnichannelsettings.RequestInventoryVerificationRequest): +async def test_request_inventory_verification_async( + transport: str = "grpc_asyncio", + request_type=omnichannelsettings.RequestInventoryVerificationRequest, +): client = OmnichannelSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2378,11 +2990,12 @@ async def test_request_inventory_verification_async(transport: str = 'grpc_async # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.RequestInventoryVerificationResponse() + ) response = await client.request_inventory_verification(request) # Establish that the underlying gRPC stub method was called. @@ -2392,13 +3005,16 @@ async def test_request_inventory_verification_async(transport: str = 'grpc_async assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + assert isinstance( + response, omnichannelsettings.RequestInventoryVerificationResponse + ) @pytest.mark.asyncio async def test_request_inventory_verification_async_from_dict(): await test_request_inventory_verification_async(request_type=dict) + def test_request_inventory_verification_field_headers(): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2408,12 +3024,12 @@ def test_request_inventory_verification_field_headers(): # a field header. Set these to a non-empty value. request = omnichannelsettings.RequestInventoryVerificationRequest() - 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.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() client.request_inventory_verification(request) @@ -2425,9 +3041,9 @@ def test_request_inventory_verification_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 @@ -2440,13 +3056,15 @@ async def test_request_inventory_verification_field_headers_async(): # a field header. Set these to a non-empty value. request = omnichannelsettings.RequestInventoryVerificationRequest() - 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.request_inventory_verification), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) + type(client.transport.request_inventory_verification), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.RequestInventoryVerificationResponse() + ) await client.request_inventory_verification(request) # Establish that the underlying gRPC stub method was called. @@ -2457,9 +3075,9 @@ async def test_request_inventory_verification_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_request_inventory_verification_flattened(): @@ -2469,14 +3087,14 @@ def test_request_inventory_verification_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.request_inventory_verification( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2484,7 +3102,7 @@ def test_request_inventory_verification_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 @@ -2498,9 +3116,10 @@ def test_request_inventory_verification_flattened_error(): with pytest.raises(ValueError): client.request_inventory_verification( omnichannelsettings.RequestInventoryVerificationRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_request_inventory_verification_flattened_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -2509,16 +3128,18 @@ async def test_request_inventory_verification_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.RequestInventoryVerificationResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.request_inventory_verification( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2526,9 +3147,10 @@ async def test_request_inventory_verification_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_request_inventory_verification_flattened_error_async(): client = OmnichannelSettingsServiceAsyncClient( @@ -2540,7 +3162,7 @@ async def test_request_inventory_verification_flattened_error_async(): with pytest.raises(ValueError): await client.request_inventory_verification( omnichannelsettings.RequestInventoryVerificationRequest(), - name='name_value', + name="name_value", ) @@ -2558,12 +3180,19 @@ def test_get_omnichannel_setting_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_omnichannel_setting in client._transport._wrapped_methods + assert ( + client._transport.get_omnichannel_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_omnichannel_setting] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_omnichannel_setting + ] = mock_rpc request = {} client.get_omnichannel_setting(request) @@ -2578,55 +3207,60 @@ def test_get_omnichannel_setting_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.GetOmnichannelSettingRequest): +def test_get_omnichannel_setting_rest_required_fields( + request_type=omnichannelsettings.GetOmnichannelSettingRequest, +): transport_class = transports.OmnichannelSettingsServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_omnichannel_setting._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_omnichannel_setting._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_omnichannel_setting._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_omnichannel_setting._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 = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = omnichannelsettings.OmnichannelSetting() # Mock the http request 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 @@ -2637,24 +3271,24 @@ def test_get_omnichannel_setting_rest_required_fields(request_type=omnichannelse return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_omnichannel_setting(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_omnichannel_setting_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_omnichannel_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_omnichannel_setting_rest_flattened(): @@ -2664,16 +3298,16 @@ def test_get_omnichannel_setting_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 = omnichannelsettings.OmnichannelSetting() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + sample_request = {"name": "accounts/sample1/omnichannelSettings/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2683,7 +3317,7 @@ def test_get_omnichannel_setting_rest_flattened(): # Convert return value to protobuf type return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2693,10 +3327,14 @@ def test_get_omnichannel_setting_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/omnichannelSettings/*}" + % client.transport._host, + args[1], + ) -def test_get_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): +def test_get_omnichannel_setting_rest_flattened_error(transport: str = "rest"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2707,7 +3345,7 @@ def test_get_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_omnichannel_setting( omnichannelsettings.GetOmnichannelSettingRequest(), - name='name_value', + name="name_value", ) @@ -2725,12 +3363,19 @@ def test_list_omnichannel_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_omnichannel_settings in client._transport._wrapped_methods + assert ( + client._transport.list_omnichannel_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_omnichannel_settings] = 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_omnichannel_settings + ] = mock_rpc request = {} client.list_omnichannel_settings(request) @@ -2745,57 +3390,67 @@ def test_list_omnichannel_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_omnichannel_settings_rest_required_fields(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): +def test_list_omnichannel_settings_rest_required_fields( + request_type=omnichannelsettings.ListOmnichannelSettingsRequest, +): transport_class = transports.OmnichannelSettingsServiceRestTransport 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_omnichannel_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_omnichannel_settings._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_omnichannel_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_omnichannel_settings._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 = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = omnichannelsettings.ListOmnichannelSettingsResponse() # Mock the http request 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 @@ -2803,27 +3458,37 @@ def test_list_omnichannel_settings_rest_required_fields(request_type=omnichannel response_value.status_code = 200 # Convert return value to protobuf type - return_value = omnichannelsettings.ListOmnichannelSettingsResponse.pb(return_value) + return_value = omnichannelsettings.ListOmnichannelSettingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_omnichannel_settings(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_omnichannel_settings_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_omnichannel_settings._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_omnichannel_settings_rest_flattened(): @@ -2833,16 +3498,16 @@ def test_list_omnichannel_settings_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 = omnichannelsettings.ListOmnichannelSettingsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -2850,9 +3515,11 @@ def test_list_omnichannel_settings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = omnichannelsettings.ListOmnichannelSettingsResponse.pb(return_value) + return_value = omnichannelsettings.ListOmnichannelSettingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2862,10 +3529,14 @@ def test_list_omnichannel_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/omnichannelSettings" + % client.transport._host, + args[1], + ) -def test_list_omnichannel_settings_rest_flattened_error(transport: str = 'rest'): +def test_list_omnichannel_settings_rest_flattened_error(transport: str = "rest"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2876,20 +3547,20 @@ def test_list_omnichannel_settings_rest_flattened_error(transport: str = 'rest') with pytest.raises(ValueError): client.list_omnichannel_settings( omnichannelsettings.ListOmnichannelSettingsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_omnichannel_settings_rest_pager(transport: str = 'rest'): +def test_list_omnichannel_settings_rest_pager(transport: str = "rest"): client = OmnichannelSettingsServiceClient( 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 = ( omnichannelsettings.ListOmnichannelSettingsResponse( @@ -2898,17 +3569,17 @@ def test_list_omnichannel_settings_rest_pager(transport: str = 'rest'): omnichannelsettings.OmnichannelSetting(), omnichannelsettings.OmnichannelSetting(), ], - next_page_token='abc', + next_page_token="abc", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[], - next_page_token='def', + next_page_token="def", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ omnichannelsettings.OmnichannelSetting(), ], - next_page_token='ghi', + next_page_token="ghi", ), omnichannelsettings.ListOmnichannelSettingsResponse( omnichannel_settings=[ @@ -2921,24 +3592,28 @@ def test_list_omnichannel_settings_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(omnichannelsettings.ListOmnichannelSettingsResponse.to_json(x) for x in response) + response = tuple( + omnichannelsettings.ListOmnichannelSettingsResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_omnichannel_settings(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, omnichannelsettings.OmnichannelSetting) - for i in results) + assert all( + isinstance(i, omnichannelsettings.OmnichannelSetting) for i in results + ) pages = list(client.list_omnichannel_settings(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 @@ -2956,12 +3631,19 @@ def test_create_omnichannel_setting_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_omnichannel_setting in client._transport._wrapped_methods + assert ( + client._transport.create_omnichannel_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_omnichannel_setting] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_omnichannel_setting + ] = mock_rpc request = {} client.create_omnichannel_setting(request) @@ -2976,57 +3658,62 @@ def test_create_omnichannel_setting_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): +def test_create_omnichannel_setting_rest_required_fields( + request_type=omnichannelsettings.CreateOmnichannelSettingRequest, +): transport_class = transports.OmnichannelSettingsServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_omnichannel_setting._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_omnichannel_setting._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_omnichannel_setting._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_omnichannel_setting._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 = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = omnichannelsettings.OmnichannelSetting() # Mock the http request 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() @@ -3036,24 +3723,32 @@ def test_create_omnichannel_setting_rest_required_fields(request_type=omnichanne return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_omnichannel_setting(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_omnichannel_setting_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_omnichannel_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "omnichannelSetting", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "omnichannelSetting", + ) + ) + ) def test_create_omnichannel_setting_rest_flattened(): @@ -3063,17 +3758,19 @@ def test_create_omnichannel_setting_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 = omnichannelsettings.OmnichannelSetting() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + parent="parent_value", + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), ) mock_args.update(sample_request) @@ -3083,7 +3780,7 @@ def test_create_omnichannel_setting_rest_flattened(): # Convert return value to protobuf type return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3093,10 +3790,14 @@ def test_create_omnichannel_setting_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/omnichannelSettings" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/omnichannelSettings" + % client.transport._host, + args[1], + ) -def test_create_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): +def test_create_omnichannel_setting_rest_flattened_error(transport: str = "rest"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3107,8 +3808,10 @@ def test_create_omnichannel_setting_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.create_omnichannel_setting( omnichannelsettings.CreateOmnichannelSettingRequest(), - parent='parent_value', - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), + parent="parent_value", + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), ) @@ -3126,12 +3829,19 @@ def test_update_omnichannel_setting_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_omnichannel_setting in client._transport._wrapped_methods + assert ( + client._transport.update_omnichannel_setting + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_omnichannel_setting] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_omnichannel_setting + ] = mock_rpc request = {} client.update_omnichannel_setting(request) @@ -3146,54 +3856,59 @@ def test_update_omnichannel_setting_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_update_omnichannel_setting_rest_required_fields(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): +def test_update_omnichannel_setting_rest_required_fields( + request_type=omnichannelsettings.UpdateOmnichannelSettingRequest, +): transport_class = transports.OmnichannelSettingsServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_omnichannel_setting._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_omnichannel_setting._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_omnichannel_setting._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = omnichannelsettings.OmnichannelSetting() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3203,24 +3918,32 @@ def test_update_omnichannel_setting_rest_required_fields(request_type=omnichanne return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_omnichannel_setting(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_omnichannel_setting_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_omnichannel_setting._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("omnichannelSetting", "updateMask", ))) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "omnichannelSetting", + "updateMask", + ) + ) + ) def test_update_omnichannel_setting_rest_flattened(): @@ -3230,17 +3953,23 @@ def test_update_omnichannel_setting_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 = omnichannelsettings.OmnichannelSetting() # get arguments that satisfy an http rule for this method - sample_request = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} + sample_request = { + "omnichannel_setting": { + "name": "accounts/sample1/omnichannelSettings/sample2" + } + } # get truthy value for each flattened field mock_args = dict( - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -3250,7 +3979,7 @@ def test_update_omnichannel_setting_rest_flattened(): # Convert return value to protobuf type return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3260,10 +3989,14 @@ def test_update_omnichannel_setting_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{omnichannel_setting.name=accounts/*/omnichannelSettings/*}" + % client.transport._host, + args[1], + ) -def test_update_omnichannel_setting_rest_flattened_error(transport: str = 'rest'): +def test_update_omnichannel_setting_rest_flattened_error(transport: str = "rest"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3274,8 +4007,10 @@ def test_update_omnichannel_setting_rest_flattened_error(transport: str = 'rest' with pytest.raises(ValueError): client.update_omnichannel_setting( omnichannelsettings.UpdateOmnichannelSettingRequest(), - omnichannel_setting=omnichannelsettings.OmnichannelSetting(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + omnichannel_setting=omnichannelsettings.OmnichannelSetting( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -3293,12 +4028,19 @@ def test_request_inventory_verification_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.request_inventory_verification in client._transport._wrapped_methods + assert ( + client._transport.request_inventory_verification + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.request_inventory_verification] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.request_inventory_verification + ] = mock_rpc request = {} client.request_inventory_verification(request) @@ -3313,84 +4055,93 @@ def test_request_inventory_verification_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_request_inventory_verification_rest_required_fields(request_type=omnichannelsettings.RequestInventoryVerificationRequest): +def test_request_inventory_verification_rest_required_fields( + request_type=omnichannelsettings.RequestInventoryVerificationRequest, +): transport_class = transports.OmnichannelSettingsServiceRestTransport 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()).request_inventory_verification._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).request_inventory_verification._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()).request_inventory_verification._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).request_inventory_verification._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 = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = omnichannelsettings.RequestInventoryVerificationResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = omnichannelsettings.RequestInventoryVerificationResponse.pb(return_value) + return_value = omnichannelsettings.RequestInventoryVerificationResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.request_inventory_verification(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_request_inventory_verification_rest_unset_required_fields(): - transport = transports.OmnichannelSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OmnichannelSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.request_inventory_verification._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + unset_fields = transport.request_inventory_verification._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("name",))) def test_request_inventory_verification_rest_flattened(): @@ -3400,16 +4151,16 @@ def test_request_inventory_verification_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 = omnichannelsettings.RequestInventoryVerificationResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + sample_request = {"name": "accounts/sample1/omnichannelSettings/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -3417,9 +4168,11 @@ def test_request_inventory_verification_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = omnichannelsettings.RequestInventoryVerificationResponse.pb(return_value) + return_value = omnichannelsettings.RequestInventoryVerificationResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3429,10 +4182,14 @@ def test_request_inventory_verification_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/omnichannelSettings/*}:requestInventoryVerification" + % client.transport._host, + args[1], + ) -def test_request_inventory_verification_rest_flattened_error(transport: str = 'rest'): +def test_request_inventory_verification_rest_flattened_error(transport: str = "rest"): client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3443,7 +4200,7 @@ def test_request_inventory_verification_rest_flattened_error(transport: str = 'r with pytest.raises(ValueError): client.request_inventory_verification( omnichannelsettings.RequestInventoryVerificationRequest(), - name='name_value', + name="name_value", ) @@ -3485,8 +4242,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = OmnichannelSettingsServiceClient( - 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. @@ -3508,6 +4264,7 @@ def test_transport_instance(): client = OmnichannelSettingsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.OmnichannelSettingsServiceGrpcTransport( @@ -3522,18 +4279,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.OmnichannelSettingsServiceGrpcTransport, - transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, - transports.OmnichannelSettingsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + transports.OmnichannelSettingsServiceRestTransport, + ], +) 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 = OmnichannelSettingsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3543,8 +4305,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3559,8 +4320,8 @@ def test_get_omnichannel_setting_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: call.return_value = omnichannelsettings.OmnichannelSetting() client.get_omnichannel_setting(request=None) @@ -3582,8 +4343,8 @@ def test_list_omnichannel_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: call.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() client.list_omnichannel_settings(request=None) @@ -3605,8 +4366,8 @@ def test_create_omnichannel_setting_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: call.return_value = omnichannelsettings.OmnichannelSetting() client.create_omnichannel_setting(request=None) @@ -3628,8 +4389,8 @@ def test_update_omnichannel_setting_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: call.return_value = omnichannelsettings.OmnichannelSetting() client.update_omnichannel_setting(request=None) @@ -3651,8 +4412,8 @@ def test_request_inventory_verification_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: call.return_value = omnichannelsettings.RequestInventoryVerificationResponse() client.request_inventory_verification(request=None) @@ -3665,16 +4426,15 @@ def test_request_inventory_verification_empty_call_grpc(): def test_transport_kind_grpc_asyncio(): - transport = OmnichannelSettingsServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = OmnichannelSettingsServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = OmnichannelSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3690,14 +4450,16 @@ async def test_get_omnichannel_setting_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting( + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + ) await client.get_omnichannel_setting(request=None) # Establish that the underlying stub method was called. @@ -3719,12 +4481,14 @@ async def test_list_omnichannel_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.ListOmnichannelSettingsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_omnichannel_settings(request=None) # Establish that the underlying stub method was called. @@ -3746,14 +4510,16 @@ async def test_create_omnichannel_setting_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting( + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + ) await client.create_omnichannel_setting(request=None) # Establish that the underlying stub method was called. @@ -3775,14 +4541,16 @@ async def test_update_omnichannel_setting_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.OmnichannelSetting( + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + ) + ) await client.update_omnichannel_setting(request=None) # Establish that the underlying stub method was called. @@ -3804,11 +4572,12 @@ async def test_request_inventory_verification_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(omnichannelsettings.RequestInventoryVerificationResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + omnichannelsettings.RequestInventoryVerificationResponse() + ) await client.request_inventory_verification(request=None) # Establish that the underlying stub method was called. @@ -3826,20 +4595,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.GetOmnichannelSettingRequest): +def test_get_omnichannel_setting_rest_bad_request( + request_type=omnichannelsettings.GetOmnichannelSettingRequest, +): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + request_init = {"name": "accounts/sample1/omnichannelSettings/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() @@ -3848,27 +4620,29 @@ def test_get_omnichannel_setting_rest_bad_request(request_type=omnichannelsettin client.get_omnichannel_setting(request) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.GetOmnichannelSettingRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.GetOmnichannelSettingRequest, + dict, + ], +) def test_get_omnichannel_setting_rest_call_success(request_type): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + request_init = {"name": "accounts/sample1/omnichannelSettings/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 = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, ) # Wrap the value into a proper Response obj @@ -3878,15 +4652,15 @@ def test_get_omnichannel_setting_rest_call_success(request_type): # Convert return value to protobuf type return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_omnichannel_setting(request) # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -3894,19 +4668,32 @@ def test_get_omnichannel_setting_rest_call_success(request_type): def test_get_omnichannel_setting_rest_interceptors(null_interceptor): transport = transports.OmnichannelSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OmnichannelSettingsServiceRestInterceptor(), + ) client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_get_omnichannel_setting_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_get_omnichannel_setting") 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.OmnichannelSettingsServiceRestInterceptor, + "post_get_omnichannel_setting", + ) as post, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "post_get_omnichannel_setting_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "pre_get_omnichannel_setting", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.GetOmnichannelSettingRequest.pb(omnichannelsettings.GetOmnichannelSettingRequest()) + pb_message = omnichannelsettings.GetOmnichannelSettingRequest.pb( + omnichannelsettings.GetOmnichannelSettingRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3917,39 +4704,53 @@ def test_get_omnichannel_setting_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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + return_value = omnichannelsettings.OmnichannelSetting.to_json( + omnichannelsettings.OmnichannelSetting() + ) req.return_value.content = return_value request = omnichannelsettings.GetOmnichannelSettingRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = omnichannelsettings.OmnichannelSetting() - post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + post_with_metadata.return_value = ( + omnichannelsettings.OmnichannelSetting(), + metadata, + ) - client.get_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_omnichannel_setting( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_omnichannel_settings_rest_bad_request(request_type=omnichannelsettings.ListOmnichannelSettingsRequest): +def test_list_omnichannel_settings_rest_bad_request( + request_type=omnichannelsettings.ListOmnichannelSettingsRequest, +): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3958,25 +4759,27 @@ def test_list_omnichannel_settings_rest_bad_request(request_type=omnichannelsett client.list_omnichannel_settings(request) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.ListOmnichannelSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.ListOmnichannelSettingsRequest, + dict, + ], +) def test_list_omnichannel_settings_rest_call_success(request_type): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = omnichannelsettings.ListOmnichannelSettingsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -3984,35 +4787,50 @@ def test_list_omnichannel_settings_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = omnichannelsettings.ListOmnichannelSettingsResponse.pb(return_value) + return_value = omnichannelsettings.ListOmnichannelSettingsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_omnichannel_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListOmnichannelSettingsPager) - 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_omnichannel_settings_rest_interceptors(null_interceptor): transport = transports.OmnichannelSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OmnichannelSettingsServiceRestInterceptor(), + ) client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_list_omnichannel_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_list_omnichannel_settings") 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.OmnichannelSettingsServiceRestInterceptor, + "post_list_omnichannel_settings", + ) as post, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "post_list_omnichannel_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "pre_list_omnichannel_settings", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.ListOmnichannelSettingsRequest.pb(omnichannelsettings.ListOmnichannelSettingsRequest()) + pb_message = omnichannelsettings.ListOmnichannelSettingsRequest.pb( + omnichannelsettings.ListOmnichannelSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4023,39 +4841,53 @@ def test_list_omnichannel_settings_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 = omnichannelsettings.ListOmnichannelSettingsResponse.to_json(omnichannelsettings.ListOmnichannelSettingsResponse()) + return_value = omnichannelsettings.ListOmnichannelSettingsResponse.to_json( + omnichannelsettings.ListOmnichannelSettingsResponse() + ) req.return_value.content = return_value request = omnichannelsettings.ListOmnichannelSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = omnichannelsettings.ListOmnichannelSettingsResponse() - post_with_metadata.return_value = omnichannelsettings.ListOmnichannelSettingsResponse(), metadata + post_with_metadata.return_value = ( + omnichannelsettings.ListOmnichannelSettingsResponse(), + metadata, + ) - client.list_omnichannel_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_omnichannel_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_create_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.CreateOmnichannelSettingRequest): +def test_create_omnichannel_setting_rest_bad_request( + request_type=omnichannelsettings.CreateOmnichannelSettingRequest, +): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -4064,25 +4896,48 @@ def test_create_omnichannel_setting_rest_bad_request(request_type=omnichannelset client.create_omnichannel_setting(request) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.CreateOmnichannelSettingRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.CreateOmnichannelSettingRequest, + dict, + ], +) def test_create_omnichannel_setting_rest_call_success(request_type): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["omnichannel_setting"] = {'name': 'name_value', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 1}} + request_init = {"parent": "accounts/sample1"} + request_init["omnichannel_setting"] = { + "name": "name_value", + "region_code": "region_code_value", + "lsf_type": 1, + "in_stock": {"uri": "uri_value", "state": 1}, + "pickup": {"uri": "uri_value", "state": 1}, + "lfp_link": { + "lfp_provider": "lfp_provider_value", + "external_account_id": "external_account_id_value", + "state": 1, + }, + "odo": {"uri": "uri_value", "state": 1}, + "about": {"uri": "uri_value", "state": 1}, + "inventory_verification": { + "state": 1, + "contact": "contact_value", + "contact_email": "contact_email_value", + "contact_state": 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 = omnichannelsettings.CreateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] + test_field = omnichannelsettings.CreateOmnichannelSettingRequest.meta.fields[ + "omnichannel_setting" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -4096,7 +4951,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 @@ -4110,7 +4965,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["omnichannel_setting"].items(): # pragma: NO COVER + for field, value in request_init["omnichannel_setting"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4125,12 +4980,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") @@ -4143,12 +5002,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 = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, ) # Wrap the value into a proper Response obj @@ -4158,15 +5017,15 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_omnichannel_setting(request) # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -4174,19 +5033,32 @@ def get_message_fields(field): def test_create_omnichannel_setting_rest_interceptors(null_interceptor): transport = transports.OmnichannelSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OmnichannelSettingsServiceRestInterceptor(), + ) client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_create_omnichannel_setting_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_create_omnichannel_setting") 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.OmnichannelSettingsServiceRestInterceptor, + "post_create_omnichannel_setting", + ) as post, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "post_create_omnichannel_setting_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "pre_create_omnichannel_setting", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.CreateOmnichannelSettingRequest.pb(omnichannelsettings.CreateOmnichannelSettingRequest()) + pb_message = omnichannelsettings.CreateOmnichannelSettingRequest.pb( + omnichannelsettings.CreateOmnichannelSettingRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4197,39 +5069,55 @@ def test_create_omnichannel_setting_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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + return_value = omnichannelsettings.OmnichannelSetting.to_json( + omnichannelsettings.OmnichannelSetting() + ) req.return_value.content = return_value request = omnichannelsettings.CreateOmnichannelSettingRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = omnichannelsettings.OmnichannelSetting() - post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + post_with_metadata.return_value = ( + omnichannelsettings.OmnichannelSetting(), + metadata, + ) - client.create_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_omnichannel_setting( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_update_omnichannel_setting_rest_bad_request(request_type=omnichannelsettings.UpdateOmnichannelSettingRequest): +def test_update_omnichannel_setting_rest_bad_request( + request_type=omnichannelsettings.UpdateOmnichannelSettingRequest, +): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} + request_init = { + "omnichannel_setting": {"name": "accounts/sample1/omnichannelSettings/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() @@ -4238,25 +5126,50 @@ def test_update_omnichannel_setting_rest_bad_request(request_type=omnichannelset client.update_omnichannel_setting(request) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.UpdateOmnichannelSettingRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.UpdateOmnichannelSettingRequest, + dict, + ], +) def test_update_omnichannel_setting_rest_call_success(request_type): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'omnichannel_setting': {'name': 'accounts/sample1/omnichannelSettings/sample2'}} - request_init["omnichannel_setting"] = {'name': 'accounts/sample1/omnichannelSettings/sample2', 'region_code': 'region_code_value', 'lsf_type': 1, 'in_stock': {'uri': 'uri_value', 'state': 1}, 'pickup': {'uri': 'uri_value', 'state': 1}, 'lfp_link': {'lfp_provider': 'lfp_provider_value', 'external_account_id': 'external_account_id_value', 'state': 1}, 'odo': {'uri': 'uri_value', 'state': 1}, 'about': {'uri': 'uri_value', 'state': 1}, 'inventory_verification': {'state': 1, 'contact': 'contact_value', 'contact_email': 'contact_email_value', 'contact_state': 1}} + request_init = { + "omnichannel_setting": {"name": "accounts/sample1/omnichannelSettings/sample2"} + } + request_init["omnichannel_setting"] = { + "name": "accounts/sample1/omnichannelSettings/sample2", + "region_code": "region_code_value", + "lsf_type": 1, + "in_stock": {"uri": "uri_value", "state": 1}, + "pickup": {"uri": "uri_value", "state": 1}, + "lfp_link": { + "lfp_provider": "lfp_provider_value", + "external_account_id": "external_account_id_value", + "state": 1, + }, + "odo": {"uri": "uri_value", "state": 1}, + "about": {"uri": "uri_value", "state": 1}, + "inventory_verification": { + "state": 1, + "contact": "contact_value", + "contact_email": "contact_email_value", + "contact_state": 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 = omnichannelsettings.UpdateOmnichannelSettingRequest.meta.fields["omnichannel_setting"] + test_field = omnichannelsettings.UpdateOmnichannelSettingRequest.meta.fields[ + "omnichannel_setting" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -4270,7 +5183,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 @@ -4284,7 +5197,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["omnichannel_setting"].items(): # pragma: NO COVER + for field, value in request_init["omnichannel_setting"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4299,12 +5212,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") @@ -4317,12 +5234,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 = omnichannelsettings.OmnichannelSetting( - name='name_value', - region_code='region_code_value', - lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, + name="name_value", + region_code="region_code_value", + lsf_type=omnichannelsettings.OmnichannelSetting.LsfType.GHLSF, ) # Wrap the value into a proper Response obj @@ -4332,15 +5249,15 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = omnichannelsettings.OmnichannelSetting.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_omnichannel_setting(request) # Establish that the response is the type that we expect. assert isinstance(response, omnichannelsettings.OmnichannelSetting) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.lsf_type == omnichannelsettings.OmnichannelSetting.LsfType.GHLSF @@ -4348,19 +5265,32 @@ def get_message_fields(field): def test_update_omnichannel_setting_rest_interceptors(null_interceptor): transport = transports.OmnichannelSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OmnichannelSettingsServiceRestInterceptor(), + ) client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_update_omnichannel_setting_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_update_omnichannel_setting") 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.OmnichannelSettingsServiceRestInterceptor, + "post_update_omnichannel_setting", + ) as post, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "post_update_omnichannel_setting_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "pre_update_omnichannel_setting", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.UpdateOmnichannelSettingRequest.pb(omnichannelsettings.UpdateOmnichannelSettingRequest()) + pb_message = omnichannelsettings.UpdateOmnichannelSettingRequest.pb( + omnichannelsettings.UpdateOmnichannelSettingRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4371,39 +5301,53 @@ def test_update_omnichannel_setting_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 = omnichannelsettings.OmnichannelSetting.to_json(omnichannelsettings.OmnichannelSetting()) + return_value = omnichannelsettings.OmnichannelSetting.to_json( + omnichannelsettings.OmnichannelSetting() + ) req.return_value.content = return_value request = omnichannelsettings.UpdateOmnichannelSettingRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = omnichannelsettings.OmnichannelSetting() - post_with_metadata.return_value = omnichannelsettings.OmnichannelSetting(), metadata + post_with_metadata.return_value = ( + omnichannelsettings.OmnichannelSetting(), + metadata, + ) - client.update_omnichannel_setting(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_omnichannel_setting( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_request_inventory_verification_rest_bad_request(request_type=omnichannelsettings.RequestInventoryVerificationRequest): +def test_request_inventory_verification_rest_bad_request( + request_type=omnichannelsettings.RequestInventoryVerificationRequest, +): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + request_init = {"name": "accounts/sample1/omnichannelSettings/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() @@ -4412,59 +5356,77 @@ def test_request_inventory_verification_rest_bad_request(request_type=omnichanne client.request_inventory_verification(request) -@pytest.mark.parametrize("request_type", [ - omnichannelsettings.RequestInventoryVerificationRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + omnichannelsettings.RequestInventoryVerificationRequest, + dict, + ], +) def test_request_inventory_verification_rest_call_success(request_type): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/omnichannelSettings/sample2'} + request_init = {"name": "accounts/sample1/omnichannelSettings/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 = omnichannelsettings.RequestInventoryVerificationResponse( - ) + return_value = omnichannelsettings.RequestInventoryVerificationResponse() # 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 = omnichannelsettings.RequestInventoryVerificationResponse.pb(return_value) + return_value = omnichannelsettings.RequestInventoryVerificationResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.request_inventory_verification(request) # Establish that the response is the type that we expect. - assert isinstance(response, omnichannelsettings.RequestInventoryVerificationResponse) + assert isinstance( + response, omnichannelsettings.RequestInventoryVerificationResponse + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_request_inventory_verification_rest_interceptors(null_interceptor): transport = transports.OmnichannelSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OmnichannelSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OmnichannelSettingsServiceRestInterceptor(), + ) client = OmnichannelSettingsServiceClient(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.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification") as post, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "post_request_inventory_verification_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OmnichannelSettingsServiceRestInterceptor, "pre_request_inventory_verification") 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.OmnichannelSettingsServiceRestInterceptor, + "post_request_inventory_verification", + ) as post, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "post_request_inventory_verification_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OmnichannelSettingsServiceRestInterceptor, + "pre_request_inventory_verification", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = omnichannelsettings.RequestInventoryVerificationRequest.pb(omnichannelsettings.RequestInventoryVerificationRequest()) + pb_message = omnichannelsettings.RequestInventoryVerificationRequest.pb( + omnichannelsettings.RequestInventoryVerificationRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4475,28 +5437,39 @@ def test_request_inventory_verification_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 = omnichannelsettings.RequestInventoryVerificationResponse.to_json(omnichannelsettings.RequestInventoryVerificationResponse()) + return_value = omnichannelsettings.RequestInventoryVerificationResponse.to_json( + omnichannelsettings.RequestInventoryVerificationResponse() + ) req.return_value.content = return_value request = omnichannelsettings.RequestInventoryVerificationRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = omnichannelsettings.RequestInventoryVerificationResponse() - post_with_metadata.return_value = omnichannelsettings.RequestInventoryVerificationResponse(), metadata + post_with_metadata.return_value = ( + omnichannelsettings.RequestInventoryVerificationResponse(), + metadata, + ) - client.request_inventory_verification(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.request_inventory_verification( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -4511,8 +5484,8 @@ def test_get_omnichannel_setting_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_omnichannel_setting), - '__call__') as call: + type(client.transport.get_omnichannel_setting), "__call__" + ) as call: client.get_omnichannel_setting(request=None) # Establish that the underlying stub method was called. @@ -4533,8 +5506,8 @@ def test_list_omnichannel_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_omnichannel_settings), - '__call__') as call: + type(client.transport.list_omnichannel_settings), "__call__" + ) as call: client.list_omnichannel_settings(request=None) # Establish that the underlying stub method was called. @@ -4555,8 +5528,8 @@ def test_create_omnichannel_setting_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_omnichannel_setting), - '__call__') as call: + type(client.transport.create_omnichannel_setting), "__call__" + ) as call: client.create_omnichannel_setting(request=None) # Establish that the underlying stub method was called. @@ -4577,8 +5550,8 @@ def test_update_omnichannel_setting_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.update_omnichannel_setting), - '__call__') as call: + type(client.transport.update_omnichannel_setting), "__call__" + ) as call: client.update_omnichannel_setting(request=None) # Establish that the underlying stub method was called. @@ -4599,8 +5572,8 @@ def test_request_inventory_verification_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.request_inventory_verification), - '__call__') as call: + type(client.transport.request_inventory_verification), "__call__" + ) as call: client.request_inventory_verification(request=None) # Establish that the underlying stub method was called. @@ -4621,18 +5594,21 @@ def test_transport_grpc_default(): transports.OmnichannelSettingsServiceGrpcTransport, ) + def test_omnichannel_settings_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.OmnichannelSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_omnichannel_settings_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.OmnichannelSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4641,11 +5617,11 @@ def test_omnichannel_settings_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_omnichannel_setting', - 'list_omnichannel_settings', - 'create_omnichannel_setting', - 'update_omnichannel_setting', - 'request_inventory_verification', + "get_omnichannel_setting", + "list_omnichannel_settings", + "create_omnichannel_setting", + "update_omnichannel_setting", + "request_inventory_verification", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4656,7 +5632,7 @@ def test_omnichannel_settings_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4665,25 +5641,30 @@ def test_omnichannel_settings_service_base_transport(): def test_omnichannel_settings_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_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._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_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OmnichannelSettingsServiceTransport( 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_omnichannel_settings_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_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.omnichannel_settings_service.transports.OmnichannelSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OmnichannelSettingsServiceTransport() @@ -4692,14 +5673,12 @@ def test_omnichannel_settings_service_base_transport_with_adc(): def test_omnichannel_settings_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) OmnichannelSettingsServiceClient() 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, ) @@ -4714,12 +5693,12 @@ def test_omnichannel_settings_service_auth_adc(): def test_omnichannel_settings_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", ) @@ -4733,48 +5712,47 @@ def test_omnichannel_settings_service_transport_auth_adc(transport_class): ], ) def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, grpc_helpers), - (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_omnichannel_settings_service_transport_create_channel(transport_class, grpc_helpers): +def test_omnichannel_settings_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, @@ -4785,9 +5763,15 @@ def test_omnichannel_settings_service_transport_create_channel(transport_class, ) -@pytest.mark.parametrize("transport_class", [transports.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + ], +) def test_omnichannel_settings_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -4797,7 +5781,7 @@ def test_omnichannel_settings_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", @@ -4818,62 +5802,80 @@ def test_omnichannel_settings_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_omnichannel_settings_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.OmnichannelSettingsServiceRestTransport ( - 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.OmnichannelSettingsServiceRestTransport( + 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_omnichannel_settings_service_host_no_port(transport_name): client = OmnichannelSettingsServiceClient( 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_omnichannel_settings_service_host_with_port(transport_name): client = OmnichannelSettingsServiceClient( 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", -]) -def test_omnichannel_settings_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_omnichannel_settings_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = OmnichannelSettingsServiceClient( @@ -4899,8 +5901,10 @@ def test_omnichannel_settings_service_client_transport_session_collision(transpo session1 = client1.transport.request_inventory_verification._session session2 = client2.transport.request_inventory_verification._session assert session1 != session2 + + def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport( @@ -4913,7 +5917,7 @@ def test_omnichannel_settings_service_grpc_transport_channel(): def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcAsyncIOTransport( @@ -4927,12 +5931,22 @@ def test_omnichannel_settings_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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + ], +) def test_omnichannel_settings_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 @@ -4941,7 +5955,7 @@ def test_omnichannel_settings_service_transport_channel_mtls_with_client_cert_so 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", @@ -4971,17 +5985,23 @@ def test_omnichannel_settings_service_transport_channel_mtls_with_client_cert_so # 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.OmnichannelSettingsServiceGrpcTransport, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport]) -def test_omnichannel_settings_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.OmnichannelSettingsServiceGrpcTransport, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_omnichannel_settings_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() @@ -5011,7 +6031,9 @@ def test_omnichannel_settings_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = OmnichannelSettingsServiceClient.account_path(account) assert expected == actual @@ -5026,11 +6048,17 @@ def test_parse_account_path(): actual = OmnichannelSettingsServiceClient.parse_account_path(path) assert expected == actual + def test_omnichannel_setting_path(): account = "whelk" omnichannel_setting = "octopus" - expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format(account=account, omnichannel_setting=omnichannel_setting, ) - actual = OmnichannelSettingsServiceClient.omnichannel_setting_path(account, omnichannel_setting) + expected = "accounts/{account}/omnichannelSettings/{omnichannel_setting}".format( + account=account, + omnichannel_setting=omnichannel_setting, + ) + actual = OmnichannelSettingsServiceClient.omnichannel_setting_path( + account, omnichannel_setting + ) assert expected == actual @@ -5045,10 +6073,15 @@ def test_parse_omnichannel_setting_path(): actual = OmnichannelSettingsServiceClient.parse_omnichannel_setting_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OmnichannelSettingsServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = OmnichannelSettingsServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -5062,9 +6095,12 @@ def test_parse_common_billing_account_path(): actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_folder_path(folder) assert expected == actual @@ -5079,9 +6115,12 @@ def test_parse_common_folder_path(): actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_organization_path(organization) assert expected == actual @@ -5096,9 +6135,12 @@ def test_parse_common_organization_path(): actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_project_path(project) assert expected == actual @@ -5113,10 +6155,14 @@ def test_parse_common_project_path(): actual = OmnichannelSettingsServiceClient.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 = OmnichannelSettingsServiceClient.common_location_path(project, location) assert expected == actual @@ -5136,14 +6182,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.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.OmnichannelSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = OmnichannelSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.OmnichannelSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.OmnichannelSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = OmnichannelSettingsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5154,10 +6204,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = OmnichannelSettingsServiceClient( - 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() @@ -5166,10 +6217,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = OmnichannelSettingsServiceAsyncClient( - 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() @@ -5177,10 +6229,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = OmnichannelSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() @@ -5188,13 +6241,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = OmnichannelSettingsServiceClient( - 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: @@ -5203,10 +6255,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (OmnichannelSettingsServiceClient, transports.OmnichannelSettingsServiceGrpcTransport), - (OmnichannelSettingsServiceAsyncClient, transports.OmnichannelSettingsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + OmnichannelSettingsServiceClient, + transports.OmnichannelSettingsServiceGrpcTransport, + ), + ( + OmnichannelSettingsServiceAsyncClient, + transports.OmnichannelSettingsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5221,7 +6283,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py similarity index 66% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py index fba11b1b3556..5b17d2f7b2d9 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_online_return_policy_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,48 +22,48 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format +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.shopping.merchant_accounts_v1.services.online_return_policy_service import OnlineReturnPolicyServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.online_return_policy_service import OnlineReturnPolicyServiceClient -from google.shopping.merchant_accounts_v1.services.online_return_policy_service import pagers -from google.shopping.merchant_accounts_v1.services.online_return_policy_service import transports -from google.shopping.merchant_accounts_v1.types import online_return_policy -from google.shopping.merchant_accounts_v1.types import online_return_policy as gsma_online_return_policy from google.shopping.type.types import types from google.type import date_pb2 # type: ignore -import google.auth - +from google.shopping.merchant_accounts_v1.services.online_return_policy_service import ( + OnlineReturnPolicyServiceAsyncClient, + OnlineReturnPolicyServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import ( + online_return_policy as gsma_online_return_policy, +) +from google.shopping.merchant_accounts_v1.types import online_return_policy CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -77,9 +78,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -87,17 +90,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -108,101 +121,249 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(None) is None - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OnlineReturnPolicyServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + OnlineReturnPolicyServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + assert OnlineReturnPolicyServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (True, "auto", None) + assert OnlineReturnPolicyServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + assert OnlineReturnPolicyServiceClient._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: OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "never", None) + assert OnlineReturnPolicyServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "always", None) + assert OnlineReturnPolicyServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", None) + assert OnlineReturnPolicyServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, False) is None - assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + OnlineReturnPolicyServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + OnlineReturnPolicyServiceClient._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 ( + OnlineReturnPolicyServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert OnlineReturnPolicyServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +@mock.patch.object( + OnlineReturnPolicyServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceClient), +) +@mock.patch.object( + OnlineReturnPolicyServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert OnlineReturnPolicyServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert OnlineReturnPolicyServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == OnlineReturnPolicyServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + OnlineReturnPolicyServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - OnlineReturnPolicyServiceClient._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." + OnlineReturnPolicyServiceClient._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 OnlineReturnPolicyServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert OnlineReturnPolicyServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert OnlineReturnPolicyServiceClient._get_universe_domain(None, None) == OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + assert ( + OnlineReturnPolicyServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + OnlineReturnPolicyServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + OnlineReturnPolicyServiceClient._get_universe_domain(None, None) + == OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: OnlineReturnPolicyServiceClient._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) @@ -218,7 +379,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") @@ -231,14 +393,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", [ - (OnlineReturnPolicyServiceClient, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, "rest"), -]) -def test_online_return_policy_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (OnlineReturnPolicyServiceClient, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, "rest"), + ], +) +def test_online_return_policy_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) @@ -246,52 +416,70 @@ def test_online_return_policy_service_client_from_service_account_info(client_cl 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.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, "grpc"), + (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.OnlineReturnPolicyServiceRestTransport, "rest"), + ], +) +def test_online_return_policy_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", [ - (OnlineReturnPolicyServiceClient, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, "rest"), -]) -def test_online_return_policy_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (OnlineReturnPolicyServiceClient, "grpc"), + (OnlineReturnPolicyServiceAsyncClient, "grpc_asyncio"), + (OnlineReturnPolicyServiceClient, "rest"), + ], +) +def test_online_return_policy_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" ) @@ -307,30 +495,57 @@ def test_online_return_policy_service_client_get_transport_class(): assert transport == transports.OnlineReturnPolicyServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) -def test_online_return_policy_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + "grpc", + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + OnlineReturnPolicyServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceClient), +) +@mock.patch.object( + OnlineReturnPolicyServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient), +) +def test_online_return_policy_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(OnlineReturnPolicyServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + OnlineReturnPolicyServiceClient, "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(OnlineReturnPolicyServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + OnlineReturnPolicyServiceClient, "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( @@ -348,13 +563,15 @@ def test_online_return_policy_service_client_client_options(client_class, transp # 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, @@ -366,7 +583,7 @@ def test_online_return_policy_service_client_client_options(client_class, transp # 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( @@ -386,23 +603,33 @@ def test_online_return_policy_service_client_client_options(client_class, transp 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", @@ -411,48 +638,102 @@ def test_online_return_policy_service_client_client_options(client_class, transp 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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "true"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", "false"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "true"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + "grpc", + "true", + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + "grpc", + "false", + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceRestTransport, + "rest", + "true", + ), + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + OnlineReturnPolicyServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceClient), +) +@mock.patch.object( + OnlineReturnPolicyServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_online_return_policy_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_online_return_policy_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 @@ -471,12 +752,22 @@ def test_online_return_policy_service_client_mtls_env_auto(client_class, transpo # 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 @@ -497,15 +788,22 @@ def test_online_return_policy_service_client_mtls_env_auto(client_class, transpo ) # 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, @@ -515,19 +813,34 @@ def test_online_return_policy_service_client_mtls_env_auto(client_class, transpo ) -@pytest.mark.parametrize("client_class", [ - OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(OnlineReturnPolicyServiceAsyncClient)) -def test_online_return_policy_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient], +) +@mock.patch.object( + OnlineReturnPolicyServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OnlineReturnPolicyServiceClient), +) +@mock.patch.object( + OnlineReturnPolicyServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OnlineReturnPolicyServiceAsyncClient), +) +def test_online_return_policy_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 @@ -535,8 +848,12 @@ def test_online_return_policy_service_client_get_mtls_endpoint_and_cert_source(c 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 @@ -554,16 +871,28 @@ def test_online_return_policy_service_client_get_mtls_endpoint_and_cert_source(c # 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 @@ -573,34 +902,65 @@ def test_online_return_policy_service_client_get_mtls_endpoint_and_cert_source(c 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", [ - OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient -]) -@mock.patch.object(OnlineReturnPolicyServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceClient)) -@mock.patch.object(OnlineReturnPolicyServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", + [OnlineReturnPolicyServiceClient, OnlineReturnPolicyServiceAsyncClient], +) +@mock.patch.object( + OnlineReturnPolicyServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceClient), +) +@mock.patch.object( + OnlineReturnPolicyServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OnlineReturnPolicyServiceAsyncClient), +) def test_online_return_policy_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = OnlineReturnPolicyServiceClient._DEFAULT_UNIVERSE - default_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = OnlineReturnPolicyServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = OnlineReturnPolicyServiceClient._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", @@ -623,11 +983,19 @@ def test_online_return_policy_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. @@ -635,27 +1003,48 @@ def test_online_return_policy_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", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc"), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest"), -]) -def test_online_return_policy_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + "grpc", + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceRestTransport, + "rest", + ), + ], +) +def test_online_return_policy_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, @@ -664,24 +1053,45 @@ def test_online_return_policy_service_client_client_options_scopes(client_class, api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceRestTransport, "rest", None), -]) -def test_online_return_policy_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", + [ + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceRestTransport, + "rest", + None, + ), + ], +) +def test_online_return_policy_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, @@ -690,11 +1100,14 @@ def test_online_return_policy_service_client_client_options_credentials_file(cli api_audience=None, ) + def test_online_return_policy_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = OnlineReturnPolicyServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -709,23 +1122,38 @@ def test_online_return_policy_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport, "grpc", grpc_helpers), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_online_return_policy_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", + [ + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_online_return_policy_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, @@ -752,9 +1180,7 @@ def test_online_return_policy_service_client_create_channel_credentials_file(cli 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, @@ -765,11 +1191,14 @@ def test_online_return_policy_service_client_create_channel_credentials_file(cli ) -@pytest.mark.parametrize("request_type", [ - online_return_policy.GetOnlineReturnPolicyRequest, - dict, -]) -def test_get_online_return_policy(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + online_return_policy.GetOnlineReturnPolicyRequest, + dict, + ], +) +def test_get_online_return_policy(request_type, transport: str = "grpc"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -781,17 +1210,19 @@ def test_get_online_return_policy(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', + return_policy_uri="return_policy_uri_value", accept_defective_only=True, process_refund_days=2034, accept_exchange=True, @@ -807,17 +1238,24 @@ def test_get_online_return_policy(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' + assert response.name == "name_value" + assert response.return_policy_id == "return_policy_id_value" + assert response.label == "label_value" + assert response.countries == ["countries_value"] + assert response.return_methods == [ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ] + assert response.item_conditions == [ + online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ] + assert response.return_policy_uri == "return_policy_uri_value" assert response.accept_defective_only is True assert response.process_refund_days == 2034 assert response.accept_exchange is True - assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + assert ( + response.return_label_source + == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + ) def test_get_online_return_policy_non_empty_request_with_auto_populated_field(): @@ -825,28 +1263,31 @@ def test_get_online_return_policy_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = OnlineReturnPolicyServiceClient( 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 = online_return_policy.GetOnlineReturnPolicyRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_online_return_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_online_return_policy(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == online_return_policy.GetOnlineReturnPolicyRequest( - name='name_value', + name="name_value", ) + def test_get_online_return_policy_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -861,12 +1302,19 @@ def test_get_online_return_policy_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_online_return_policy in client._transport._wrapped_methods + assert ( + client._transport.get_online_return_policy + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_online_return_policy + ] = mock_rpc request = {} client.get_online_return_policy(request) @@ -879,8 +1327,11 @@ def test_get_online_return_policy_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_online_return_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_online_return_policy_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: @@ -894,12 +1345,17 @@ async def test_get_online_return_policy_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_online_return_policy in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_online_return_policy + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_online_return_policy] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_online_return_policy + ] = mock_rpc request = {} await client.get_online_return_policy(request) @@ -913,8 +1369,12 @@ async def test_get_online_return_policy_async_use_cached_wrapped_rpc(transport: assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.GetOnlineReturnPolicyRequest): +async def test_get_online_return_policy_async( + transport: str = "grpc_asyncio", + request_type=online_return_policy.GetOnlineReturnPolicyRequest, +): client = OnlineReturnPolicyServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -926,22 +1386,28 @@ async def test_get_online_return_policy_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.OnlineReturnPolicy( + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[ + online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ], + return_policy_uri="return_policy_uri_value", + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + ) response = await client.get_online_return_policy(request) # Establish that the underlying gRPC stub method was called. @@ -952,23 +1418,31 @@ async def test_get_online_return_policy_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' + assert response.name == "name_value" + assert response.return_policy_id == "return_policy_id_value" + assert response.label == "label_value" + assert response.countries == ["countries_value"] + assert response.return_methods == [ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ] + assert response.item_conditions == [ + online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ] + assert response.return_policy_uri == "return_policy_uri_value" assert response.accept_defective_only is True assert response.process_refund_days == 2034 assert response.accept_exchange is True - assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + assert ( + response.return_label_source + == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + ) @pytest.mark.asyncio async def test_get_online_return_policy_async_from_dict(): await test_get_online_return_policy_async(request_type=dict) + def test_get_online_return_policy_field_headers(): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -978,12 +1452,12 @@ def test_get_online_return_policy_field_headers(): # a field header. Set these to a non-empty value. request = online_return_policy.GetOnlineReturnPolicyRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: call.return_value = online_return_policy.OnlineReturnPolicy() client.get_online_return_policy(request) @@ -995,9 +1469,9 @@ def test_get_online_return_policy_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 @@ -1010,13 +1484,15 @@ async def test_get_online_return_policy_field_headers_async(): # a field header. Set these to a non-empty value. request = online_return_policy.GetOnlineReturnPolicyRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) + type(client.transport.get_online_return_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.OnlineReturnPolicy() + ) await client.get_online_return_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1027,9 +1503,9 @@ async def test_get_online_return_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_online_return_policy_flattened(): @@ -1039,14 +1515,14 @@ def test_get_online_return_policy_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = online_return_policy.OnlineReturnPolicy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_online_return_policy( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1054,7 +1530,7 @@ def test_get_online_return_policy_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 @@ -1068,9 +1544,10 @@ def test_get_online_return_policy_flattened_error(): with pytest.raises(ValueError): client.get_online_return_policy( online_return_policy.GetOnlineReturnPolicyRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_online_return_policy_flattened_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1079,16 +1556,18 @@ async def test_get_online_return_policy_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = online_return_policy.OnlineReturnPolicy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.OnlineReturnPolicy() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_online_return_policy( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1096,9 +1575,10 @@ async def test_get_online_return_policy_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_online_return_policy_flattened_error_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1110,15 +1590,18 @@ async def test_get_online_return_policy_flattened_error_async(): with pytest.raises(ValueError): await client.get_online_return_policy( online_return_policy.GetOnlineReturnPolicyRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - online_return_policy.ListOnlineReturnPoliciesRequest, - dict, -]) -def test_list_online_return_policies(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + online_return_policy.ListOnlineReturnPoliciesRequest, + dict, + ], +) +def test_list_online_return_policies(request_type, transport: str = "grpc"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1130,11 +1613,11 @@ def test_list_online_return_policies(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_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_online_return_policies(request) @@ -1146,7 +1629,7 @@ def test_list_online_return_policies(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_online_return_policies_non_empty_request_with_auto_populated_field(): @@ -1154,30 +1637,33 @@ def test_list_online_return_policies_non_empty_request_with_auto_populated_field # automatically populated, according to AIP-4235, with non-empty requests. client = OnlineReturnPolicyServiceClient( 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 = online_return_policy.ListOnlineReturnPoliciesRequest( - 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_online_return_policies), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.list_online_return_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_online_return_policies(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == online_return_policy.ListOnlineReturnPoliciesRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_online_return_policies_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1192,12 +1678,19 @@ def test_list_online_return_policies_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_online_return_policies in client._transport._wrapped_methods + assert ( + client._transport.list_online_return_policies + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_online_return_policies] = 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_online_return_policies + ] = mock_rpc request = {} client.list_online_return_policies(request) @@ -1210,8 +1703,11 @@ def test_list_online_return_policies_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_online_return_policies_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_online_return_policies_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: @@ -1225,12 +1721,17 @@ async def test_list_online_return_policies_async_use_cached_wrapped_rpc(transpor wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_online_return_policies in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_online_return_policies + 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_online_return_policies] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_online_return_policies + ] = mock_rpc request = {} await client.list_online_return_policies(request) @@ -1244,8 +1745,12 @@ async def test_list_online_return_policies_async_use_cached_wrapped_rpc(transpor assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_online_return_policies_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.ListOnlineReturnPoliciesRequest): +async def test_list_online_return_policies_async( + transport: str = "grpc_asyncio", + request_type=online_return_policy.ListOnlineReturnPoliciesRequest, +): client = OnlineReturnPolicyServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1257,12 +1762,14 @@ async def test_list_online_return_policies_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_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_online_return_policies(request) # Establish that the underlying gRPC stub method was called. @@ -1273,13 +1780,14 @@ async def test_list_online_return_policies_async(transport: str = 'grpc_asyncio' # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListOnlineReturnPoliciesAsyncPager) - 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_online_return_policies_async_from_dict(): await test_list_online_return_policies_async(request_type=dict) + def test_list_online_return_policies_field_headers(): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1289,12 +1797,12 @@ def test_list_online_return_policies_field_headers(): # a field header. Set these to a non-empty value. request = online_return_policy.ListOnlineReturnPoliciesRequest() - 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_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() client.list_online_return_policies(request) @@ -1306,9 +1814,9 @@ def test_list_online_return_policies_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 @@ -1321,13 +1829,15 @@ async def test_list_online_return_policies_field_headers_async(): # a field header. Set these to a non-empty value. request = online_return_policy.ListOnlineReturnPoliciesRequest() - 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_online_return_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) + type(client.transport.list_online_return_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.ListOnlineReturnPoliciesResponse() + ) await client.list_online_return_policies(request) # Establish that the underlying gRPC stub method was called. @@ -1338,9 +1848,9 @@ async def test_list_online_return_policies_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_online_return_policies_flattened(): @@ -1350,14 +1860,14 @@ def test_list_online_return_policies_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_online_return_policies( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1365,7 +1875,7 @@ def test_list_online_return_policies_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 @@ -1379,9 +1889,10 @@ def test_list_online_return_policies_flattened_error(): with pytest.raises(ValueError): client.list_online_return_policies( online_return_policy.ListOnlineReturnPoliciesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_online_return_policies_flattened_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1390,16 +1901,18 @@ async def test_list_online_return_policies_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.ListOnlineReturnPoliciesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_online_return_policies( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1407,9 +1920,10 @@ async def test_list_online_return_policies_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_online_return_policies_flattened_error_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1421,7 +1935,7 @@ async def test_list_online_return_policies_flattened_error_async(): with pytest.raises(ValueError): await client.list_online_return_policies( online_return_policy.ListOnlineReturnPoliciesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1433,8 +1947,8 @@ def test_list_online_return_policies_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_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( online_return_policy.ListOnlineReturnPoliciesResponse( @@ -1443,17 +1957,17 @@ def test_list_online_return_policies_pager(transport_name: str = "grpc"): online_return_policy.OnlineReturnPolicy(), online_return_policy.OnlineReturnPolicy(), ], - next_page_token='abc', + next_page_token="abc", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[], - next_page_token='def', + next_page_token="def", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ online_return_policy.OnlineReturnPolicy(), ], - next_page_token='ghi', + next_page_token="ghi", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ @@ -1468,11 +1982,11 @@ def test_list_online_return_policies_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_online_return_policies( + request={}, retry=retry, timeout=timeout ) - pager = client.list_online_return_policies(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -1480,8 +1994,11 @@ def test_list_online_return_policies_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, online_return_policy.OnlineReturnPolicy) - for i in results) + assert all( + isinstance(i, online_return_policy.OnlineReturnPolicy) for i in results + ) + + def test_list_online_return_policies_pages(transport_name: str = "grpc"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1490,8 +2007,8 @@ def test_list_online_return_policies_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_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Set the response to a series of pages. call.side_effect = ( online_return_policy.ListOnlineReturnPoliciesResponse( @@ -1500,17 +2017,17 @@ def test_list_online_return_policies_pages(transport_name: str = "grpc"): online_return_policy.OnlineReturnPolicy(), online_return_policy.OnlineReturnPolicy(), ], - next_page_token='abc', + next_page_token="abc", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[], - next_page_token='def', + next_page_token="def", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ online_return_policy.OnlineReturnPolicy(), ], - next_page_token='ghi', + next_page_token="ghi", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ @@ -1521,9 +2038,10 @@ def test_list_online_return_policies_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_online_return_policies(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_online_return_policies_async_pager(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1532,8 +2050,10 @@ async def test_list_online_return_policies_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_online_return_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( online_return_policy.ListOnlineReturnPoliciesResponse( @@ -1542,17 +2062,17 @@ async def test_list_online_return_policies_async_pager(): online_return_policy.OnlineReturnPolicy(), online_return_policy.OnlineReturnPolicy(), ], - next_page_token='abc', + next_page_token="abc", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[], - next_page_token='def', + next_page_token="def", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ online_return_policy.OnlineReturnPolicy(), ], - next_page_token='ghi', + next_page_token="ghi", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ @@ -1562,15 +2082,18 @@ async def test_list_online_return_policies_async_pager(): ), RuntimeError, ) - async_pager = await client.list_online_return_policies(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_online_return_policies( + 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, online_return_policy.OnlineReturnPolicy) - for i in responses) + assert all( + isinstance(i, online_return_policy.OnlineReturnPolicy) for i in responses + ) @pytest.mark.asyncio @@ -1581,8 +2104,10 @@ async def test_list_online_return_policies_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_online_return_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: # Set the response to a series of pages. call.side_effect = ( online_return_policy.ListOnlineReturnPoliciesResponse( @@ -1591,17 +2116,17 @@ async def test_list_online_return_policies_async_pages(): online_return_policy.OnlineReturnPolicy(), online_return_policy.OnlineReturnPolicy(), ], - next_page_token='abc', + next_page_token="abc", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[], - next_page_token='def', + next_page_token="def", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ online_return_policy.OnlineReturnPolicy(), ], - next_page_token='ghi', + next_page_token="ghi", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ @@ -1614,18 +2139,22 @@ async def test_list_online_return_policies_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_online_return_policies(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", [ - gsma_online_return_policy.CreateOnlineReturnPolicyRequest, - dict, -]) -def test_create_online_return_policy(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + dict, + ], +) +def test_create_online_return_policy(request_type, transport: str = "grpc"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1637,17 +2166,21 @@ def test_create_online_return_policy(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ], + return_policy_uri="return_policy_uri_value", accept_defective_only=True, process_refund_days=2034, accept_exchange=True, @@ -1663,17 +2196,24 @@ def test_create_online_return_policy(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' + assert response.name == "name_value" + assert response.return_policy_id == "return_policy_id_value" + assert response.label == "label_value" + assert response.countries == ["countries_value"] + assert response.return_methods == [ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ] + assert response.item_conditions == [ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ] + assert response.return_policy_uri == "return_policy_uri_value" assert response.accept_defective_only is True assert response.process_refund_days == 2034 assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + assert ( + response.return_label_source + == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + ) def test_create_online_return_policy_non_empty_request_with_auto_populated_field(): @@ -1681,28 +2221,31 @@ def test_create_online_return_policy_non_empty_request_with_auto_populated_field # automatically populated, according to AIP-4235, with non-empty requests. client = OnlineReturnPolicyServiceClient( 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest( - 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.create_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.create_online_return_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_online_return_policy(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gsma_online_return_policy.CreateOnlineReturnPolicyRequest( - parent='parent_value', + parent="parent_value", ) + def test_create_online_return_policy_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1717,12 +2260,19 @@ def test_create_online_return_policy_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_online_return_policy in client._transport._wrapped_methods + assert ( + client._transport.create_online_return_policy + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_online_return_policy + ] = mock_rpc request = {} client.create_online_return_policy(request) @@ -1735,8 +2285,11 @@ def test_create_online_return_policy_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_online_return_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_online_return_policy_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: @@ -1750,12 +2303,17 @@ async def test_create_online_return_policy_async_use_cached_wrapped_rpc(transpor wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_online_return_policy in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_online_return_policy + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_online_return_policy] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_online_return_policy + ] = mock_rpc request = {} await client.create_online_return_policy(request) @@ -1769,8 +2327,12 @@ async def test_create_online_return_policy_async_use_cached_wrapped_rpc(transpor assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): +async def test_create_online_return_policy_async( + transport: str = "grpc_asyncio", + request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest, +): client = OnlineReturnPolicyServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1782,22 +2344,28 @@ async def test_create_online_return_policy_async(transport: str = 'grpc_asyncio' # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_online_return_policy.OnlineReturnPolicy( + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ], + return_policy_uri="return_policy_uri_value", + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + ) response = await client.create_online_return_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1808,23 +2376,31 @@ async def test_create_online_return_policy_async(transport: str = 'grpc_asyncio' # Establish that the response is the type that we expect. assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' + assert response.name == "name_value" + assert response.return_policy_id == "return_policy_id_value" + assert response.label == "label_value" + assert response.countries == ["countries_value"] + assert response.return_methods == [ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ] + assert response.item_conditions == [ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ] + assert response.return_policy_uri == "return_policy_uri_value" assert response.accept_defective_only is True assert response.process_refund_days == 2034 assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + assert ( + response.return_label_source + == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + ) @pytest.mark.asyncio async def test_create_online_return_policy_async_from_dict(): await test_create_online_return_policy_async(request_type=dict) + def test_create_online_return_policy_field_headers(): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1834,12 +2410,12 @@ def test_create_online_return_policy_field_headers(): # a field header. Set these to a non-empty value. request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: call.return_value = gsma_online_return_policy.OnlineReturnPolicy() client.create_online_return_policy(request) @@ -1851,9 +2427,9 @@ def test_create_online_return_policy_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 @@ -1866,13 +2442,15 @@ async def test_create_online_return_policy_field_headers_async(): # a field header. Set these to a non-empty value. request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + type(client.transport.create_online_return_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_online_return_policy.OnlineReturnPolicy() + ) await client.create_online_return_policy(request) # Establish that the underlying gRPC stub method was called. @@ -1883,9 +2461,9 @@ async def test_create_online_return_policy_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_online_return_policy_flattened(): @@ -1895,15 +2473,17 @@ def test_create_online_return_policy_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gsma_online_return_policy.OnlineReturnPolicy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_online_return_policy( - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + parent="parent_value", + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy( + name="name_value" + ), ) # Establish that the underlying call was made with the expected @@ -1911,10 +2491,10 @@ def test_create_online_return_policy_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].online_return_policy - mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name="name_value") assert arg == mock_val @@ -1928,10 +2508,13 @@ def test_create_online_return_policy_flattened_error(): with pytest.raises(ValueError): client.create_online_return_policy( gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + parent="parent_value", + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy( + name="name_value" + ), ) + @pytest.mark.asyncio async def test_create_online_return_policy_flattened_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1940,17 +2523,21 @@ async def test_create_online_return_policy_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gsma_online_return_policy.OnlineReturnPolicy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_online_return_policy.OnlineReturnPolicy() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_online_return_policy( - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + parent="parent_value", + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy( + name="name_value" + ), ) # Establish that the underlying call was made with the expected @@ -1958,12 +2545,13 @@ async def test_create_online_return_policy_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].online_return_policy - mock_val = gsma_online_return_policy.OnlineReturnPolicy(name='name_value') + mock_val = gsma_online_return_policy.OnlineReturnPolicy(name="name_value") assert arg == mock_val + @pytest.mark.asyncio async def test_create_online_return_policy_flattened_error_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -1975,16 +2563,21 @@ async def test_create_online_return_policy_flattened_error_async(): with pytest.raises(ValueError): await client.create_online_return_policy( gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + parent="parent_value", + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy( + name="name_value" + ), ) -@pytest.mark.parametrize("request_type", [ - online_return_policy.DeleteOnlineReturnPolicyRequest, - dict, -]) -def test_delete_online_return_policy(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + online_return_policy.DeleteOnlineReturnPolicyRequest, + dict, + ], +) +def test_delete_online_return_policy(request_type, transport: str = "grpc"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1996,8 +2589,8 @@ def test_delete_online_return_policy(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_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_online_return_policy(request) @@ -2017,28 +2610,31 @@ def test_delete_online_return_policy_non_empty_request_with_auto_populated_field # automatically populated, according to AIP-4235, with non-empty requests. client = OnlineReturnPolicyServiceClient( 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 = online_return_policy.DeleteOnlineReturnPolicyRequest( - 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_online_return_policy), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.delete_online_return_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_online_return_policy(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == online_return_policy.DeleteOnlineReturnPolicyRequest( - name='name_value', + name="name_value", ) + def test_delete_online_return_policy_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2053,12 +2649,19 @@ def test_delete_online_return_policy_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_online_return_policy in client._transport._wrapped_methods + assert ( + client._transport.delete_online_return_policy + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_online_return_policy] = 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_online_return_policy + ] = mock_rpc request = {} client.delete_online_return_policy(request) @@ -2071,8 +2674,11 @@ def test_delete_online_return_policy_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_online_return_policy_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_online_return_policy_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: @@ -2086,12 +2692,17 @@ async def test_delete_online_return_policy_async_use_cached_wrapped_rpc(transpor wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_online_return_policy in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_online_return_policy + 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_online_return_policy] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_online_return_policy + ] = mock_rpc request = {} await client.delete_online_return_policy(request) @@ -2105,8 +2716,12 @@ async def test_delete_online_return_policy_async_use_cached_wrapped_rpc(transpor assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_online_return_policy_async(transport: str = 'grpc_asyncio', request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): +async def test_delete_online_return_policy_async( + transport: str = "grpc_asyncio", + request_type=online_return_policy.DeleteOnlineReturnPolicyRequest, +): client = OnlineReturnPolicyServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2118,8 +2733,8 @@ async def test_delete_online_return_policy_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_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_online_return_policy(request) @@ -2138,6 +2753,7 @@ async def test_delete_online_return_policy_async(transport: str = 'grpc_asyncio' async def test_delete_online_return_policy_async_from_dict(): await test_delete_online_return_policy_async(request_type=dict) + def test_delete_online_return_policy_field_headers(): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2147,12 +2763,12 @@ def test_delete_online_return_policy_field_headers(): # a field header. Set these to a non-empty value. request = online_return_policy.DeleteOnlineReturnPolicyRequest() - 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_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: call.return_value = None client.delete_online_return_policy(request) @@ -2164,9 +2780,9 @@ def test_delete_online_return_policy_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 @@ -2179,12 +2795,12 @@ async def test_delete_online_return_policy_field_headers_async(): # a field header. Set these to a non-empty value. request = online_return_policy.DeleteOnlineReturnPolicyRequest() - 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_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_online_return_policy(request) @@ -2196,9 +2812,9 @@ async def test_delete_online_return_policy_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_online_return_policy_flattened(): @@ -2208,14 +2824,14 @@ def test_delete_online_return_policy_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__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_online_return_policy( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2223,7 +2839,7 @@ def test_delete_online_return_policy_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 @@ -2237,9 +2853,10 @@ def test_delete_online_return_policy_flattened_error(): with pytest.raises(ValueError): client.delete_online_return_policy( online_return_policy.DeleteOnlineReturnPolicyRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_online_return_policy_flattened_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -2248,8 +2865,8 @@ async def test_delete_online_return_policy_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = None @@ -2257,7 +2874,7 @@ async def test_delete_online_return_policy_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_online_return_policy( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2265,9 +2882,10 @@ async def test_delete_online_return_policy_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_online_return_policy_flattened_error_async(): client = OnlineReturnPolicyServiceAsyncClient( @@ -2279,7 +2897,7 @@ async def test_delete_online_return_policy_flattened_error_async(): with pytest.raises(ValueError): await client.delete_online_return_policy( online_return_policy.DeleteOnlineReturnPolicyRequest(), - name='name_value', + name="name_value", ) @@ -2297,12 +2915,19 @@ def test_get_online_return_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_online_return_policy in client._transport._wrapped_methods + assert ( + client._transport.get_online_return_policy + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_online_return_policy] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_online_return_policy + ] = mock_rpc request = {} client.get_online_return_policy(request) @@ -2317,55 +2942,60 @@ def test_get_online_return_policy_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_online_return_policy_rest_required_fields(request_type=online_return_policy.GetOnlineReturnPolicyRequest): +def test_get_online_return_policy_rest_required_fields( + request_type=online_return_policy.GetOnlineReturnPolicyRequest, +): transport_class = transports.OnlineReturnPolicyServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_online_return_policy._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_online_return_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_online_return_policy._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_online_return_policy._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 = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = online_return_policy.OnlineReturnPolicy() # Mock the http request 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 @@ -2376,24 +3006,24 @@ def test_get_online_return_policy_rest_required_fields(request_type=online_retur return_value = online_return_policy.OnlineReturnPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_online_return_policy(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_online_return_policy_rest_flattened(): @@ -2403,16 +3033,16 @@ def test_get_online_return_policy_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 = online_return_policy.OnlineReturnPolicy() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + sample_request = {"name": "accounts/sample1/onlineReturnPolicies/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2422,7 +3052,7 @@ def test_get_online_return_policy_rest_flattened(): # Convert return value to protobuf type return_value = online_return_policy.OnlineReturnPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2432,10 +3062,14 @@ def test_get_online_return_policy_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}" + % client.transport._host, + args[1], + ) -def test_get_online_return_policy_rest_flattened_error(transport: str = 'rest'): +def test_get_online_return_policy_rest_flattened_error(transport: str = "rest"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2446,7 +3080,7 @@ def test_get_online_return_policy_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_online_return_policy( online_return_policy.GetOnlineReturnPolicyRequest(), - name='name_value', + name="name_value", ) @@ -2464,12 +3098,19 @@ def test_list_online_return_policies_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_online_return_policies in client._transport._wrapped_methods + assert ( + client._transport.list_online_return_policies + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_online_return_policies] = 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_online_return_policies + ] = mock_rpc request = {} client.list_online_return_policies(request) @@ -2484,57 +3125,67 @@ def test_list_online_return_policies_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_list_online_return_policies_rest_required_fields(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): +def test_list_online_return_policies_rest_required_fields( + request_type=online_return_policy.ListOnlineReturnPoliciesRequest, +): transport_class = transports.OnlineReturnPolicyServiceRestTransport 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_online_return_policies._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_online_return_policies._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_online_return_policies._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_online_return_policies._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 = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = online_return_policy.ListOnlineReturnPoliciesResponse() # Mock the http request 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 @@ -2542,27 +3193,37 @@ def test_list_online_return_policies_rest_required_fields(request_type=online_re response_value.status_code = 200 # Convert return value to protobuf type - return_value = online_return_policy.ListOnlineReturnPoliciesResponse.pb(return_value) + return_value = online_return_policy.ListOnlineReturnPoliciesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_online_return_policies(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_online_return_policies_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_online_return_policies._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_online_return_policies_rest_flattened(): @@ -2572,16 +3233,16 @@ def test_list_online_return_policies_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 = online_return_policy.ListOnlineReturnPoliciesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -2589,9 +3250,11 @@ def test_list_online_return_policies_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = online_return_policy.ListOnlineReturnPoliciesResponse.pb(return_value) + return_value = online_return_policy.ListOnlineReturnPoliciesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2601,10 +3264,14 @@ def test_list_online_return_policies_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/onlineReturnPolicies" + % client.transport._host, + args[1], + ) -def test_list_online_return_policies_rest_flattened_error(transport: str = 'rest'): +def test_list_online_return_policies_rest_flattened_error(transport: str = "rest"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2615,20 +3282,20 @@ def test_list_online_return_policies_rest_flattened_error(transport: str = 'rest with pytest.raises(ValueError): client.list_online_return_policies( online_return_policy.ListOnlineReturnPoliciesRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_online_return_policies_rest_pager(transport: str = 'rest'): +def test_list_online_return_policies_rest_pager(transport: str = "rest"): client = OnlineReturnPolicyServiceClient( 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 = ( online_return_policy.ListOnlineReturnPoliciesResponse( @@ -2637,17 +3304,17 @@ def test_list_online_return_policies_rest_pager(transport: str = 'rest'): online_return_policy.OnlineReturnPolicy(), online_return_policy.OnlineReturnPolicy(), ], - next_page_token='abc', + next_page_token="abc", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[], - next_page_token='def', + next_page_token="def", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ online_return_policy.OnlineReturnPolicy(), ], - next_page_token='ghi', + next_page_token="ghi", ), online_return_policy.ListOnlineReturnPoliciesResponse( online_return_policies=[ @@ -2660,24 +3327,28 @@ def test_list_online_return_policies_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(online_return_policy.ListOnlineReturnPoliciesResponse.to_json(x) for x in response) + response = tuple( + online_return_policy.ListOnlineReturnPoliciesResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_online_return_policies(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, online_return_policy.OnlineReturnPolicy) - for i in results) + assert all( + isinstance(i, online_return_policy.OnlineReturnPolicy) for i in results + ) pages = list(client.list_online_return_policies(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 @@ -2695,12 +3366,19 @@ def test_create_online_return_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_online_return_policy in client._transport._wrapped_methods + assert ( + client._transport.create_online_return_policy + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_online_return_policy] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_online_return_policy + ] = mock_rpc request = {} client.create_online_return_policy(request) @@ -2715,57 +3393,62 @@ def test_create_online_return_policy_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_create_online_return_policy_rest_required_fields(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): +def test_create_online_return_policy_rest_required_fields( + request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest, +): transport_class = transports.OnlineReturnPolicyServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_online_return_policy._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_online_return_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_online_return_policy._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_online_return_policy._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 = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gsma_online_return_policy.OnlineReturnPolicy() # Mock the http request 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() @@ -2775,24 +3458,32 @@ def test_create_online_return_policy_rest_required_fields(request_type=gsma_onli return_value = gsma_online_return_policy.OnlineReturnPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_online_return_policy(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "onlineReturnPolicy", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "onlineReturnPolicy", + ) + ) + ) def test_create_online_return_policy_rest_flattened(): @@ -2802,17 +3493,19 @@ def test_create_online_return_policy_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 = gsma_online_return_policy.OnlineReturnPolicy() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + parent="parent_value", + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy( + name="name_value" + ), ) mock_args.update(sample_request) @@ -2822,7 +3515,7 @@ def test_create_online_return_policy_rest_flattened(): # Convert return value to protobuf type return_value = gsma_online_return_policy.OnlineReturnPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2832,10 +3525,14 @@ def test_create_online_return_policy_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/onlineReturnPolicies" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/onlineReturnPolicies" + % client.transport._host, + args[1], + ) -def test_create_online_return_policy_rest_flattened_error(transport: str = 'rest'): +def test_create_online_return_policy_rest_flattened_error(transport: str = "rest"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2846,8 +3543,10 @@ def test_create_online_return_policy_rest_flattened_error(transport: str = 'rest with pytest.raises(ValueError): client.create_online_return_policy( gsma_online_return_policy.CreateOnlineReturnPolicyRequest(), - parent='parent_value', - online_return_policy=gsma_online_return_policy.OnlineReturnPolicy(name='name_value'), + parent="parent_value", + online_return_policy=gsma_online_return_policy.OnlineReturnPolicy( + name="name_value" + ), ) @@ -2865,12 +3564,19 @@ def test_delete_online_return_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_online_return_policy in client._transport._wrapped_methods + assert ( + client._transport.delete_online_return_policy + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_online_return_policy] = 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_online_return_policy + ] = mock_rpc request = {} client.delete_online_return_policy(request) @@ -2885,80 +3591,85 @@ def test_delete_online_return_policy_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_delete_online_return_policy_rest_required_fields(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): +def test_delete_online_return_policy_rest_required_fields( + request_type=online_return_policy.DeleteOnlineReturnPolicyRequest, +): transport_class = transports.OnlineReturnPolicyServiceRestTransport 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_online_return_policy._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_online_return_policy._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_online_return_policy._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_online_return_policy._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 = OnlineReturnPolicyServiceClient( 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_online_return_policy(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_online_return_policy_rest_unset_required_fields(): - transport = transports.OnlineReturnPolicyServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.OnlineReturnPolicyServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_online_return_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_delete_online_return_policy_rest_flattened(): @@ -2968,24 +3679,24 @@ def test_delete_online_return_policy_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/onlineReturnPolicies/sample2'} + sample_request = {"name": "accounts/sample1/onlineReturnPolicies/sample2"} # 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"} @@ -2995,10 +3706,14 @@ def test_delete_online_return_policy_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/onlineReturnPolicies/*}" + % client.transport._host, + args[1], + ) -def test_delete_online_return_policy_rest_flattened_error(transport: str = 'rest'): +def test_delete_online_return_policy_rest_flattened_error(transport: str = "rest"): client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3009,7 +3724,7 @@ def test_delete_online_return_policy_rest_flattened_error(transport: str = 'rest with pytest.raises(ValueError): client.delete_online_return_policy( online_return_policy.DeleteOnlineReturnPolicyRequest(), - name='name_value', + name="name_value", ) @@ -3051,8 +3766,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = OnlineReturnPolicyServiceClient( - 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. @@ -3074,6 +3788,7 @@ def test_transport_instance(): client = OnlineReturnPolicyServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.OnlineReturnPolicyServiceGrpcTransport( @@ -3088,18 +3803,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.OnlineReturnPolicyServiceGrpcTransport, - transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, - transports.OnlineReturnPolicyServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + transports.OnlineReturnPolicyServiceRestTransport, + ], +) 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 = OnlineReturnPolicyServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3109,8 +3829,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3125,8 +3844,8 @@ def test_get_online_return_policy_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: call.return_value = online_return_policy.OnlineReturnPolicy() client.get_online_return_policy(request=None) @@ -3148,8 +3867,8 @@ def test_list_online_return_policies_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: call.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() client.list_online_return_policies(request=None) @@ -3171,8 +3890,8 @@ def test_create_online_return_policy_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: call.return_value = gsma_online_return_policy.OnlineReturnPolicy() client.create_online_return_policy(request=None) @@ -3194,8 +3913,8 @@ def test_delete_online_return_policy_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: call.return_value = None client.delete_online_return_policy(request=None) @@ -3208,16 +3927,15 @@ def test_delete_online_return_policy_empty_call_grpc(): def test_transport_kind_grpc_asyncio(): - transport = OnlineReturnPolicyServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = OnlineReturnPolicyServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = OnlineReturnPolicyServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3233,22 +3951,28 @@ async def test_get_online_return_policy_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.OnlineReturnPolicy( + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[ + online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ], + return_policy_uri="return_policy_uri_value", + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + ) await client.get_online_return_policy(request=None) # Establish that the underlying stub method was called. @@ -3270,12 +3994,14 @@ async def test_list_online_return_policies_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + online_return_policy.ListOnlineReturnPoliciesResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_online_return_policies(request=None) # Establish that the underlying stub method was called. @@ -3297,22 +4023,28 @@ async def test_create_online_return_policy_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_online_return_policy.OnlineReturnPolicy( + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ], + return_policy_uri="return_policy_uri_value", + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + ) + ) await client.create_online_return_policy(request=None) # Establish that the underlying stub method was called. @@ -3334,8 +4066,8 @@ async def test_delete_online_return_policy_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_online_return_policy(request=None) @@ -3355,20 +4087,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_online_return_policy_rest_bad_request(request_type=online_return_policy.GetOnlineReturnPolicyRequest): +def test_get_online_return_policy_rest_bad_request( + request_type=online_return_policy.GetOnlineReturnPolicyRequest, +): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + request_init = {"name": "accounts/sample1/onlineReturnPolicies/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() @@ -3377,35 +4112,39 @@ def test_get_online_return_policy_rest_bad_request(request_type=online_return_po client.get_online_return_policy(request) -@pytest.mark.parametrize("request_type", [ - online_return_policy.GetOnlineReturnPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + online_return_policy.GetOnlineReturnPolicyRequest, + dict, + ], +) def test_get_online_return_policy_rest_call_success(request_type): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + request_init = {"name": "accounts/sample1/onlineReturnPolicies/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 = online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], + return_policy_uri="return_policy_uri_value", + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, ) # Wrap the value into a proper Response obj @@ -3415,43 +4154,63 @@ def test_get_online_return_policy_rest_call_success(request_type): # Convert return value to protobuf type return_value = online_return_policy.OnlineReturnPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_online_return_policy(request) # Establish that the response is the type that we expect. assert isinstance(response, online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' + assert response.name == "name_value" + assert response.return_policy_id == "return_policy_id_value" + assert response.label == "label_value" + assert response.countries == ["countries_value"] + assert response.return_methods == [ + online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ] + assert response.item_conditions == [ + online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ] + assert response.return_policy_uri == "return_policy_uri_value" assert response.accept_defective_only is True assert response.process_refund_days == 2034 assert response.accept_exchange is True - assert response.return_label_source == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + assert ( + response.return_label_source + == online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_online_return_policy_rest_interceptors(null_interceptor): transport = transports.OnlineReturnPolicyServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_get_online_return_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_get_online_return_policy") 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.OnlineReturnPolicyServiceRestInterceptor, + "post_get_online_return_policy", + ) as post, mock.patch.object( + transports.OnlineReturnPolicyServiceRestInterceptor, + "post_get_online_return_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OnlineReturnPolicyServiceRestInterceptor, + "pre_get_online_return_policy", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = online_return_policy.GetOnlineReturnPolicyRequest.pb(online_return_policy.GetOnlineReturnPolicyRequest()) + pb_message = online_return_policy.GetOnlineReturnPolicyRequest.pb( + online_return_policy.GetOnlineReturnPolicyRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3462,39 +4221,53 @@ def test_get_online_return_policy_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 = online_return_policy.OnlineReturnPolicy.to_json(online_return_policy.OnlineReturnPolicy()) + return_value = online_return_policy.OnlineReturnPolicy.to_json( + online_return_policy.OnlineReturnPolicy() + ) req.return_value.content = return_value request = online_return_policy.GetOnlineReturnPolicyRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = online_return_policy.OnlineReturnPolicy() - post_with_metadata.return_value = online_return_policy.OnlineReturnPolicy(), metadata + post_with_metadata.return_value = ( + online_return_policy.OnlineReturnPolicy(), + metadata, + ) - client.get_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_online_return_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_list_online_return_policies_rest_bad_request(request_type=online_return_policy.ListOnlineReturnPoliciesRequest): +def test_list_online_return_policies_rest_bad_request( + request_type=online_return_policy.ListOnlineReturnPoliciesRequest, +): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3503,25 +4276,27 @@ def test_list_online_return_policies_rest_bad_request(request_type=online_return client.list_online_return_policies(request) -@pytest.mark.parametrize("request_type", [ - online_return_policy.ListOnlineReturnPoliciesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + online_return_policy.ListOnlineReturnPoliciesRequest, + dict, + ], +) def test_list_online_return_policies_rest_call_success(request_type): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = online_return_policy.ListOnlineReturnPoliciesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -3529,35 +4304,50 @@ def test_list_online_return_policies_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = online_return_policy.ListOnlineReturnPoliciesResponse.pb(return_value) + return_value = online_return_policy.ListOnlineReturnPoliciesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_online_return_policies(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListOnlineReturnPoliciesPager) - 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_online_return_policies_rest_interceptors(null_interceptor): transport = transports.OnlineReturnPolicyServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_list_online_return_policies_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_list_online_return_policies") 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.OnlineReturnPolicyServiceRestInterceptor, + "post_list_online_return_policies", + ) as post, mock.patch.object( + transports.OnlineReturnPolicyServiceRestInterceptor, + "post_list_online_return_policies_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OnlineReturnPolicyServiceRestInterceptor, + "pre_list_online_return_policies", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = online_return_policy.ListOnlineReturnPoliciesRequest.pb(online_return_policy.ListOnlineReturnPoliciesRequest()) + pb_message = online_return_policy.ListOnlineReturnPoliciesRequest.pb( + online_return_policy.ListOnlineReturnPoliciesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3568,39 +4358,53 @@ def test_list_online_return_policies_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 = online_return_policy.ListOnlineReturnPoliciesResponse.to_json(online_return_policy.ListOnlineReturnPoliciesResponse()) + return_value = online_return_policy.ListOnlineReturnPoliciesResponse.to_json( + online_return_policy.ListOnlineReturnPoliciesResponse() + ) req.return_value.content = return_value request = online_return_policy.ListOnlineReturnPoliciesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = online_return_policy.ListOnlineReturnPoliciesResponse() - post_with_metadata.return_value = online_return_policy.ListOnlineReturnPoliciesResponse(), metadata + post_with_metadata.return_value = ( + online_return_policy.ListOnlineReturnPoliciesResponse(), + metadata, + ) - client.list_online_return_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_online_return_policies( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_create_online_return_policy_rest_bad_request(request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest): +def test_create_online_return_policy_rest_bad_request( + request_type=gsma_online_return_policy.CreateOnlineReturnPolicyRequest, +): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3609,25 +4413,59 @@ def test_create_online_return_policy_rest_bad_request(request_type=gsma_online_r client.create_online_return_policy(request) -@pytest.mark.parametrize("request_type", [ - gsma_online_return_policy.CreateOnlineReturnPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gsma_online_return_policy.CreateOnlineReturnPolicyRequest, + dict, + ], +) def test_create_online_return_policy_rest_call_success(request_type): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["online_return_policy"] = {'name': 'name_value', 'return_policy_id': 'return_policy_id_value', 'label': 'label_value', 'countries': ['countries_value1', 'countries_value2'], 'policy': {'type_': 1, 'days': 433}, 'seasonal_overrides': [{'return_days': 1200, 'return_until_date': {'year': 433, 'month': 550, 'day': 318}, 'label': 'label_value', 'start_date': {}, 'end_date': {}}], 'restocking_fee': {'fixed_fee': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'micro_percent': 1386}, 'return_methods': [1], 'item_conditions': [1], 'return_shipping_fee': {'type_': 1, 'fixed_fee': {}}, 'return_policy_uri': 'return_policy_uri_value', 'accept_defective_only': True, 'process_refund_days': 2034, 'accept_exchange': True, 'return_label_source': 1} + request_init = {"parent": "accounts/sample1"} + request_init["online_return_policy"] = { + "name": "name_value", + "return_policy_id": "return_policy_id_value", + "label": "label_value", + "countries": ["countries_value1", "countries_value2"], + "policy": {"type_": 1, "days": 433}, + "seasonal_overrides": [ + { + "return_days": 1200, + "return_until_date": {"year": 433, "month": 550, "day": 318}, + "label": "label_value", + "start_date": {}, + "end_date": {}, + } + ], + "restocking_fee": { + "fixed_fee": { + "amount_micros": 1408, + "currency_code": "currency_code_value", + }, + "micro_percent": 1386, + }, + "return_methods": [1], + "item_conditions": [1], + "return_shipping_fee": {"type_": 1, "fixed_fee": {}}, + "return_policy_uri": "return_policy_uri_value", + "accept_defective_only": True, + "process_refund_days": 2034, + "accept_exchange": True, + "return_label_source": 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 = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.meta.fields["online_return_policy"] + test_field = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.meta.fields[ + "online_return_policy" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -3641,7 +4479,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 @@ -3655,7 +4493,9 @@ 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["online_return_policy"].items(): # pragma: NO COVER + for field, value in request_init[ + "online_return_policy" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3670,12 +4510,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") @@ -3688,20 +4532,24 @@ 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 = gsma_online_return_policy.OnlineReturnPolicy( - name='name_value', - return_policy_id='return_policy_id_value', - label='label_value', - countries=['countries_value'], - return_methods=[gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL], - item_conditions=[gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW], - return_policy_uri='return_policy_uri_value', - accept_defective_only=True, - process_refund_days=2034, - accept_exchange=True, - return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, + name="name_value", + return_policy_id="return_policy_id_value", + label="label_value", + countries=["countries_value"], + return_methods=[ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ], + item_conditions=[ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ], + return_policy_uri="return_policy_uri_value", + accept_defective_only=True, + process_refund_days=2034, + accept_exchange=True, + return_label_source=gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT, ) # Wrap the value into a proper Response obj @@ -3711,43 +4559,63 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gsma_online_return_policy.OnlineReturnPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_online_return_policy(request) # Establish that the response is the type that we expect. assert isinstance(response, gsma_online_return_policy.OnlineReturnPolicy) - assert response.name == 'name_value' - assert response.return_policy_id == 'return_policy_id_value' - assert response.label == 'label_value' - assert response.countries == ['countries_value'] - assert response.return_methods == [gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL] - assert response.item_conditions == [gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW] - assert response.return_policy_uri == 'return_policy_uri_value' + assert response.name == "name_value" + assert response.return_policy_id == "return_policy_id_value" + assert response.label == "label_value" + assert response.countries == ["countries_value"] + assert response.return_methods == [ + gsma_online_return_policy.OnlineReturnPolicy.ReturnMethod.BY_MAIL + ] + assert response.item_conditions == [ + gsma_online_return_policy.OnlineReturnPolicy.ItemCondition.NEW + ] + assert response.return_policy_uri == "return_policy_uri_value" assert response.accept_defective_only is True assert response.process_refund_days == 2034 assert response.accept_exchange is True - assert response.return_label_source == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + assert ( + response.return_label_source + == gsma_online_return_policy.OnlineReturnPolicy.ReturnLabelSource.DOWNLOAD_AND_PRINT + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_online_return_policy_rest_interceptors(null_interceptor): transport = transports.OnlineReturnPolicyServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy") as post, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "post_create_online_return_policy_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.OnlineReturnPolicyServiceRestInterceptor, "pre_create_online_return_policy") 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.OnlineReturnPolicyServiceRestInterceptor, + "post_create_online_return_policy", + ) as post, mock.patch.object( + transports.OnlineReturnPolicyServiceRestInterceptor, + "post_create_online_return_policy_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.OnlineReturnPolicyServiceRestInterceptor, + "pre_create_online_return_policy", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb(gsma_online_return_policy.CreateOnlineReturnPolicyRequest()) + pb_message = gsma_online_return_policy.CreateOnlineReturnPolicyRequest.pb( + gsma_online_return_policy.CreateOnlineReturnPolicyRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3758,39 +4626,53 @@ def test_create_online_return_policy_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 = gsma_online_return_policy.OnlineReturnPolicy.to_json(gsma_online_return_policy.OnlineReturnPolicy()) + return_value = gsma_online_return_policy.OnlineReturnPolicy.to_json( + gsma_online_return_policy.OnlineReturnPolicy() + ) req.return_value.content = return_value request = gsma_online_return_policy.CreateOnlineReturnPolicyRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = gsma_online_return_policy.OnlineReturnPolicy() - post_with_metadata.return_value = gsma_online_return_policy.OnlineReturnPolicy(), metadata + post_with_metadata.return_value = ( + gsma_online_return_policy.OnlineReturnPolicy(), + metadata, + ) - client.create_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_online_return_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_delete_online_return_policy_rest_bad_request(request_type=online_return_policy.DeleteOnlineReturnPolicyRequest): +def test_delete_online_return_policy_rest_bad_request( + request_type=online_return_policy.DeleteOnlineReturnPolicyRequest, +): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + request_init = {"name": "accounts/sample1/onlineReturnPolicies/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() @@ -3799,30 +4681,32 @@ def test_delete_online_return_policy_rest_bad_request(request_type=online_return client.delete_online_return_policy(request) -@pytest.mark.parametrize("request_type", [ - online_return_policy.DeleteOnlineReturnPolicyRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + online_return_policy.DeleteOnlineReturnPolicyRequest, + dict, + ], +) def test_delete_online_return_policy_rest_call_success(request_type): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/onlineReturnPolicies/sample2'} + request_init = {"name": "accounts/sample1/onlineReturnPolicies/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 = 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_online_return_policy(request) @@ -3835,15 +4719,24 @@ def test_delete_online_return_policy_rest_call_success(request_type): def test_delete_online_return_policy_rest_interceptors(null_interceptor): transport = transports.OnlineReturnPolicyServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.OnlineReturnPolicyServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.OnlineReturnPolicyServiceRestInterceptor(), + ) client = OnlineReturnPolicyServiceClient(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.OnlineReturnPolicyServiceRestInterceptor, "pre_delete_online_return_policy") 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.OnlineReturnPolicyServiceRestInterceptor, + "pre_delete_online_return_policy", + ) as pre: pre.assert_not_called() - pb_message = online_return_policy.DeleteOnlineReturnPolicyRequest.pb(online_return_policy.DeleteOnlineReturnPolicyRequest()) + pb_message = online_return_policy.DeleteOnlineReturnPolicyRequest.pb( + online_return_policy.DeleteOnlineReturnPolicyRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3856,20 +4749,26 @@ def test_delete_online_return_policy_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = online_return_policy.DeleteOnlineReturnPolicyRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_online_return_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_online_return_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() + def test_initialize_client_w_rest(): client = OnlineReturnPolicyServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -3884,8 +4783,8 @@ def test_get_online_return_policy_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_online_return_policy), - '__call__') as call: + type(client.transport.get_online_return_policy), "__call__" + ) as call: client.get_online_return_policy(request=None) # Establish that the underlying stub method was called. @@ -3906,8 +4805,8 @@ def test_list_online_return_policies_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.list_online_return_policies), - '__call__') as call: + type(client.transport.list_online_return_policies), "__call__" + ) as call: client.list_online_return_policies(request=None) # Establish that the underlying stub method was called. @@ -3928,8 +4827,8 @@ def test_create_online_return_policy_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.create_online_return_policy), - '__call__') as call: + type(client.transport.create_online_return_policy), "__call__" + ) as call: client.create_online_return_policy(request=None) # Establish that the underlying stub method was called. @@ -3950,8 +4849,8 @@ def test_delete_online_return_policy_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.delete_online_return_policy), - '__call__') as call: + type(client.transport.delete_online_return_policy), "__call__" + ) as call: client.delete_online_return_policy(request=None) # Establish that the underlying stub method was called. @@ -3972,18 +4871,21 @@ def test_transport_grpc_default(): transports.OnlineReturnPolicyServiceGrpcTransport, ) + def test_online_return_policy_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.OnlineReturnPolicyServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_online_return_policy_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.OnlineReturnPolicyServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3992,10 +4894,10 @@ def test_online_return_policy_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_online_return_policy', - 'list_online_return_policies', - 'create_online_return_policy', - 'delete_online_return_policy', + "get_online_return_policy", + "list_online_return_policies", + "create_online_return_policy", + "delete_online_return_policy", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4006,7 +4908,7 @@ def test_online_return_policy_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4015,25 +4917,30 @@ def test_online_return_policy_service_base_transport(): def test_online_return_policy_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_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._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_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OnlineReturnPolicyServiceTransport( 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_online_return_policy_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_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.online_return_policy_service.transports.OnlineReturnPolicyServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.OnlineReturnPolicyServiceTransport() @@ -4042,14 +4949,12 @@ def test_online_return_policy_service_base_transport_with_adc(): def test_online_return_policy_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) OnlineReturnPolicyServiceClient() 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, ) @@ -4064,12 +4969,12 @@ def test_online_return_policy_service_auth_adc(): def test_online_return_policy_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", ) @@ -4083,48 +4988,47 @@ def test_online_return_policy_service_transport_auth_adc(transport_class): ], ) def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, grpc_helpers), - (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_online_return_policy_service_transport_create_channel(transport_class, grpc_helpers): +def test_online_return_policy_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, @@ -4135,9 +5039,15 @@ def test_online_return_policy_service_transport_create_channel(transport_class, ) -@pytest.mark.parametrize("transport_class", [transports.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + ], +) def test_online_return_policy_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -4147,7 +5057,7 @@ def test_online_return_policy_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", @@ -4168,62 +5078,80 @@ def test_online_return_policy_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_online_return_policy_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.OnlineReturnPolicyServiceRestTransport ( - 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.OnlineReturnPolicyServiceRestTransport( + 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_online_return_policy_service_host_no_port(transport_name): client = OnlineReturnPolicyServiceClient( 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_online_return_policy_service_host_with_port(transport_name): client = OnlineReturnPolicyServiceClient( 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", -]) -def test_online_return_policy_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_online_return_policy_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = OnlineReturnPolicyServiceClient( @@ -4246,8 +5174,10 @@ def test_online_return_policy_service_client_transport_session_collision(transpo session1 = client1.transport.delete_online_return_policy._session session2 = client2.transport.delete_online_return_policy._session assert session1 != session2 + + def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport( @@ -4260,7 +5190,7 @@ def test_online_return_policy_service_grpc_transport_channel(): def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcAsyncIOTransport( @@ -4274,12 +5204,22 @@ def test_online_return_policy_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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + ], +) def test_online_return_policy_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 @@ -4288,7 +5228,7 @@ def test_online_return_policy_service_transport_channel_mtls_with_client_cert_so 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", @@ -4318,17 +5258,23 @@ def test_online_return_policy_service_transport_channel_mtls_with_client_cert_so # 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.OnlineReturnPolicyServiceGrpcTransport, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport]) -def test_online_return_policy_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.OnlineReturnPolicyServiceGrpcTransport, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + ], +) +def test_online_return_policy_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() @@ -4359,8 +5305,13 @@ def test_online_return_policy_service_transport_channel_mtls_with_adc( def test_online_return_policy_path(): account = "squid" return_policy = "clam" - expected = "accounts/{account}/onlineReturnPolicies/{return_policy}".format(account=account, return_policy=return_policy, ) - actual = OnlineReturnPolicyServiceClient.online_return_policy_path(account, return_policy) + expected = "accounts/{account}/onlineReturnPolicies/{return_policy}".format( + account=account, + return_policy=return_policy, + ) + actual = OnlineReturnPolicyServiceClient.online_return_policy_path( + account, return_policy + ) assert expected == actual @@ -4375,10 +5326,15 @@ def test_parse_online_return_policy_path(): actual = OnlineReturnPolicyServiceClient.parse_online_return_policy_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = OnlineReturnPolicyServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = OnlineReturnPolicyServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -4392,9 +5348,12 @@ def test_parse_common_billing_account_path(): actual = OnlineReturnPolicyServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = OnlineReturnPolicyServiceClient.common_folder_path(folder) assert expected == actual @@ -4409,9 +5368,12 @@ def test_parse_common_folder_path(): actual = OnlineReturnPolicyServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = OnlineReturnPolicyServiceClient.common_organization_path(organization) assert expected == actual @@ -4426,9 +5388,12 @@ def test_parse_common_organization_path(): actual = OnlineReturnPolicyServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = OnlineReturnPolicyServiceClient.common_project_path(project) assert expected == actual @@ -4443,10 +5408,14 @@ def test_parse_common_project_path(): actual = OnlineReturnPolicyServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = OnlineReturnPolicyServiceClient.common_location_path(project, location) assert expected == actual @@ -4466,14 +5435,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.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.OnlineReturnPolicyServiceTransport, "_prep_wrapped_messages" + ) as prep: client = OnlineReturnPolicyServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.OnlineReturnPolicyServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.OnlineReturnPolicyServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = OnlineReturnPolicyServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -4484,10 +5457,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = OnlineReturnPolicyServiceClient( - 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() @@ -4496,10 +5470,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = OnlineReturnPolicyServiceAsyncClient( - 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() @@ -4507,10 +5482,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = OnlineReturnPolicyServiceClient( - 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() @@ -4518,13 +5494,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = OnlineReturnPolicyServiceClient( - 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: @@ -4533,10 +5508,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (OnlineReturnPolicyServiceClient, transports.OnlineReturnPolicyServiceGrpcTransport), - (OnlineReturnPolicyServiceAsyncClient, transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + OnlineReturnPolicyServiceClient, + transports.OnlineReturnPolicyServiceGrpcTransport, + ), + ( + OnlineReturnPolicyServiceAsyncClient, + transports.OnlineReturnPolicyServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -4551,7 +5536,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py similarity index 70% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py index 1762b7ef772c..d5c440e62e7b 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_programs_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_programs_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,45 +22,43 @@ 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.shopping.merchant_accounts_v1.services.programs_service import ProgramsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.programs_service import ProgramsServiceClient -from google.shopping.merchant_accounts_v1.services.programs_service import pagers -from google.shopping.merchant_accounts_v1.services.programs_service import transports -from google.shopping.merchant_accounts_v1.types import programs -import google.auth - +from google.shopping.merchant_accounts_v1.services.programs_service import ( + ProgramsServiceAsyncClient, + ProgramsServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import programs CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,228 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ProgramsServiceClient._get_default_mtls_endpoint(None) is None - assert ProgramsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProgramsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + ProgramsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ProgramsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ProgramsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProgramsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProgramsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + def test__read_environment_variables(): assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ProgramsServiceClient._read_environment_variables() == (True, "auto", None) + assert ProgramsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + assert ProgramsServiceClient._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: ProgramsServiceClient._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 ProgramsServiceClient._read_environment_variables() == (False, "never", None) + assert ProgramsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ProgramsServiceClient._read_environment_variables() == (False, "always", None) + assert ProgramsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ProgramsServiceClient._read_environment_variables() == (False, "auto", None) + assert ProgramsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ProgramsServiceClient._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 ProgramsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, False) is None - assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + ProgramsServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ProgramsServiceClient._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 ProgramsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ProgramsServiceClient._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 ( + ProgramsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ProgramsServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) + +@mock.patch.object( + ProgramsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceClient), +) +@mock.patch.object( + ProgramsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert ProgramsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProgramsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ProgramsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + ProgramsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ProgramsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "always") + == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ProgramsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ProgramsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ProgramsServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ProgramsServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - ProgramsServiceClient._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." + ProgramsServiceClient._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 ProgramsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ProgramsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ProgramsServiceClient._get_universe_domain(None, None) == ProgramsServiceClient._DEFAULT_UNIVERSE + assert ( + ProgramsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ProgramsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ProgramsServiceClient._get_universe_domain(None, None) + == ProgramsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: ProgramsServiceClient._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) @@ -215,7 +353,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") @@ -228,14 +367,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", [ - (ProgramsServiceClient, "grpc"), - (ProgramsServiceAsyncClient, "grpc_asyncio"), - (ProgramsServiceClient, "rest"), -]) -def test_programs_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ProgramsServiceClient, "grpc"), + (ProgramsServiceAsyncClient, "grpc_asyncio"), + (ProgramsServiceClient, "rest"), + ], +) +def test_programs_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) @@ -243,52 +390,70 @@ def test_programs_service_client_from_service_account_info(client_class, transpo 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.ProgramsServiceGrpcTransport, "grpc"), - (transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProgramsServiceRestTransport, "rest"), -]) -def test_programs_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.ProgramsServiceGrpcTransport, "grpc"), + (transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProgramsServiceRestTransport, "rest"), + ], +) +def test_programs_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", [ - (ProgramsServiceClient, "grpc"), - (ProgramsServiceAsyncClient, "grpc_asyncio"), - (ProgramsServiceClient, "rest"), -]) -def test_programs_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ProgramsServiceClient, "grpc"), + (ProgramsServiceAsyncClient, "grpc_asyncio"), + (ProgramsServiceClient, "rest"), + ], +) +def test_programs_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" ) @@ -304,30 +469,45 @@ def test_programs_service_client_get_transport_class(): assert transport == transports.ProgramsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), -]) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) -def test_programs_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + ( + ProgramsServiceAsyncClient, + transports.ProgramsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + ProgramsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceClient), +) +@mock.patch.object( + ProgramsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceAsyncClient), +) +def test_programs_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(ProgramsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(ProgramsServiceClient, "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(ProgramsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(ProgramsServiceClient, "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( @@ -345,13 +525,15 @@ def test_programs_service_client_client_options(client_class, transport_class, t # 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, @@ -363,7 +545,7 @@ def test_programs_service_client_client_options(client_class, transport_class, t # 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( @@ -383,23 +565,33 @@ def test_programs_service_client_client_options(client_class, transport_class, t 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", @@ -408,48 +600,102 @@ def test_programs_service_client_client_options(client_class, transport_class, t 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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "true"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", "false"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "true"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + ProgramsServiceClient, + transports.ProgramsServiceGrpcTransport, + "grpc", + "true", + ), + ( + ProgramsServiceAsyncClient, + transports.ProgramsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + ProgramsServiceClient, + transports.ProgramsServiceGrpcTransport, + "grpc", + "false", + ), + ( + ProgramsServiceAsyncClient, + transports.ProgramsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + ProgramsServiceClient, + transports.ProgramsServiceRestTransport, + "rest", + "true", + ), + ( + ProgramsServiceClient, + transports.ProgramsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + ProgramsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceClient), +) +@mock.patch.object( + ProgramsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_programs_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_programs_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 @@ -468,12 +714,22 @@ def test_programs_service_client_mtls_env_auto(client_class, transport_class, tr # 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 @@ -494,15 +750,22 @@ def test_programs_service_client_mtls_env_auto(client_class, transport_class, tr ) # 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, @@ -512,19 +775,31 @@ def test_programs_service_client_mtls_env_auto(client_class, transport_class, tr ) -@pytest.mark.parametrize("client_class", [ - ProgramsServiceClient, ProgramsServiceAsyncClient -]) -@mock.patch.object(ProgramsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProgramsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [ProgramsServiceClient, ProgramsServiceAsyncClient] +) +@mock.patch.object( + ProgramsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProgramsServiceClient), +) +@mock.patch.object( + ProgramsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProgramsServiceAsyncClient), +) def test_programs_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 @@ -532,8 +807,12 @@ def test_programs_service_client_get_mtls_endpoint_and_cert_source(client_class) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -551,16 +830,28 @@ def test_programs_service_client_get_mtls_endpoint_and_cert_source(client_class) # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -570,34 +861,62 @@ def test_programs_service_client_get_mtls_endpoint_and_cert_source(client_class) with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # 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", [ - ProgramsServiceClient, ProgramsServiceAsyncClient -]) -@mock.patch.object(ProgramsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceClient)) -@mock.patch.object(ProgramsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ProgramsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [ProgramsServiceClient, ProgramsServiceAsyncClient] +) +@mock.patch.object( + ProgramsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceClient), +) +@mock.patch.object( + ProgramsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProgramsServiceAsyncClient), +) def test_programs_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ProgramsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = ProgramsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ProgramsServiceClient._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", @@ -620,11 +939,19 @@ def test_programs_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. @@ -632,27 +959,40 @@ def test_programs_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", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), -]) -def test_programs_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc"), + ( + ProgramsServiceAsyncClient, + transports.ProgramsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest"), + ], +) +def test_programs_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, @@ -661,24 +1001,40 @@ def test_programs_service_client_client_options_scopes(client_class, transport_c api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", None), -]) -def test_programs_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", + [ + ( + ProgramsServiceClient, + transports.ProgramsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ProgramsServiceAsyncClient, + transports.ProgramsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ProgramsServiceClient, transports.ProgramsServiceRestTransport, "rest", None), + ], +) +def test_programs_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, @@ -687,11 +1043,14 @@ def test_programs_service_client_client_options_credentials_file(client_class, t api_audience=None, ) + def test_programs_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = ProgramsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1065,38 @@ def test_programs_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport, "grpc", grpc_helpers), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_programs_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", + [ + ( + ProgramsServiceClient, + transports.ProgramsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ProgramsServiceAsyncClient, + transports.ProgramsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_programs_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, @@ -749,9 +1123,7 @@ def test_programs_service_client_create_channel_credentials_file(client_class, t 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, @@ -762,11 +1134,14 @@ def test_programs_service_client_create_channel_credentials_file(client_class, t ) -@pytest.mark.parametrize("request_type", [ - programs.GetProgramRequest, - dict, -]) -def test_get_program(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + programs.GetProgramRequest, + dict, + ], +) +def test_get_program(request_type, transport: str = "grpc"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -777,15 +1152,13 @@ def test_get_program(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', + name="name_value", + documentation_uri="documentation_uri_value", state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], + active_region_codes=["active_region_codes_value"], ) response = client.get_program(request) @@ -797,10 +1170,10 @@ def test_get_program(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] def test_get_program_non_empty_request_with_auto_populated_field(): @@ -808,28 +1181,29 @@ def test_get_program_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProgramsServiceClient( 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 = programs.GetProgramRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.get_program), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_program(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == programs.GetProgramRequest( - name='name_value', + name="name_value", ) + def test_get_program_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -848,7 +1222,9 @@ def test_get_program_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_program] = mock_rpc request = {} client.get_program(request) @@ -862,8 +1238,11 @@ def test_get_program_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_program_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_program_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 +1256,17 @@ async def test_get_program_async_use_cached_wrapped_rpc(transport: str = "grpc_a wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_program in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_program + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_program] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_program + ] = mock_rpc request = {} await client.get_program(request) @@ -896,8 +1280,11 @@ async def test_get_program_async_use_cached_wrapped_rpc(transport: str = "grpc_a assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_program_async(transport: str = 'grpc_asyncio', request_type=programs.GetProgramRequest): +async def test_get_program_async( + transport: str = "grpc_asyncio", request_type=programs.GetProgramRequest +): client = ProgramsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -908,16 +1295,16 @@ async def test_get_program_async(transport: str = 'grpc_asyncio', request_type=p request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.Program( + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], + ) + ) response = await client.get_program(request) # Establish that the underlying gRPC stub method was called. @@ -928,16 +1315,17 @@ async def test_get_program_async(transport: str = 'grpc_asyncio', request_type=p # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] @pytest.mark.asyncio async def test_get_program_async_from_dict(): await test_get_program_async(request_type=dict) + def test_get_program_field_headers(): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -947,12 +1335,10 @@ def test_get_program_field_headers(): # a field header. Set these to a non-empty value. request = programs.GetProgramRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: call.return_value = programs.Program() client.get_program(request) @@ -964,9 +1350,9 @@ def test_get_program_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 @@ -979,12 +1365,10 @@ async def test_get_program_field_headers_async(): # a field header. Set these to a non-empty value. request = programs.GetProgramRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) await client.get_program(request) @@ -996,9 +1380,9 @@ async def test_get_program_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_program_flattened(): @@ -1007,15 +1391,13 @@ def test_get_program_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_program( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1023,7 +1405,7 @@ def test_get_program_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 @@ -1037,9 +1419,10 @@ def test_get_program_flattened_error(): with pytest.raises(ValueError): client.get_program( programs.GetProgramRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_program_flattened_async(): client = ProgramsServiceAsyncClient( @@ -1047,9 +1430,7 @@ async def test_get_program_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program() @@ -1057,7 +1438,7 @@ async def test_get_program_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_program( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1065,9 +1446,10 @@ async def test_get_program_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_program_flattened_error_async(): client = ProgramsServiceAsyncClient( @@ -1079,15 +1461,18 @@ async def test_get_program_flattened_error_async(): with pytest.raises(ValueError): await client.get_program( programs.GetProgramRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - programs.ListProgramsRequest, - dict, -]) -def test_list_programs(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + programs.ListProgramsRequest, + dict, + ], +) +def test_list_programs(request_type, transport: str = "grpc"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1098,12 +1483,10 @@ def test_list_programs(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.ListProgramsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_programs(request) @@ -1115,7 +1498,7 @@ def test_list_programs(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProgramsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_programs_non_empty_request_with_auto_populated_field(): @@ -1123,30 +1506,31 @@ def test_list_programs_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProgramsServiceClient( 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 = programs.ListProgramsRequest( - 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_programs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_programs(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == programs.ListProgramsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_programs_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1165,7 +1549,9 @@ def test_list_programs_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_programs] = mock_rpc request = {} client.list_programs(request) @@ -1179,8 +1565,11 @@ def test_list_programs_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_programs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_programs_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: @@ -1194,12 +1583,17 @@ async def test_list_programs_async_use_cached_wrapped_rpc(transport: str = "grpc wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_programs in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_programs + 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_programs] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_programs + ] = mock_rpc request = {} await client.list_programs(request) @@ -1213,8 +1607,11 @@ async def test_list_programs_async_use_cached_wrapped_rpc(transport: str = "grpc assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_programs_async(transport: str = 'grpc_asyncio', request_type=programs.ListProgramsRequest): +async def test_list_programs_async( + transport: str = "grpc_asyncio", request_type=programs.ListProgramsRequest +): client = ProgramsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1225,13 +1622,13 @@ async def test_list_programs_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.ListProgramsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_programs(request) # Establish that the underlying gRPC stub method was called. @@ -1242,13 +1639,14 @@ async def test_list_programs_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProgramsAsyncPager) - 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_programs_async_from_dict(): await test_list_programs_async(request_type=dict) + def test_list_programs_field_headers(): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1258,12 +1656,10 @@ def test_list_programs_field_headers(): # a field header. Set these to a non-empty value. request = programs.ListProgramsRequest() - 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_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: call.return_value = programs.ListProgramsResponse() client.list_programs(request) @@ -1275,9 +1671,9 @@ def test_list_programs_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 @@ -1290,13 +1686,13 @@ async def test_list_programs_field_headers_async(): # a field header. Set these to a non-empty value. request = programs.ListProgramsRequest() - 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_programs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.ListProgramsResponse() + ) await client.list_programs(request) # Establish that the underlying gRPC stub method was called. @@ -1307,9 +1703,9 @@ async def test_list_programs_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_programs_flattened(): @@ -1318,15 +1714,13 @@ def test_list_programs_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.ListProgramsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_programs( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1334,7 +1728,7 @@ def test_list_programs_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 @@ -1348,9 +1742,10 @@ def test_list_programs_flattened_error(): with pytest.raises(ValueError): client.list_programs( programs.ListProgramsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_programs_flattened_async(): client = ProgramsServiceAsyncClient( @@ -1358,17 +1753,17 @@ async def test_list_programs_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.ListProgramsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.ListProgramsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_programs( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1376,9 +1771,10 @@ async def test_list_programs_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_programs_flattened_error_async(): client = ProgramsServiceAsyncClient( @@ -1390,7 +1786,7 @@ async def test_list_programs_flattened_error_async(): with pytest.raises(ValueError): await client.list_programs( programs.ListProgramsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1401,9 +1797,7 @@ def test_list_programs_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_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( programs.ListProgramsResponse( @@ -1412,17 +1806,17 @@ def test_list_programs_pager(transport_name: str = "grpc"): programs.Program(), programs.Program(), ], - next_page_token='abc', + next_page_token="abc", ), programs.ListProgramsResponse( programs=[], - next_page_token='def', + next_page_token="def", ), programs.ListProgramsResponse( programs=[ programs.Program(), ], - next_page_token='ghi', + next_page_token="ghi", ), programs.ListProgramsResponse( programs=[ @@ -1437,9 +1831,7 @@ def test_list_programs_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_programs(request={}, retry=retry, timeout=timeout) @@ -1449,8 +1841,9 @@ def test_list_programs_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, programs.Program) - for i in results) + assert all(isinstance(i, programs.Program) for i in results) + + def test_list_programs_pages(transport_name: str = "grpc"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1458,9 +1851,7 @@ def test_list_programs_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_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( programs.ListProgramsResponse( @@ -1469,17 +1860,17 @@ def test_list_programs_pages(transport_name: str = "grpc"): programs.Program(), programs.Program(), ], - next_page_token='abc', + next_page_token="abc", ), programs.ListProgramsResponse( programs=[], - next_page_token='def', + next_page_token="def", ), programs.ListProgramsResponse( programs=[ programs.Program(), ], - next_page_token='ghi', + next_page_token="ghi", ), programs.ListProgramsResponse( programs=[ @@ -1490,9 +1881,10 @@ def test_list_programs_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_programs(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_programs_async_pager(): client = ProgramsServiceAsyncClient( @@ -1501,8 +1893,8 @@ async def test_list_programs_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_programs), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_programs), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( programs.ListProgramsResponse( @@ -1511,17 +1903,17 @@ async def test_list_programs_async_pager(): programs.Program(), programs.Program(), ], - next_page_token='abc', + next_page_token="abc", ), programs.ListProgramsResponse( programs=[], - next_page_token='def', + next_page_token="def", ), programs.ListProgramsResponse( programs=[ programs.Program(), ], - next_page_token='ghi', + next_page_token="ghi", ), programs.ListProgramsResponse( programs=[ @@ -1531,15 +1923,16 @@ async def test_list_programs_async_pager(): ), RuntimeError, ) - async_pager = await client.list_programs(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_programs( + 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, programs.Program) - for i in responses) + assert all(isinstance(i, programs.Program) for i in responses) @pytest.mark.asyncio @@ -1550,8 +1943,8 @@ async def test_list_programs_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_programs), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_programs), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( programs.ListProgramsResponse( @@ -1560,17 +1953,17 @@ async def test_list_programs_async_pages(): programs.Program(), programs.Program(), ], - next_page_token='abc', + next_page_token="abc", ), programs.ListProgramsResponse( programs=[], - next_page_token='def', + next_page_token="def", ), programs.ListProgramsResponse( programs=[ programs.Program(), ], - next_page_token='ghi', + next_page_token="ghi", ), programs.ListProgramsResponse( programs=[ @@ -1583,18 +1976,22 @@ async def test_list_programs_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_programs(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", [ - programs.EnableProgramRequest, - dict, -]) -def test_enable_program(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + programs.EnableProgramRequest, + dict, + ], +) +def test_enable_program(request_type, transport: str = "grpc"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1605,15 +2002,13 @@ def test_enable_program(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', + name="name_value", + documentation_uri="documentation_uri_value", state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], + active_region_codes=["active_region_codes_value"], ) response = client.enable_program(request) @@ -1625,10 +2020,10 @@ def test_enable_program(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] def test_enable_program_non_empty_request_with_auto_populated_field(): @@ -1636,28 +2031,29 @@ def test_enable_program_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProgramsServiceClient( 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 = programs.EnableProgramRequest( - 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.enable_program), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.enable_program(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == programs.EnableProgramRequest( - name='name_value', + name="name_value", ) + def test_enable_program_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1676,7 +2072,9 @@ def test_enable_program_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc request = {} client.enable_program(request) @@ -1690,8 +2088,11 @@ def test_enable_program_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_enable_program_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_enable_program_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: @@ -1705,12 +2106,17 @@ async def test_enable_program_async_use_cached_wrapped_rpc(transport: str = "grp wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.enable_program in client._client._transport._wrapped_methods + assert ( + client._client._transport.enable_program + 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.enable_program] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.enable_program + ] = mock_rpc request = {} await client.enable_program(request) @@ -1724,8 +2130,11 @@ async def test_enable_program_async_use_cached_wrapped_rpc(transport: str = "grp assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_enable_program_async(transport: str = 'grpc_asyncio', request_type=programs.EnableProgramRequest): +async def test_enable_program_async( + transport: str = "grpc_asyncio", request_type=programs.EnableProgramRequest +): client = ProgramsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1736,16 +2145,16 @@ async def test_enable_program_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.Program( + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], + ) + ) response = await client.enable_program(request) # Establish that the underlying gRPC stub method was called. @@ -1756,16 +2165,17 @@ async def test_enable_program_async(transport: str = 'grpc_asyncio', request_typ # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] @pytest.mark.asyncio async def test_enable_program_async_from_dict(): await test_enable_program_async(request_type=dict) + def test_enable_program_field_headers(): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1775,12 +2185,10 @@ def test_enable_program_field_headers(): # a field header. Set these to a non-empty value. request = programs.EnableProgramRequest() - 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.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: call.return_value = programs.Program() client.enable_program(request) @@ -1792,9 +2200,9 @@ def test_enable_program_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 @@ -1807,12 +2215,10 @@ async def test_enable_program_field_headers_async(): # a field header. Set these to a non-empty value. request = programs.EnableProgramRequest() - 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.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) await client.enable_program(request) @@ -1824,9 +2230,9 @@ async def test_enable_program_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_enable_program_flattened(): @@ -1835,15 +2241,13 @@ def test_enable_program_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.enable_program( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1851,7 +2255,7 @@ def test_enable_program_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 @@ -1865,9 +2269,10 @@ def test_enable_program_flattened_error(): with pytest.raises(ValueError): client.enable_program( programs.EnableProgramRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_enable_program_flattened_async(): client = ProgramsServiceAsyncClient( @@ -1875,9 +2280,7 @@ async def test_enable_program_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program() @@ -1885,7 +2288,7 @@ async def test_enable_program_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.enable_program( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1893,9 +2296,10 @@ async def test_enable_program_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_enable_program_flattened_error_async(): client = ProgramsServiceAsyncClient( @@ -1907,15 +2311,18 @@ async def test_enable_program_flattened_error_async(): with pytest.raises(ValueError): await client.enable_program( programs.EnableProgramRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - programs.DisableProgramRequest, - dict, -]) -def test_disable_program(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + programs.DisableProgramRequest, + dict, + ], +) +def test_disable_program(request_type, transport: str = "grpc"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1926,15 +2333,13 @@ def test_disable_program(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', + name="name_value", + documentation_uri="documentation_uri_value", state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], + active_region_codes=["active_region_codes_value"], ) response = client.disable_program(request) @@ -1946,10 +2351,10 @@ def test_disable_program(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] def test_disable_program_non_empty_request_with_auto_populated_field(): @@ -1957,28 +2362,29 @@ def test_disable_program_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ProgramsServiceClient( 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 = programs.DisableProgramRequest( - 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.disable_program), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.disable_program(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == programs.DisableProgramRequest( - name='name_value', + name="name_value", ) + def test_disable_program_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1997,7 +2403,9 @@ def test_disable_program_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc request = {} client.disable_program(request) @@ -2011,8 +2419,11 @@ def test_disable_program_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_disable_program_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_disable_program_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: @@ -2026,12 +2437,17 @@ async def test_disable_program_async_use_cached_wrapped_rpc(transport: str = "gr wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.disable_program in client._client._transport._wrapped_methods + assert ( + client._client._transport.disable_program + 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.disable_program] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.disable_program + ] = mock_rpc request = {} await client.disable_program(request) @@ -2045,8 +2461,11 @@ async def test_disable_program_async_use_cached_wrapped_rpc(transport: str = "gr assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_disable_program_async(transport: str = 'grpc_asyncio', request_type=programs.DisableProgramRequest): +async def test_disable_program_async( + transport: str = "grpc_asyncio", request_type=programs.DisableProgramRequest +): client = ProgramsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2057,16 +2476,16 @@ async def test_disable_program_async(transport: str = 'grpc_asyncio', request_ty request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.Program( + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], + ) + ) response = await client.disable_program(request) # Establish that the underlying gRPC stub method was called. @@ -2077,16 +2496,17 @@ async def test_disable_program_async(transport: str = 'grpc_asyncio', request_ty # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] @pytest.mark.asyncio async def test_disable_program_async_from_dict(): await test_disable_program_async(request_type=dict) + def test_disable_program_field_headers(): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2096,12 +2516,10 @@ def test_disable_program_field_headers(): # a field header. Set these to a non-empty value. request = programs.DisableProgramRequest() - 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.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: call.return_value = programs.Program() client.disable_program(request) @@ -2113,9 +2531,9 @@ def test_disable_program_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 @@ -2128,12 +2546,10 @@ async def test_disable_program_field_headers_async(): # a field header. Set these to a non-empty value. request = programs.DisableProgramRequest() - 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.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program()) await client.disable_program(request) @@ -2145,9 +2561,9 @@ async def test_disable_program_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_disable_program_flattened(): @@ -2156,15 +2572,13 @@ def test_disable_program_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.disable_program( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2172,7 +2586,7 @@ def test_disable_program_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 @@ -2186,9 +2600,10 @@ def test_disable_program_flattened_error(): with pytest.raises(ValueError): client.disable_program( programs.DisableProgramRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_disable_program_flattened_async(): client = ProgramsServiceAsyncClient( @@ -2196,9 +2611,7 @@ async def test_disable_program_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = programs.Program() @@ -2206,7 +2619,7 @@ async def test_disable_program_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.disable_program( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2214,9 +2627,10 @@ async def test_disable_program_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_disable_program_flattened_error_async(): client = ProgramsServiceAsyncClient( @@ -2228,7 +2642,7 @@ async def test_disable_program_flattened_error_async(): with pytest.raises(ValueError): await client.disable_program( programs.DisableProgramRequest(), - name='name_value', + name="name_value", ) @@ -2250,7 +2664,9 @@ def test_get_program_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_program] = mock_rpc request = {} @@ -2273,48 +2689,51 @@ def test_get_program_rest_required_fields(request_type=programs.GetProgramReques request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_program._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_program._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_program._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_program._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 = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = programs.Program() # Mock the http request 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 @@ -2325,24 +2744,24 @@ def test_get_program_rest_required_fields(request_type=programs.GetProgramReques return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_program(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_program_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_program._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_program_rest_flattened(): @@ -2352,16 +2771,16 @@ def test_get_program_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 = programs.Program() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2'} + sample_request = {"name": "accounts/sample1/programs/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2371,7 +2790,7 @@ def test_get_program_rest_flattened(): # Convert return value to protobuf type return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2381,10 +2800,13 @@ def test_get_program_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/programs/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/programs/*}" % client.transport._host, + args[1], + ) -def test_get_program_rest_flattened_error(transport: str = 'rest'): +def test_get_program_rest_flattened_error(transport: str = "rest"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2395,7 +2817,7 @@ def test_get_program_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_program( programs.GetProgramRequest(), - name='name_value', + name="name_value", ) @@ -2417,7 +2839,9 @@ def test_list_programs_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_programs] = mock_rpc request = {} @@ -2440,50 +2864,58 @@ def test_list_programs_rest_required_fields(request_type=programs.ListProgramsRe 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_programs._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_programs._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_programs._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_programs._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 = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = programs.ListProgramsResponse() # Mock the http request 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 @@ -2494,24 +2926,32 @@ def test_list_programs_rest_required_fields(request_type=programs.ListProgramsRe return_value = programs.ListProgramsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_programs(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_programs_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_programs._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_programs_rest_flattened(): @@ -2521,16 +2961,16 @@ def test_list_programs_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 = programs.ListProgramsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -2540,7 +2980,7 @@ def test_list_programs_rest_flattened(): # Convert return value to protobuf type return_value = programs.ListProgramsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2550,10 +2990,13 @@ def test_list_programs_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/programs" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/programs" % client.transport._host, + args[1], + ) -def test_list_programs_rest_flattened_error(transport: str = 'rest'): +def test_list_programs_rest_flattened_error(transport: str = "rest"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2564,20 +3007,20 @@ def test_list_programs_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_programs( programs.ListProgramsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_programs_rest_pager(transport: str = 'rest'): +def test_list_programs_rest_pager(transport: str = "rest"): client = ProgramsServiceClient( 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 = ( programs.ListProgramsResponse( @@ -2586,17 +3029,17 @@ def test_list_programs_rest_pager(transport: str = 'rest'): programs.Program(), programs.Program(), ], - next_page_token='abc', + next_page_token="abc", ), programs.ListProgramsResponse( programs=[], - next_page_token='def', + next_page_token="def", ), programs.ListProgramsResponse( programs=[ programs.Program(), ], - next_page_token='ghi', + next_page_token="ghi", ), programs.ListProgramsResponse( programs=[ @@ -2612,21 +3055,20 @@ def test_list_programs_rest_pager(transport: str = 'rest'): response = tuple(programs.ListProgramsResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_programs(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, programs.Program) - for i in results) + assert all(isinstance(i, programs.Program) for i in results) pages = list(client.list_programs(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 @@ -2648,7 +3090,9 @@ def test_enable_program_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.enable_program] = mock_rpc request = {} @@ -2664,57 +3108,62 @@ def test_enable_program_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_enable_program_rest_required_fields(request_type=programs.EnableProgramRequest): +def test_enable_program_rest_required_fields( + request_type=programs.EnableProgramRequest, +): transport_class = transports.ProgramsServiceRestTransport 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()).enable_program._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_program._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()).enable_program._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_program._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 = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = programs.Program() # Mock the http request 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() @@ -2724,24 +3173,24 @@ def test_enable_program_rest_required_fields(request_type=programs.EnableProgram return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.enable_program(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_enable_program_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.enable_program._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_enable_program_rest_flattened(): @@ -2751,16 +3200,16 @@ def test_enable_program_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 = programs.Program() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2'} + sample_request = {"name": "accounts/sample1/programs/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2770,7 +3219,7 @@ def test_enable_program_rest_flattened(): # Convert return value to protobuf type return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2780,10 +3229,14 @@ def test_enable_program_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/programs/*}:enable" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/programs/*}:enable" + % client.transport._host, + args[1], + ) -def test_enable_program_rest_flattened_error(transport: str = 'rest'): +def test_enable_program_rest_flattened_error(transport: str = "rest"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2794,7 +3247,7 @@ def test_enable_program_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.enable_program( programs.EnableProgramRequest(), - name='name_value', + name="name_value", ) @@ -2816,7 +3269,9 @@ def test_disable_program_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.disable_program] = mock_rpc request = {} @@ -2832,57 +3287,62 @@ def test_disable_program_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_disable_program_rest_required_fields(request_type=programs.DisableProgramRequest): +def test_disable_program_rest_required_fields( + request_type=programs.DisableProgramRequest, +): transport_class = transports.ProgramsServiceRestTransport 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()).disable_program._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_program._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()).disable_program._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).disable_program._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 = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = programs.Program() # Mock the http request 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() @@ -2892,24 +3352,24 @@ def test_disable_program_rest_required_fields(request_type=programs.DisableProgr return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.disable_program(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_disable_program_rest_unset_required_fields(): - transport = transports.ProgramsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.ProgramsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.disable_program._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_disable_program_rest_flattened(): @@ -2919,16 +3379,16 @@ def test_disable_program_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 = programs.Program() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/programs/sample2'} + sample_request = {"name": "accounts/sample1/programs/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2938,7 +3398,7 @@ def test_disable_program_rest_flattened(): # Convert return value to protobuf type return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2948,10 +3408,14 @@ def test_disable_program_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/programs/*}:disable" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/programs/*}:disable" + % client.transport._host, + args[1], + ) -def test_disable_program_rest_flattened_error(transport: str = 'rest'): +def test_disable_program_rest_flattened_error(transport: str = "rest"): client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2962,7 +3426,7 @@ def test_disable_program_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.disable_program( programs.DisableProgramRequest(), - name='name_value', + name="name_value", ) @@ -3004,8 +3468,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ProgramsServiceClient( - 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. @@ -3027,6 +3490,7 @@ def test_transport_instance(): client = ProgramsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProgramsServiceGrpcTransport( @@ -3041,18 +3505,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.ProgramsServiceGrpcTransport, - transports.ProgramsServiceGrpcAsyncIOTransport, - transports.ProgramsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + transports.ProgramsServiceRestTransport, + ], +) 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 = ProgramsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3062,8 +3531,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3077,9 +3545,7 @@ def test_get_program_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: call.return_value = programs.Program() client.get_program(request=None) @@ -3100,9 +3566,7 @@ def test_list_programs_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: call.return_value = programs.ListProgramsResponse() client.list_programs(request=None) @@ -3123,9 +3587,7 @@ def test_enable_program_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: call.return_value = programs.Program() client.enable_program(request=None) @@ -3146,9 +3608,7 @@ def test_disable_program_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: call.return_value = programs.Program() client.disable_program(request=None) @@ -3169,8 +3629,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ProgramsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3185,16 +3644,16 @@ async def test_get_program_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.Program( + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], + ) + ) await client.get_program(request=None) # Establish that the underlying stub method was called. @@ -3215,13 +3674,13 @@ async def test_list_programs_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.ListProgramsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.ListProgramsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_programs(request=None) # Establish that the underlying stub method was called. @@ -3242,16 +3701,16 @@ async def test_enable_program_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.Program( + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], + ) + ) await client.enable_program(request=None) # Establish that the underlying stub method was called. @@ -3272,16 +3731,16 @@ async def test_disable_program_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + programs.Program( + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], + ) + ) await client.disable_program(request=None) # Establish that the underlying stub method was called. @@ -3301,18 +3760,19 @@ def test_transport_kind_rest(): def test_get_program_rest_bad_request(request_type=programs.GetProgramRequest): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2'} + request_init = {"name": "accounts/sample1/programs/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() @@ -3321,28 +3781,30 @@ def test_get_program_rest_bad_request(request_type=programs.GetProgramRequest): client.get_program(request) -@pytest.mark.parametrize("request_type", [ - programs.GetProgramRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + programs.GetProgramRequest, + dict, + ], +) def test_get_program_rest_call_success(request_type): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2'} + request_init = {"name": "accounts/sample1/programs/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 = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], ) # Wrap the value into a proper Response obj @@ -3352,32 +3814,40 @@ def test_get_program_rest_call_success(request_type): # Convert return value to protobuf type return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_program(request) # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_program_rest_interceptors(null_interceptor): transport = transports.ProgramsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.ProgramsServiceRestInterceptor(), + ) client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_get_program") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_get_program_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_get_program") 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.ProgramsServiceRestInterceptor, "post_get_program" + ) as post, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "post_get_program_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "pre_get_program" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3396,7 +3866,7 @@ def test_get_program_rest_interceptors(null_interceptor): req.return_value.content = return_value request = programs.GetProgramRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3404,7 +3874,13 @@ def test_get_program_rest_interceptors(null_interceptor): post.return_value = programs.Program() post_with_metadata.return_value = programs.Program(), metadata - client.get_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_program( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3413,18 +3889,19 @@ def test_get_program_rest_interceptors(null_interceptor): def test_list_programs_rest_bad_request(request_type=programs.ListProgramsRequest): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3433,25 +3910,27 @@ def test_list_programs_rest_bad_request(request_type=programs.ListProgramsReques client.list_programs(request) -@pytest.mark.parametrize("request_type", [ - programs.ListProgramsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + programs.ListProgramsRequest, + dict, + ], +) def test_list_programs_rest_call_success(request_type): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = programs.ListProgramsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -3461,29 +3940,37 @@ def test_list_programs_rest_call_success(request_type): # Convert return value to protobuf type return_value = programs.ListProgramsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_programs(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProgramsPager) - 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_programs_rest_interceptors(null_interceptor): transport = transports.ProgramsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.ProgramsServiceRestInterceptor(), + ) client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_list_programs") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_list_programs_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_list_programs") 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.ProgramsServiceRestInterceptor, "post_list_programs" + ) as post, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "post_list_programs_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "pre_list_programs" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3498,11 +3985,13 @@ def test_list_programs_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 = programs.ListProgramsResponse.to_json(programs.ListProgramsResponse()) + return_value = programs.ListProgramsResponse.to_json( + programs.ListProgramsResponse() + ) req.return_value.content = return_value request = programs.ListProgramsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3510,7 +3999,13 @@ def test_list_programs_rest_interceptors(null_interceptor): post.return_value = programs.ListProgramsResponse() post_with_metadata.return_value = programs.ListProgramsResponse(), metadata - client.list_programs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_programs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3519,18 +4014,19 @@ def test_list_programs_rest_interceptors(null_interceptor): def test_enable_program_rest_bad_request(request_type=programs.EnableProgramRequest): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2'} + request_init = {"name": "accounts/sample1/programs/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() @@ -3539,28 +4035,30 @@ def test_enable_program_rest_bad_request(request_type=programs.EnableProgramRequ client.enable_program(request) -@pytest.mark.parametrize("request_type", [ - programs.EnableProgramRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + programs.EnableProgramRequest, + dict, + ], +) def test_enable_program_rest_call_success(request_type): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2'} + request_init = {"name": "accounts/sample1/programs/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 = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], ) # Wrap the value into a proper Response obj @@ -3570,32 +4068,40 @@ def test_enable_program_rest_call_success(request_type): # Convert return value to protobuf type return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.enable_program(request) # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_enable_program_rest_interceptors(null_interceptor): transport = transports.ProgramsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.ProgramsServiceRestInterceptor(), + ) client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_enable_program") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_enable_program_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_enable_program") 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.ProgramsServiceRestInterceptor, "post_enable_program" + ) as post, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "post_enable_program_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "pre_enable_program" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3614,7 +4120,7 @@ def test_enable_program_rest_interceptors(null_interceptor): req.return_value.content = return_value request = programs.EnableProgramRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3622,7 +4128,13 @@ def test_enable_program_rest_interceptors(null_interceptor): post.return_value = programs.Program() post_with_metadata.return_value = programs.Program(), metadata - client.enable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.enable_program( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3631,18 +4143,19 @@ def test_enable_program_rest_interceptors(null_interceptor): def test_disable_program_rest_bad_request(request_type=programs.DisableProgramRequest): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2'} + request_init = {"name": "accounts/sample1/programs/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() @@ -3651,28 +4164,30 @@ def test_disable_program_rest_bad_request(request_type=programs.DisableProgramRe client.disable_program(request) -@pytest.mark.parametrize("request_type", [ - programs.DisableProgramRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + programs.DisableProgramRequest, + dict, + ], +) def test_disable_program_rest_call_success(request_type): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/programs/sample2'} + request_init = {"name": "accounts/sample1/programs/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 = programs.Program( - name='name_value', - documentation_uri='documentation_uri_value', - state=programs.Program.State.NOT_ELIGIBLE, - active_region_codes=['active_region_codes_value'], + name="name_value", + documentation_uri="documentation_uri_value", + state=programs.Program.State.NOT_ELIGIBLE, + active_region_codes=["active_region_codes_value"], ) # Wrap the value into a proper Response obj @@ -3682,32 +4197,40 @@ def test_disable_program_rest_call_success(request_type): # Convert return value to protobuf type return_value = programs.Program.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.disable_program(request) # Establish that the response is the type that we expect. assert isinstance(response, programs.Program) - assert response.name == 'name_value' - assert response.documentation_uri == 'documentation_uri_value' + assert response.name == "name_value" + assert response.documentation_uri == "documentation_uri_value" assert response.state == programs.Program.State.NOT_ELIGIBLE - assert response.active_region_codes == ['active_region_codes_value'] + assert response.active_region_codes == ["active_region_codes_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) def test_disable_program_rest_interceptors(null_interceptor): transport = transports.ProgramsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProgramsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.ProgramsServiceRestInterceptor(), + ) client = ProgramsServiceClient(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.ProgramsServiceRestInterceptor, "post_disable_program") as post, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "post_disable_program_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ProgramsServiceRestInterceptor, "pre_disable_program") 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.ProgramsServiceRestInterceptor, "post_disable_program" + ) as post, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "post_disable_program_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ProgramsServiceRestInterceptor, "pre_disable_program" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3726,7 +4249,7 @@ def test_disable_program_rest_interceptors(null_interceptor): req.return_value.content = return_value request = programs.DisableProgramRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3734,16 +4257,22 @@ def test_disable_program_rest_interceptors(null_interceptor): post.return_value = programs.Program() post_with_metadata.return_value = programs.Program(), metadata - client.disable_program(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.disable_program( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = ProgramsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -3757,9 +4286,7 @@ def test_get_program_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_program), - '__call__') as call: + with mock.patch.object(type(client.transport.get_program), "__call__") as call: client.get_program(request=None) # Establish that the underlying stub method was called. @@ -3779,9 +4306,7 @@ def test_list_programs_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_programs), - '__call__') as call: + with mock.patch.object(type(client.transport.list_programs), "__call__") as call: client.list_programs(request=None) # Establish that the underlying stub method was called. @@ -3801,9 +4326,7 @@ def test_enable_program_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.enable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.enable_program), "__call__") as call: client.enable_program(request=None) # Establish that the underlying stub method was called. @@ -3823,9 +4346,7 @@ def test_disable_program_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.disable_program), - '__call__') as call: + with mock.patch.object(type(client.transport.disable_program), "__call__") as call: client.disable_program(request=None) # Establish that the underlying stub method was called. @@ -3846,18 +4367,21 @@ def test_transport_grpc_default(): transports.ProgramsServiceGrpcTransport, ) + def test_programs_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProgramsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_programs_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.ProgramsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3866,10 +4390,10 @@ def test_programs_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_program', - 'list_programs', - 'enable_program', - 'disable_program', + "get_program", + "list_programs", + "enable_program", + "disable_program", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3880,7 +4404,7 @@ def test_programs_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3889,25 +4413,30 @@ def test_programs_service_base_transport(): def test_programs_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_accounts_v1.services.programs_service.transports.ProgramsServiceTransport._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_accounts_v1.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProgramsServiceTransport( 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_programs_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_accounts_v1.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.programs_service.transports.ProgramsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProgramsServiceTransport() @@ -3916,14 +4445,12 @@ def test_programs_service_base_transport_with_adc(): def test_programs_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) ProgramsServiceClient() 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, ) @@ -3938,12 +4465,12 @@ def test_programs_service_auth_adc(): def test_programs_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", ) @@ -3957,48 +4484,45 @@ def test_programs_service_transport_auth_adc(transport_class): ], ) def test_programs_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.ProgramsServiceGrpcTransport, grpc_helpers), - (transports.ProgramsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.ProgramsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_programs_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, @@ -4009,10 +4533,14 @@ def test_programs_service_transport_create_channel(transport_class, grpc_helpers ) -@pytest.mark.parametrize("transport_class", [transports.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) -def test_programs_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + ], +) +def test_programs_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4021,7 +4549,7 @@ def test_programs_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", @@ -4042,61 +4570,77 @@ def test_programs_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_programs_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.ProgramsServiceRestTransport ( - 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.ProgramsServiceRestTransport( + 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_programs_service_host_no_port(transport_name): client = ProgramsServiceClient( 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_programs_service_host_with_port(transport_name): client = ProgramsServiceClient( 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_programs_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4120,8 +4664,10 @@ def test_programs_service_client_transport_session_collision(transport_name): session1 = client1.transport.disable_program._session session2 = client2.transport.disable_program._session assert session1 != session2 + + def test_programs_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.ProgramsServiceGrpcTransport( @@ -4134,7 +4680,7 @@ def test_programs_service_grpc_transport_channel(): def test_programs_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.ProgramsServiceGrpcAsyncIOTransport( @@ -4148,12 +4694,22 @@ def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + ], +) def test_programs_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 @@ -4162,7 +4718,7 @@ def test_programs_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", @@ -4192,17 +4748,23 @@ def test_programs_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.ProgramsServiceGrpcTransport, transports.ProgramsServiceGrpcAsyncIOTransport]) -def test_programs_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProgramsServiceGrpcTransport, + transports.ProgramsServiceGrpcAsyncIOTransport, + ], +) +def test_programs_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() @@ -4233,7 +4795,10 @@ def test_programs_service_transport_channel_mtls_with_adc( def test_program_path(): account = "squid" program = "clam" - expected = "accounts/{account}/programs/{program}".format(account=account, program=program, ) + expected = "accounts/{account}/programs/{program}".format( + account=account, + program=program, + ) actual = ProgramsServiceClient.program_path(account, program) assert expected == actual @@ -4249,9 +4814,12 @@ def test_parse_program_path(): actual = ProgramsServiceClient.parse_program_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = ProgramsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -4266,9 +4834,12 @@ def test_parse_common_billing_account_path(): actual = ProgramsServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = ProgramsServiceClient.common_folder_path(folder) assert expected == actual @@ -4283,9 +4854,12 @@ def test_parse_common_folder_path(): actual = ProgramsServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = ProgramsServiceClient.common_organization_path(organization) assert expected == actual @@ -4300,9 +4874,12 @@ def test_parse_common_organization_path(): actual = ProgramsServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = ProgramsServiceClient.common_project_path(project) assert expected == actual @@ -4317,10 +4894,14 @@ def test_parse_common_project_path(): actual = ProgramsServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = ProgramsServiceClient.common_location_path(project, location) assert expected == actual @@ -4340,14 +4921,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.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.ProgramsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = ProgramsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.ProgramsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.ProgramsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = ProgramsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -4358,10 +4943,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ProgramsServiceClient( - 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() @@ -4370,10 +4956,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ProgramsServiceAsyncClient( - 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() @@ -4381,10 +4968,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ProgramsServiceClient( - 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() @@ -4392,13 +4980,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = ProgramsServiceClient( - 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: @@ -4407,10 +4994,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport), - (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ProgramsServiceClient, transports.ProgramsServiceGrpcTransport), + (ProgramsServiceAsyncClient, transports.ProgramsServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -4425,7 +5016,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py similarity index 71% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py index dcda19f62337..c8e353c37b2f 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_regions_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_regions_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,47 +22,45 @@ 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 field_mask_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.regions_service import RegionsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.regions_service import RegionsServiceClient -from google.shopping.merchant_accounts_v1.services.regions_service import pagers -from google.shopping.merchant_accounts_v1.services.regions_service import transports -from google.shopping.merchant_accounts_v1.types import regions -import google.auth - +from google.shopping.merchant_accounts_v1.services.regions_service import ( + RegionsServiceAsyncClient, + RegionsServiceClient, + pagers, + transports, +) +from google.shopping.merchant_accounts_v1.types import regions CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -76,9 +75,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(): @@ -86,17 +87,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(): @@ -107,101 +118,228 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert RegionsServiceClient._get_default_mtls_endpoint(None) is None - assert RegionsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + RegionsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + def test__read_environment_variables(): assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert RegionsServiceClient._read_environment_variables() == (True, "auto", None) + assert RegionsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + assert RegionsServiceClient._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: RegionsServiceClient._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 RegionsServiceClient._read_environment_variables() == (False, "never", None) + assert RegionsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert RegionsServiceClient._read_environment_variables() == (False, "always", None) + assert RegionsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert RegionsServiceClient._read_environment_variables() == (False, "auto", None) + assert RegionsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: RegionsServiceClient._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 RegionsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, False) is None - assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + RegionsServiceClient._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 ( + RegionsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RegionsServiceClient._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 RegionsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert RegionsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +@mock.patch.object( + RegionsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceClient), +) +@mock.patch.object( + RegionsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = RegionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert RegionsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT - assert RegionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert RegionsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + RegionsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RegionsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionsServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + RegionsServiceClient._get_api_endpoint(None, None, default_universe, "always") + == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RegionsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionsServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + RegionsServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - RegionsServiceClient._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." + RegionsServiceClient._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 RegionsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert RegionsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert RegionsServiceClient._get_universe_domain(None, None) == RegionsServiceClient._DEFAULT_UNIVERSE + assert ( + RegionsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RegionsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RegionsServiceClient._get_universe_domain(None, None) + == RegionsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: RegionsServiceClient._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) @@ -217,7 +355,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") @@ -230,14 +369,20 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] -@pytest.mark.parametrize("client_class,transport_name", [ - (RegionsServiceClient, "grpc"), - (RegionsServiceAsyncClient, "grpc_asyncio"), - (RegionsServiceClient, "rest"), -]) + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RegionsServiceClient, "grpc"), + (RegionsServiceAsyncClient, "grpc_asyncio"), + (RegionsServiceClient, "rest"), + ], +) def test_regions_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) @@ -245,52 +390,68 @@ def test_regions_service_client_from_service_account_info(client_class, transpor 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.RegionsServiceGrpcTransport, "grpc"), - (transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RegionsServiceRestTransport, "rest"), -]) -def test_regions_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.RegionsServiceGrpcTransport, "grpc"), + (transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegionsServiceRestTransport, "rest"), + ], +) +def test_regions_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", [ - (RegionsServiceClient, "grpc"), - (RegionsServiceAsyncClient, "grpc_asyncio"), - (RegionsServiceClient, "rest"), -]) +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RegionsServiceClient, "grpc"), + (RegionsServiceAsyncClient, "grpc_asyncio"), + (RegionsServiceClient, "rest"), + ], +) def test_regions_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" ) @@ -306,30 +467,45 @@ def test_regions_service_client_get_transport_class(): assert transport == transports.RegionsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), -]) -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) -def test_regions_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + ( + RegionsServiceAsyncClient, + transports.RegionsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + RegionsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceClient), +) +@mock.patch.object( + RegionsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceAsyncClient), +) +def test_regions_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(RegionsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(RegionsServiceClient, "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(RegionsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(RegionsServiceClient, "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( @@ -347,13 +523,15 @@ def test_regions_service_client_client_options(client_class, transport_class, tr # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -365,7 +543,7 @@ def test_regions_service_client_client_options(client_class, transport_class, tr # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -385,23 +563,33 @@ def test_regions_service_client_client_options(client_class, transport_class, tr with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # Check the case 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", @@ -410,48 +598,82 @@ def test_regions_service_client_client_options(client_class, transport_class, tr api_audience=None, ) # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "true"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "false"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "true"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "true"), + ( + RegionsServiceAsyncClient, + transports.RegionsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", "false"), + ( + RegionsServiceAsyncClient, + transports.RegionsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "true"), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + RegionsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceClient), +) +@mock.patch.object( + RegionsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_regions_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_regions_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 @@ -470,12 +692,22 @@ def test_regions_service_client_mtls_env_auto(client_class, transport_class, tra # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT @@ -496,15 +728,22 @@ def test_regions_service_client_mtls_env_auto(client_class, transport_class, tra ) # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, @@ -514,19 +753,31 @@ def test_regions_service_client_mtls_env_auto(client_class, transport_class, tra ) -@pytest.mark.parametrize("client_class", [ - RegionsServiceClient, RegionsServiceAsyncClient -]) -@mock.patch.object(RegionsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegionsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [RegionsServiceClient, RegionsServiceAsyncClient] +) +@mock.patch.object( + RegionsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionsServiceClient), +) +@mock.patch.object( + RegionsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionsServiceAsyncClient), +) def test_regions_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 @@ -534,8 +785,12 @@ def test_regions_service_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -553,16 +808,28 @@ def test_regions_service_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -572,34 +839,62 @@ def test_regions_service_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # 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", [ - RegionsServiceClient, RegionsServiceAsyncClient -]) -@mock.patch.object(RegionsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceClient)) -@mock.patch.object(RegionsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(RegionsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [RegionsServiceClient, RegionsServiceAsyncClient] +) +@mock.patch.object( + RegionsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceClient), +) +@mock.patch.object( + RegionsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionsServiceAsyncClient), +) def test_regions_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = RegionsServiceClient._DEFAULT_UNIVERSE - default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = RegionsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = RegionsServiceClient._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", @@ -622,11 +917,19 @@ def test_regions_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. @@ -634,27 +937,40 @@ def test_regions_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", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), -]) -def test_regions_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc"), + ( + RegionsServiceAsyncClient, + transports.RegionsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest"), + ], +) +def test_regions_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, @@ -663,24 +979,40 @@ def test_regions_service_client_client_options_scopes(client_class, transport_cl api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", None), -]) -def test_regions_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", + [ + ( + RegionsServiceClient, + transports.RegionsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + RegionsServiceAsyncClient, + transports.RegionsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (RegionsServiceClient, transports.RegionsServiceRestTransport, "rest", None), + ], +) +def test_regions_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, @@ -689,11 +1021,14 @@ def test_regions_service_client_client_options_credentials_file(client_class, tr api_audience=None, ) + def test_regions_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = RegionsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -708,23 +1043,38 @@ def test_regions_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport, "grpc", grpc_helpers), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_regions_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", + [ + ( + RegionsServiceClient, + transports.RegionsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + RegionsServiceAsyncClient, + transports.RegionsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_regions_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, @@ -751,9 +1101,7 @@ def test_regions_service_client_create_channel_credentials_file(client_class, tr 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, @@ -764,11 +1112,14 @@ def test_regions_service_client_create_channel_credentials_file(client_class, tr ) -@pytest.mark.parametrize("request_type", [ - regions.GetRegionRequest, - dict, -]) -def test_get_region(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regions.GetRegionRequest, + dict, + ], +) +def test_get_region(request_type, transport: str = "grpc"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,13 +1130,11 @@ def test_get_region(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", ) response = client.get_region(request) @@ -797,8 +1146,8 @@ def test_get_region(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" def test_get_region_non_empty_request_with_auto_populated_field(): @@ -806,28 +1155,29 @@ def test_get_region_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = RegionsServiceClient( 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 = regions.GetRegionRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.get_region), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_region(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regions.GetRegionRequest( - name='name_value', + name="name_value", ) + def test_get_region_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -846,7 +1196,9 @@ def test_get_region_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_region] = mock_rpc request = {} client.get_region(request) @@ -860,6 +1212,7 @@ def test_get_region_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio async def test_get_region_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -875,12 +1228,17 @@ async def test_get_region_async_use_cached_wrapped_rpc(transport: str = "grpc_as wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_region in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_region + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_region] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_region + ] = mock_rpc request = {} await client.get_region(request) @@ -894,8 +1252,11 @@ async def test_get_region_async_use_cached_wrapped_rpc(transport: str = "grpc_as assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_region_async(transport: str = 'grpc_asyncio', request_type=regions.GetRegionRequest): +async def test_get_region_async( + transport: str = "grpc_asyncio", request_type=regions.GetRegionRequest +): client = RegionsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -906,14 +1267,14 @@ async def test_get_region_async(transport: str = 'grpc_asyncio', request_type=re request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.Region( + name="name_value", + display_name="display_name_value", + ) + ) response = await client.get_region(request) # Establish that the underlying gRPC stub method was called. @@ -924,14 +1285,15 @@ async def test_get_region_async(transport: str = 'grpc_asyncio', request_type=re # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" @pytest.mark.asyncio async def test_get_region_async_from_dict(): await test_get_region_async(request_type=dict) + def test_get_region_field_headers(): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -941,12 +1303,10 @@ def test_get_region_field_headers(): # a field header. Set these to a non-empty value. request = regions.GetRegionRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: call.return_value = regions.Region() client.get_region(request) @@ -958,9 +1318,9 @@ def test_get_region_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 @@ -973,12 +1333,10 @@ async def test_get_region_field_headers_async(): # a field header. Set these to a non-empty value. request = regions.GetRegionRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) await client.get_region(request) @@ -990,9 +1348,9 @@ async def test_get_region_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_region_flattened(): @@ -1001,15 +1359,13 @@ def test_get_region_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_region( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1017,7 +1373,7 @@ def test_get_region_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 @@ -1031,9 +1387,10 @@ def test_get_region_flattened_error(): with pytest.raises(ValueError): client.get_region( regions.GetRegionRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_region_flattened_async(): client = RegionsServiceAsyncClient( @@ -1041,9 +1398,7 @@ async def test_get_region_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region() @@ -1051,7 +1406,7 @@ async def test_get_region_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_region( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1059,9 +1414,10 @@ async def test_get_region_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_region_flattened_error_async(): client = RegionsServiceAsyncClient( @@ -1073,15 +1429,18 @@ async def test_get_region_flattened_error_async(): with pytest.raises(ValueError): await client.get_region( regions.GetRegionRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - regions.CreateRegionRequest, - dict, -]) -def test_create_region(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regions.CreateRegionRequest, + dict, + ], +) +def test_create_region(request_type, transport: str = "grpc"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1092,13 +1451,11 @@ def test_create_region(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", ) response = client.create_region(request) @@ -1110,8 +1467,8 @@ def test_create_region(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" def test_create_region_non_empty_request_with_auto_populated_field(): @@ -1119,30 +1476,31 @@ def test_create_region_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = RegionsServiceClient( 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 = regions.CreateRegionRequest( - parent='parent_value', - region_id='region_id_value', + parent="parent_value", + region_id="region_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.create_region), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_region(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regions.CreateRegionRequest( - parent='parent_value', - region_id='region_id_value', + parent="parent_value", + region_id="region_id_value", ) + def test_create_region_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1161,7 +1519,9 @@ def test_create_region_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.create_region] = mock_rpc request = {} client.create_region(request) @@ -1175,8 +1535,11 @@ def test_create_region_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_region_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_region_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: @@ -1190,12 +1553,17 @@ async def test_create_region_async_use_cached_wrapped_rpc(transport: str = "grpc wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_region in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_region + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_region] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_region + ] = mock_rpc request = {} await client.create_region(request) @@ -1209,8 +1577,11 @@ async def test_create_region_async_use_cached_wrapped_rpc(transport: str = "grpc assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_region_async(transport: str = 'grpc_asyncio', request_type=regions.CreateRegionRequest): +async def test_create_region_async( + transport: str = "grpc_asyncio", request_type=regions.CreateRegionRequest +): client = RegionsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1221,14 +1592,14 @@ async def test_create_region_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.Region( + name="name_value", + display_name="display_name_value", + ) + ) response = await client.create_region(request) # Establish that the underlying gRPC stub method was called. @@ -1239,14 +1610,15 @@ async def test_create_region_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" @pytest.mark.asyncio async def test_create_region_async_from_dict(): await test_create_region_async(request_type=dict) + def test_create_region_field_headers(): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1256,12 +1628,10 @@ def test_create_region_field_headers(): # a field header. Set these to a non-empty value. request = regions.CreateRegionRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: call.return_value = regions.Region() client.create_region(request) @@ -1273,9 +1643,9 @@ def test_create_region_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 @@ -1288,12 +1658,10 @@ async def test_create_region_field_headers_async(): # a field header. Set these to a non-empty value. request = regions.CreateRegionRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) await client.create_region(request) @@ -1305,9 +1673,9 @@ async def test_create_region_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_region_flattened(): @@ -1316,17 +1684,15 @@ def test_create_region_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_region( - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', + parent="parent_value", + region=regions.Region(name="name_value"), + region_id="region_id_value", ) # Establish that the underlying call was made with the expected @@ -1334,13 +1700,13 @@ def test_create_region_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].region - mock_val = regions.Region(name='name_value') + mock_val = regions.Region(name="name_value") assert arg == mock_val arg = args[0].region_id - mock_val = 'region_id_value' + mock_val = "region_id_value" assert arg == mock_val @@ -1354,11 +1720,12 @@ def test_create_region_flattened_error(): with pytest.raises(ValueError): client.create_region( regions.CreateRegionRequest(), - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', + parent="parent_value", + region=regions.Region(name="name_value"), + region_id="region_id_value", ) + @pytest.mark.asyncio async def test_create_region_flattened_async(): client = RegionsServiceAsyncClient( @@ -1366,9 +1733,7 @@ async def test_create_region_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region() @@ -1376,9 +1741,9 @@ async def test_create_region_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_region( - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', + parent="parent_value", + region=regions.Region(name="name_value"), + region_id="region_id_value", ) # Establish that the underlying call was made with the expected @@ -1386,15 +1751,16 @@ async def test_create_region_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].region - mock_val = regions.Region(name='name_value') + mock_val = regions.Region(name="name_value") assert arg == mock_val arg = args[0].region_id - mock_val = 'region_id_value' + mock_val = "region_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_region_flattened_error_async(): client = RegionsServiceAsyncClient( @@ -1406,17 +1772,20 @@ async def test_create_region_flattened_error_async(): with pytest.raises(ValueError): await client.create_region( regions.CreateRegionRequest(), - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', + parent="parent_value", + region=regions.Region(name="name_value"), + region_id="region_id_value", ) -@pytest.mark.parametrize("request_type", [ - regions.UpdateRegionRequest, - dict, -]) -def test_update_region(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regions.UpdateRegionRequest, + dict, + ], +) +def test_update_region(request_type, transport: str = "grpc"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1427,13 +1796,11 @@ def test_update_region(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", ) response = client.update_region(request) @@ -1445,8 +1812,8 @@ def test_update_region(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" def test_update_region_non_empty_request_with_auto_populated_field(): @@ -1454,25 +1821,24 @@ def test_update_region_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = RegionsServiceClient( 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 = regions.UpdateRegionRequest( - ) + request = regions.UpdateRegionRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.update_region), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_region(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == regions.UpdateRegionRequest( - ) + assert args[0] == regions.UpdateRegionRequest() + def test_update_region_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1492,7 +1858,9 @@ def test_update_region_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_region] = mock_rpc request = {} client.update_region(request) @@ -1506,8 +1874,11 @@ def test_update_region_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_region_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_region_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: @@ -1521,12 +1892,17 @@ async def test_update_region_async_use_cached_wrapped_rpc(transport: str = "grpc wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_region in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_region + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_region] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_region + ] = mock_rpc request = {} await client.update_region(request) @@ -1540,8 +1916,11 @@ async def test_update_region_async_use_cached_wrapped_rpc(transport: str = "grpc assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_region_async(transport: str = 'grpc_asyncio', request_type=regions.UpdateRegionRequest): +async def test_update_region_async( + transport: str = "grpc_asyncio", request_type=regions.UpdateRegionRequest +): client = RegionsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1552,14 +1931,14 @@ async def test_update_region_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.Region( + name="name_value", + display_name="display_name_value", + ) + ) response = await client.update_region(request) # Establish that the underlying gRPC stub method was called. @@ -1570,14 +1949,15 @@ async def test_update_region_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" @pytest.mark.asyncio async def test_update_region_async_from_dict(): await test_update_region_async(request_type=dict) + def test_update_region_field_headers(): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1587,12 +1967,10 @@ def test_update_region_field_headers(): # a field header. Set these to a non-empty value. request = regions.UpdateRegionRequest() - request.region.name = 'name_value' + request.region.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: call.return_value = regions.Region() client.update_region(request) @@ -1604,9 +1982,9 @@ def test_update_region_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'region.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "region.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1619,12 +1997,10 @@ async def test_update_region_field_headers_async(): # a field header. Set these to a non-empty value. request = regions.UpdateRegionRequest() - request.region.name = 'name_value' + request.region.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region()) await client.update_region(request) @@ -1636,9 +2012,9 @@ async def test_update_region_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'region.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "region.name=name_value", + ) in kw["metadata"] def test_update_region_flattened(): @@ -1647,16 +2023,14 @@ def test_update_region_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_region( - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + region=regions.Region(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1664,10 +2038,10 @@ def test_update_region_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].region - mock_val = regions.Region(name='name_value') + mock_val = regions.Region(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1681,10 +2055,11 @@ def test_update_region_flattened_error(): with pytest.raises(ValueError): client.update_region( regions.UpdateRegionRequest(), - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + region=regions.Region(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_region_flattened_async(): client = RegionsServiceAsyncClient( @@ -1692,9 +2067,7 @@ async def test_update_region_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.Region() @@ -1702,8 +2075,8 @@ async def test_update_region_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_region( - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + region=regions.Region(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1711,12 +2084,13 @@ async def test_update_region_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].region - mock_val = regions.Region(name='name_value') + mock_val = regions.Region(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_region_flattened_error_async(): client = RegionsServiceAsyncClient( @@ -1728,16 +2102,19 @@ async def test_update_region_flattened_error_async(): with pytest.raises(ValueError): await client.update_region( regions.UpdateRegionRequest(), - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + region=regions.Region(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - regions.DeleteRegionRequest, - dict, -]) -def test_delete_region(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regions.DeleteRegionRequest, + dict, + ], +) +def test_delete_region(request_type, transport: str = "grpc"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1748,9 +2125,7 @@ def test_delete_region(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_region(request) @@ -1770,28 +2145,29 @@ def test_delete_region_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = RegionsServiceClient( 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 = regions.DeleteRegionRequest( - 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_region), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_region(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regions.DeleteRegionRequest( - name='name_value', + name="name_value", ) + def test_delete_region_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1810,7 +2186,9 @@ def test_delete_region_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.delete_region] = mock_rpc request = {} client.delete_region(request) @@ -1824,8 +2202,11 @@ def test_delete_region_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_region_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_region_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: @@ -1839,12 +2220,17 @@ async def test_delete_region_async_use_cached_wrapped_rpc(transport: str = "grpc wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_region in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_region + 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_region] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_region + ] = mock_rpc request = {} await client.delete_region(request) @@ -1858,8 +2244,11 @@ async def test_delete_region_async_use_cached_wrapped_rpc(transport: str = "grpc assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_region_async(transport: str = 'grpc_asyncio', request_type=regions.DeleteRegionRequest): +async def test_delete_region_async( + transport: str = "grpc_asyncio", request_type=regions.DeleteRegionRequest +): client = RegionsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1870,9 +2259,7 @@ async def test_delete_region_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_region(request) @@ -1891,6 +2278,7 @@ async def test_delete_region_async(transport: str = 'grpc_asyncio', request_type async def test_delete_region_async_from_dict(): await test_delete_region_async(request_type=dict) + def test_delete_region_field_headers(): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1900,12 +2288,10 @@ def test_delete_region_field_headers(): # a field header. Set these to a non-empty value. request = regions.DeleteRegionRequest() - 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_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: call.return_value = None client.delete_region(request) @@ -1917,9 +2303,9 @@ def test_delete_region_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 @@ -1932,12 +2318,10 @@ async def test_delete_region_field_headers_async(): # a field header. Set these to a non-empty value. request = regions.DeleteRegionRequest() - 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_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_region(request) @@ -1949,9 +2333,9 @@ async def test_delete_region_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_region_flattened(): @@ -1960,15 +2344,13 @@ def test_delete_region_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__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_region( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1976,7 +2358,7 @@ def test_delete_region_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 @@ -1990,9 +2372,10 @@ def test_delete_region_flattened_error(): with pytest.raises(ValueError): client.delete_region( regions.DeleteRegionRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_region_flattened_async(): client = RegionsServiceAsyncClient( @@ -2000,9 +2383,7 @@ async def test_delete_region_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -2010,7 +2391,7 @@ async def test_delete_region_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_region( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2018,9 +2399,10 @@ async def test_delete_region_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_region_flattened_error_async(): client = RegionsServiceAsyncClient( @@ -2032,15 +2414,18 @@ async def test_delete_region_flattened_error_async(): with pytest.raises(ValueError): await client.delete_region( regions.DeleteRegionRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - regions.ListRegionsRequest, - dict, -]) -def test_list_regions(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + regions.ListRegionsRequest, + dict, + ], +) +def test_list_regions(request_type, transport: str = "grpc"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2051,12 +2436,10 @@ def test_list_regions(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.ListRegionsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_regions(request) @@ -2068,7 +2451,7 @@ def test_list_regions(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRegionsPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_regions_non_empty_request_with_auto_populated_field(): @@ -2076,30 +2459,31 @@ def test_list_regions_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = RegionsServiceClient( 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 = regions.ListRegionsRequest( - 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_regions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_regions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == regions.ListRegionsRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_regions_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2118,7 +2502,9 @@ def test_list_regions_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_regions] = mock_rpc request = {} client.list_regions(request) @@ -2132,8 +2518,11 @@ def test_list_regions_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_regions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_list_regions_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: @@ -2147,12 +2536,17 @@ async def test_list_regions_async_use_cached_wrapped_rpc(transport: str = "grpc_ wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_regions in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_regions + 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_regions] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_regions + ] = mock_rpc request = {} await client.list_regions(request) @@ -2166,8 +2560,11 @@ async def test_list_regions_async_use_cached_wrapped_rpc(transport: str = "grpc_ assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_regions_async(transport: str = 'grpc_asyncio', request_type=regions.ListRegionsRequest): +async def test_list_regions_async( + transport: str = "grpc_asyncio", request_type=regions.ListRegionsRequest +): client = RegionsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2178,13 +2575,13 @@ async def test_list_regions_async(transport: str = 'grpc_asyncio', request_type= request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.ListRegionsResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_regions(request) # Establish that the underlying gRPC stub method was called. @@ -2195,13 +2592,14 @@ async def test_list_regions_async(transport: str = 'grpc_asyncio', request_type= # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRegionsAsyncPager) - 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_regions_async_from_dict(): await test_list_regions_async(request_type=dict) + def test_list_regions_field_headers(): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2211,12 +2609,10 @@ def test_list_regions_field_headers(): # a field header. Set these to a non-empty value. request = regions.ListRegionsRequest() - 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_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: call.return_value = regions.ListRegionsResponse() client.list_regions(request) @@ -2228,9 +2624,9 @@ def test_list_regions_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 @@ -2243,13 +2639,13 @@ async def test_list_regions_field_headers_async(): # a field header. Set these to a non-empty value. request = regions.ListRegionsRequest() - 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_regions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.ListRegionsResponse() + ) await client.list_regions(request) # Establish that the underlying gRPC stub method was called. @@ -2260,9 +2656,9 @@ async def test_list_regions_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_regions_flattened(): @@ -2271,15 +2667,13 @@ def test_list_regions_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.ListRegionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_regions( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -2287,7 +2681,7 @@ def test_list_regions_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 @@ -2301,9 +2695,10 @@ def test_list_regions_flattened_error(): with pytest.raises(ValueError): client.list_regions( regions.ListRegionsRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_regions_flattened_async(): client = RegionsServiceAsyncClient( @@ -2311,17 +2706,17 @@ async def test_list_regions_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = regions.ListRegionsResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.ListRegionsResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_regions( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -2329,9 +2724,10 @@ async def test_list_regions_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_regions_flattened_error_async(): client = RegionsServiceAsyncClient( @@ -2343,7 +2739,7 @@ async def test_list_regions_flattened_error_async(): with pytest.raises(ValueError): await client.list_regions( regions.ListRegionsRequest(), - parent='parent_value', + parent="parent_value", ) @@ -2354,9 +2750,7 @@ def test_list_regions_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_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( regions.ListRegionsResponse( @@ -2365,17 +2759,17 @@ def test_list_regions_pager(transport_name: str = "grpc"): regions.Region(), regions.Region(), ], - next_page_token='abc', + next_page_token="abc", ), regions.ListRegionsResponse( regions=[], - next_page_token='def', + next_page_token="def", ), regions.ListRegionsResponse( regions=[ regions.Region(), ], - next_page_token='ghi', + next_page_token="ghi", ), regions.ListRegionsResponse( regions=[ @@ -2390,9 +2784,7 @@ def test_list_regions_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_regions(request={}, retry=retry, timeout=timeout) @@ -2402,8 +2794,9 @@ def test_list_regions_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, regions.Region) - for i in results) + assert all(isinstance(i, regions.Region) for i in results) + + def test_list_regions_pages(transport_name: str = "grpc"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2411,9 +2804,7 @@ def test_list_regions_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_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( regions.ListRegionsResponse( @@ -2422,17 +2813,17 @@ def test_list_regions_pages(transport_name: str = "grpc"): regions.Region(), regions.Region(), ], - next_page_token='abc', + next_page_token="abc", ), regions.ListRegionsResponse( regions=[], - next_page_token='def', + next_page_token="def", ), regions.ListRegionsResponse( regions=[ regions.Region(), ], - next_page_token='ghi', + next_page_token="ghi", ), regions.ListRegionsResponse( regions=[ @@ -2443,9 +2834,10 @@ def test_list_regions_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_regions(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_regions_async_pager(): client = RegionsServiceAsyncClient( @@ -2454,8 +2846,8 @@ async def test_list_regions_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_regions), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_regions), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( regions.ListRegionsResponse( @@ -2464,17 +2856,17 @@ async def test_list_regions_async_pager(): regions.Region(), regions.Region(), ], - next_page_token='abc', + next_page_token="abc", ), regions.ListRegionsResponse( regions=[], - next_page_token='def', + next_page_token="def", ), regions.ListRegionsResponse( regions=[ regions.Region(), ], - next_page_token='ghi', + next_page_token="ghi", ), regions.ListRegionsResponse( regions=[ @@ -2484,15 +2876,16 @@ async def test_list_regions_async_pager(): ), RuntimeError, ) - async_pager = await client.list_regions(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_regions( + 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, regions.Region) - for i in responses) + assert all(isinstance(i, regions.Region) for i in responses) @pytest.mark.asyncio @@ -2503,8 +2896,8 @@ async def test_list_regions_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_regions), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_regions), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( regions.ListRegionsResponse( @@ -2513,17 +2906,17 @@ async def test_list_regions_async_pages(): regions.Region(), regions.Region(), ], - next_page_token='abc', + next_page_token="abc", ), regions.ListRegionsResponse( regions=[], - next_page_token='def', + next_page_token="def", ), regions.ListRegionsResponse( regions=[ regions.Region(), ], - next_page_token='ghi', + next_page_token="ghi", ), regions.ListRegionsResponse( regions=[ @@ -2536,11 +2929,11 @@ async def test_list_regions_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_regions(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 @@ -2562,7 +2955,9 @@ def test_get_region_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_region] = mock_rpc request = {} @@ -2585,48 +2980,51 @@ def test_get_region_rest_required_fields(request_type=regions.GetRegionRequest): request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_region._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_region._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 = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = regions.Region() # Mock the http request 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 @@ -2637,24 +3035,24 @@ def test_get_region_rest_required_fields(request_type=regions.GetRegionRequest): return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_region(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_region_rest_flattened(): @@ -2664,16 +3062,16 @@ def test_get_region_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 = regions.Region() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/regions/sample2'} + sample_request = {"name": "accounts/sample1/regions/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2683,7 +3081,7 @@ def test_get_region_rest_flattened(): # Convert return value to protobuf type return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2693,10 +3091,13 @@ def test_get_region_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/regions/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/regions/*}" % client.transport._host, + args[1], + ) -def test_get_region_rest_flattened_error(transport: str = 'rest'): +def test_get_region_rest_flattened_error(transport: str = "rest"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2707,7 +3108,7 @@ def test_get_region_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_region( regions.GetRegionRequest(), - name='name_value', + name="name_value", ) @@ -2729,7 +3130,9 @@ def test_create_region_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.create_region] = mock_rpc request = {} @@ -2753,58 +3156,61 @@ def test_create_region_rest_required_fields(request_type=regions.CreateRegionReq request_init["region_id"] = "" 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 assert "regionId" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_region._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "regionId" in jsonified_request assert jsonified_request["regionId"] == request_init["region_id"] - jsonified_request["parent"] = 'parent_value' - jsonified_request["regionId"] = 'region_id_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["regionId"] = "region_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_region._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("region_id", )) + assert not set(unset_fields) - set(("region_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" assert "regionId" in jsonified_request - assert jsonified_request["regionId"] == 'region_id_value' + assert jsonified_request["regionId"] == "region_id_value" client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = regions.Region() # Mock the http request 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() @@ -2814,7 +3220,7 @@ def test_create_region_rest_required_fields(request_type=regions.CreateRegionReq return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2825,17 +3231,28 @@ def test_create_region_rest_required_fields(request_type=regions.CreateRegionReq "regionId", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(("regionId", )) & set(("parent", "regionId", "region", ))) + assert set(unset_fields) == ( + set(("regionId",)) + & set( + ( + "parent", + "regionId", + "region", + ) + ) + ) def test_create_region_rest_flattened(): @@ -2845,18 +3262,18 @@ def test_create_region_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 = regions.Region() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', + parent="parent_value", + region=regions.Region(name="name_value"), + region_id="region_id_value", ) mock_args.update(sample_request) @@ -2866,7 +3283,7 @@ def test_create_region_rest_flattened(): # Convert return value to protobuf type return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2876,10 +3293,13 @@ def test_create_region_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/regions" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/regions" % client.transport._host, + args[1], + ) -def test_create_region_rest_flattened_error(transport: str = 'rest'): +def test_create_region_rest_flattened_error(transport: str = "rest"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2890,9 +3310,9 @@ def test_create_region_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_region( regions.CreateRegionRequest(), - parent='parent_value', - region=regions.Region(name='name_value'), - region_id='region_id_value', + parent="parent_value", + region=regions.Region(name="name_value"), + region_id="region_id_value", ) @@ -2914,7 +3334,9 @@ def test_update_region_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_region] = mock_rpc request = {} @@ -2936,48 +3358,51 @@ def test_update_region_rest_required_fields(request_type=regions.UpdateRegionReq request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_region._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_region._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = regions.Region() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -2987,24 +3412,24 @@ def test_update_region_rest_required_fields(request_type=regions.UpdateRegionReq return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_region(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("region", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("region",))) def test_update_region_rest_flattened(): @@ -3014,17 +3439,17 @@ def test_update_region_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 = regions.Region() # get arguments that satisfy an http rule for this method - sample_request = {'region': {'name': 'accounts/sample1/regions/sample2'}} + sample_request = {"region": {"name": "accounts/sample1/regions/sample2"}} # get truthy value for each flattened field mock_args = dict( - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + region=regions.Region(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -3034,7 +3459,7 @@ def test_update_region_rest_flattened(): # Convert return value to protobuf type return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3044,10 +3469,14 @@ def test_update_region_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{region.name=accounts/*/regions/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{region.name=accounts/*/regions/*}" + % client.transport._host, + args[1], + ) -def test_update_region_rest_flattened_error(transport: str = 'rest'): +def test_update_region_rest_flattened_error(transport: str = "rest"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3058,8 +3487,8 @@ def test_update_region_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_region( regions.UpdateRegionRequest(), - region=regions.Region(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + region=regions.Region(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -3081,7 +3510,9 @@ def test_delete_region_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.delete_region] = mock_rpc request = {} @@ -3104,73 +3535,76 @@ def test_delete_region_rest_required_fields(request_type=regions.DeleteRegionReq 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_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_region._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_region._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_region._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 = RegionsServiceClient( 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_region(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_region_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_region._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_delete_region_rest_flattened(): @@ -3180,24 +3614,24 @@ def test_delete_region_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/regions/sample2'} + sample_request = {"name": "accounts/sample1/regions/sample2"} # 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"} @@ -3207,10 +3641,13 @@ def test_delete_region_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/regions/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/regions/*}" % client.transport._host, + args[1], + ) -def test_delete_region_rest_flattened_error(transport: str = 'rest'): +def test_delete_region_rest_flattened_error(transport: str = "rest"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3221,7 +3658,7 @@ def test_delete_region_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_region( regions.DeleteRegionRequest(), - name='name_value', + name="name_value", ) @@ -3243,7 +3680,9 @@ def test_list_regions_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_regions] = mock_rpc request = {} @@ -3266,50 +3705,58 @@ def test_list_regions_rest_required_fields(request_type=regions.ListRegionsReque 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_regions._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_regions._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_regions._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_regions._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 = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = regions.ListRegionsResponse() # Mock the http request 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 @@ -3320,24 +3767,32 @@ def test_list_regions_rest_required_fields(request_type=regions.ListRegionsReque return_value = regions.ListRegionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_regions(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_regions_rest_unset_required_fields(): - transport = transports.RegionsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.RegionsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_regions._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_regions_rest_flattened(): @@ -3347,16 +3802,16 @@ def test_list_regions_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 = regions.ListRegionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -3366,7 +3821,7 @@ def test_list_regions_rest_flattened(): # Convert return value to protobuf type return_value = regions.ListRegionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3376,10 +3831,13 @@ def test_list_regions_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/regions" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/regions" % client.transport._host, + args[1], + ) -def test_list_regions_rest_flattened_error(transport: str = 'rest'): +def test_list_regions_rest_flattened_error(transport: str = "rest"): client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3390,20 +3848,20 @@ def test_list_regions_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_regions( regions.ListRegionsRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_regions_rest_pager(transport: str = 'rest'): +def test_list_regions_rest_pager(transport: str = "rest"): client = RegionsServiceClient( 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 = ( regions.ListRegionsResponse( @@ -3412,17 +3870,17 @@ def test_list_regions_rest_pager(transport: str = 'rest'): regions.Region(), regions.Region(), ], - next_page_token='abc', + next_page_token="abc", ), regions.ListRegionsResponse( regions=[], - next_page_token='def', + next_page_token="def", ), regions.ListRegionsResponse( regions=[ regions.Region(), ], - next_page_token='ghi', + next_page_token="ghi", ), regions.ListRegionsResponse( regions=[ @@ -3438,21 +3896,20 @@ def test_list_regions_rest_pager(transport: str = 'rest'): response = tuple(regions.ListRegionsResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_regions(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, regions.Region) - for i in results) + assert all(isinstance(i, regions.Region) for i in results) pages = list(client.list_regions(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 @@ -3494,8 +3951,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = RegionsServiceClient( - 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. @@ -3517,6 +3973,7 @@ def test_transport_instance(): client = RegionsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.RegionsServiceGrpcTransport( @@ -3531,18 +3988,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.RegionsServiceGrpcTransport, - transports.RegionsServiceGrpcAsyncIOTransport, - transports.RegionsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + transports.RegionsServiceRestTransport, + ], +) 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 = RegionsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3552,8 +4014,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3567,9 +4028,7 @@ def test_get_region_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: call.return_value = regions.Region() client.get_region(request=None) @@ -3590,9 +4049,7 @@ def test_create_region_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: call.return_value = regions.Region() client.create_region(request=None) @@ -3613,9 +4070,7 @@ def test_update_region_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: call.return_value = regions.Region() client.update_region(request=None) @@ -3636,9 +4091,7 @@ def test_delete_region_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: call.return_value = None client.delete_region(request=None) @@ -3659,9 +4112,7 @@ def test_list_regions_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: call.return_value = regions.ListRegionsResponse() client.list_regions(request=None) @@ -3682,8 +4133,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = RegionsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3698,14 +4148,14 @@ async def test_get_region_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.Region( + name="name_value", + display_name="display_name_value", + ) + ) await client.get_region(request=None) # Establish that the underlying stub method was called. @@ -3726,14 +4176,14 @@ async def test_create_region_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.Region( + name="name_value", + display_name="display_name_value", + ) + ) await client.create_region(request=None) # Establish that the underlying stub method was called. @@ -3754,14 +4204,14 @@ async def test_update_region_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.Region( - name='name_value', - display_name='display_name_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.Region( + name="name_value", + display_name="display_name_value", + ) + ) await client.update_region(request=None) # Establish that the underlying stub method was called. @@ -3782,9 +4232,7 @@ async def test_delete_region_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_region(request=None) @@ -3807,13 +4255,13 @@ async def test_list_regions_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(regions.ListRegionsResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + regions.ListRegionsResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_regions(request=None) # Establish that the underlying stub method was called. @@ -3833,18 +4281,19 @@ def test_transport_kind_rest(): def test_get_region_rest_bad_request(request_type=regions.GetRegionRequest): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/sample2'} + request_init = {"name": "accounts/sample1/regions/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() @@ -3853,26 +4302,28 @@ def test_get_region_rest_bad_request(request_type=regions.GetRegionRequest): client.get_region(request) -@pytest.mark.parametrize("request_type", [ - regions.GetRegionRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regions.GetRegionRequest, + dict, + ], +) def test_get_region_rest_call_success(request_type): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/sample2'} + request_init = {"name": "accounts/sample1/regions/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 = regions.Region( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", ) # Wrap the value into a proper Response obj @@ -3882,30 +4333,38 @@ def test_get_region_rest_call_success(request_type): # Convert return value to protobuf type return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_region(request) # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_region_rest_interceptors(null_interceptor): transport = transports.RegionsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionsServiceRestInterceptor(), + ) client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_get_region") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_get_region_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_get_region") 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.RegionsServiceRestInterceptor, "post_get_region" + ) as post, mock.patch.object( + transports.RegionsServiceRestInterceptor, "post_get_region_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionsServiceRestInterceptor, "pre_get_region" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3924,7 +4383,7 @@ def test_get_region_rest_interceptors(null_interceptor): req.return_value.content = return_value request = regions.GetRegionRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3932,7 +4391,13 @@ def test_get_region_rest_interceptors(null_interceptor): post.return_value = regions.Region() post_with_metadata.return_value = regions.Region(), metadata - client.get_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_region( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3941,18 +4406,19 @@ def test_get_region_rest_interceptors(null_interceptor): def test_create_region_rest_bad_request(request_type=regions.CreateRegionRequest): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3961,19 +4427,31 @@ def test_create_region_rest_bad_request(request_type=regions.CreateRegionRequest client.create_region(request) -@pytest.mark.parametrize("request_type", [ - regions.CreateRegionRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regions.CreateRegionRequest, + dict, + ], +) def test_create_region_rest_call_success(request_type): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["region"] = {'name': 'name_value', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} + request_init = {"parent": "accounts/sample1"} + request_init["region"] = { + "name": "name_value", + "display_name": "display_name_value", + "postal_code_area": { + "region_code": "region_code_value", + "postal_codes": [{"begin": "begin_value", "end": "end_value"}], + }, + "geotarget_area": {"geotarget_criteria_ids": [2324, 2325]}, + "regional_inventory_eligible": {"value": True}, + "shipping_eligible": {}, + } # 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 @@ -3993,7 +4471,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 @@ -4007,7 +4485,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["region"].items(): # pragma: NO COVER + for field, value in request_init["region"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4022,12 +4500,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") @@ -4040,11 +4522,11 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = regions.Region( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", ) # Wrap the value into a proper Response obj @@ -4054,30 +4536,38 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_region(request) # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_region_rest_interceptors(null_interceptor): transport = transports.RegionsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionsServiceRestInterceptor(), + ) client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_create_region") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_create_region_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_create_region") 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.RegionsServiceRestInterceptor, "post_create_region" + ) as post, mock.patch.object( + transports.RegionsServiceRestInterceptor, "post_create_region_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionsServiceRestInterceptor, "pre_create_region" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4096,7 +4586,7 @@ def test_create_region_rest_interceptors(null_interceptor): req.return_value.content = return_value request = regions.CreateRegionRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4104,7 +4594,13 @@ def test_create_region_rest_interceptors(null_interceptor): post.return_value = regions.Region() post_with_metadata.return_value = regions.Region(), metadata - client.create_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_region( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -4113,18 +4609,19 @@ def test_create_region_rest_interceptors(null_interceptor): def test_update_region_rest_bad_request(request_type=regions.UpdateRegionRequest): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'region': {'name': 'accounts/sample1/regions/sample2'}} + request_init = {"region": {"name": "accounts/sample1/regions/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() @@ -4133,19 +4630,31 @@ def test_update_region_rest_bad_request(request_type=regions.UpdateRegionRequest client.update_region(request) -@pytest.mark.parametrize("request_type", [ - regions.UpdateRegionRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regions.UpdateRegionRequest, + dict, + ], +) def test_update_region_rest_call_success(request_type): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'region': {'name': 'accounts/sample1/regions/sample2'}} - request_init["region"] = {'name': 'accounts/sample1/regions/sample2', 'display_name': 'display_name_value', 'postal_code_area': {'region_code': 'region_code_value', 'postal_codes': [{'begin': 'begin_value', 'end': 'end_value'}]}, 'geotarget_area': {'geotarget_criteria_ids': [2324, 2325]}, 'regional_inventory_eligible': {'value': True}, 'shipping_eligible': {}} + request_init = {"region": {"name": "accounts/sample1/regions/sample2"}} + request_init["region"] = { + "name": "accounts/sample1/regions/sample2", + "display_name": "display_name_value", + "postal_code_area": { + "region_code": "region_code_value", + "postal_codes": [{"begin": "begin_value", "end": "end_value"}], + }, + "geotarget_area": {"geotarget_criteria_ids": [2324, 2325]}, + "regional_inventory_eligible": {"value": True}, + "shipping_eligible": {}, + } # 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 @@ -4165,7 +4674,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 @@ -4179,7 +4688,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["region"].items(): # pragma: NO COVER + for field, value in request_init["region"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4194,12 +4703,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") @@ -4212,11 +4725,11 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = regions.Region( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", ) # Wrap the value into a proper Response obj @@ -4226,30 +4739,38 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = regions.Region.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_region(request) # Establish that the response is the type that we expect. assert isinstance(response, regions.Region) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_region_rest_interceptors(null_interceptor): transport = transports.RegionsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionsServiceRestInterceptor(), + ) client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_update_region") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_update_region_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_update_region") 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.RegionsServiceRestInterceptor, "post_update_region" + ) as post, mock.patch.object( + transports.RegionsServiceRestInterceptor, "post_update_region_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionsServiceRestInterceptor, "pre_update_region" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4268,7 +4789,7 @@ def test_update_region_rest_interceptors(null_interceptor): req.return_value.content = return_value request = regions.UpdateRegionRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4276,7 +4797,13 @@ def test_update_region_rest_interceptors(null_interceptor): post.return_value = regions.Region() post_with_metadata.return_value = regions.Region(), metadata - client.update_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_region( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -4285,18 +4812,19 @@ def test_update_region_rest_interceptors(null_interceptor): def test_delete_region_rest_bad_request(request_type=regions.DeleteRegionRequest): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/sample2'} + request_init = {"name": "accounts/sample1/regions/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() @@ -4305,30 +4833,32 @@ def test_delete_region_rest_bad_request(request_type=regions.DeleteRegionRequest client.delete_region(request) -@pytest.mark.parametrize("request_type", [ - regions.DeleteRegionRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regions.DeleteRegionRequest, + dict, + ], +) def test_delete_region_rest_call_success(request_type): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/regions/sample2'} + request_init = {"name": "accounts/sample1/regions/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 = 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_region(request) @@ -4341,13 +4871,19 @@ def test_delete_region_rest_call_success(request_type): def test_delete_region_rest_interceptors(null_interceptor): transport = transports.RegionsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionsServiceRestInterceptor(), + ) client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "pre_delete_region") 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.RegionsServiceRestInterceptor, "pre_delete_region" + ) as pre: pre.assert_not_called() pb_message = regions.DeleteRegionRequest.pb(regions.DeleteRegionRequest()) transcode.return_value = { @@ -4362,31 +4898,38 @@ def test_delete_region_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = regions.DeleteRegionRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_region(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_region( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() def test_list_regions_rest_bad_request(request_type=regions.ListRegionsRequest): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -4395,25 +4938,27 @@ def test_list_regions_rest_bad_request(request_type=regions.ListRegionsRequest): client.list_regions(request) -@pytest.mark.parametrize("request_type", [ - regions.ListRegionsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + regions.ListRegionsRequest, + dict, + ], +) def test_list_regions_rest_call_success(request_type): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = regions.ListRegionsResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -4423,29 +4968,37 @@ def test_list_regions_rest_call_success(request_type): # Convert return value to protobuf type return_value = regions.ListRegionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_regions(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListRegionsPager) - 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_regions_rest_interceptors(null_interceptor): transport = transports.RegionsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegionsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.RegionsServiceRestInterceptor(), + ) client = RegionsServiceClient(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.RegionsServiceRestInterceptor, "post_list_regions") as post, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "post_list_regions_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.RegionsServiceRestInterceptor, "pre_list_regions") 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.RegionsServiceRestInterceptor, "post_list_regions" + ) as post, mock.patch.object( + transports.RegionsServiceRestInterceptor, "post_list_regions_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionsServiceRestInterceptor, "pre_list_regions" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4460,11 +5013,13 @@ def test_list_regions_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 = regions.ListRegionsResponse.to_json(regions.ListRegionsResponse()) + return_value = regions.ListRegionsResponse.to_json( + regions.ListRegionsResponse() + ) req.return_value.content = return_value request = regions.ListRegionsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4472,16 +5027,22 @@ def test_list_regions_rest_interceptors(null_interceptor): post.return_value = regions.ListRegionsResponse() post_with_metadata.return_value = regions.ListRegionsResponse(), metadata - client.list_regions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_regions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = RegionsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -4495,9 +5056,7 @@ def test_get_region_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_region), - '__call__') as call: + with mock.patch.object(type(client.transport.get_region), "__call__") as call: client.get_region(request=None) # Establish that the underlying stub method was called. @@ -4517,9 +5076,7 @@ def test_create_region_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_region), - '__call__') as call: + with mock.patch.object(type(client.transport.create_region), "__call__") as call: client.create_region(request=None) # Establish that the underlying stub method was called. @@ -4539,9 +5096,7 @@ def test_update_region_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_region), - '__call__') as call: + with mock.patch.object(type(client.transport.update_region), "__call__") as call: client.update_region(request=None) # Establish that the underlying stub method was called. @@ -4561,9 +5116,7 @@ def test_delete_region_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_region), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_region), "__call__") as call: client.delete_region(request=None) # Establish that the underlying stub method was called. @@ -4583,9 +5136,7 @@ def test_list_regions_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_regions), - '__call__') as call: + with mock.patch.object(type(client.transport.list_regions), "__call__") as call: client.list_regions(request=None) # Establish that the underlying stub method was called. @@ -4606,18 +5157,21 @@ def test_transport_grpc_default(): transports.RegionsServiceGrpcTransport, ) + def test_regions_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.RegionsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_regions_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.RegionsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4626,11 +5180,11 @@ def test_regions_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_region', - 'create_region', - 'update_region', - 'delete_region', - 'list_regions', + "get_region", + "create_region", + "update_region", + "delete_region", + "list_regions", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4641,7 +5195,7 @@ def test_regions_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4650,25 +5204,30 @@ def test_regions_service_base_transport(): def test_regions_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_accounts_v1.services.regions_service.transports.RegionsServiceTransport._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_accounts_v1.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionsServiceTransport( 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_regions_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_accounts_v1.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.regions_service.transports.RegionsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.RegionsServiceTransport() @@ -4677,14 +5236,12 @@ def test_regions_service_base_transport_with_adc(): def test_regions_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) RegionsServiceClient() 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, ) @@ -4699,12 +5256,12 @@ def test_regions_service_auth_adc(): def test_regions_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", ) @@ -4718,48 +5275,45 @@ def test_regions_service_transport_auth_adc(transport_class): ], ) def test_regions_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.RegionsServiceGrpcTransport, grpc_helpers), - (transports.RegionsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.RegionsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_regions_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, @@ -4770,10 +5324,14 @@ def test_regions_service_transport_create_channel(transport_class, grpc_helpers) ) -@pytest.mark.parametrize("transport_class", [transports.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) -def test_regions_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + ], +) +def test_regions_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4782,7 +5340,7 @@ def test_regions_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", @@ -4803,61 +5361,77 @@ def test_regions_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_regions_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.RegionsServiceRestTransport ( - 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.RegionsServiceRestTransport( + 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_regions_service_host_no_port(transport_name): client = RegionsServiceClient( 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_regions_service_host_with_port(transport_name): client = RegionsServiceClient( 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_regions_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4884,8 +5458,10 @@ def test_regions_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_regions._session session2 = client2.transport.list_regions._session assert session1 != session2 + + def test_regions_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.RegionsServiceGrpcTransport( @@ -4898,7 +5474,7 @@ def test_regions_service_grpc_transport_channel(): def test_regions_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.RegionsServiceGrpcAsyncIOTransport( @@ -4912,12 +5488,22 @@ def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + ], +) def test_regions_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 @@ -4926,7 +5512,7 @@ def test_regions_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", @@ -4956,17 +5542,23 @@ def test_regions_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.RegionsServiceGrpcTransport, transports.RegionsServiceGrpcAsyncIOTransport]) -def test_regions_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionsServiceGrpcTransport, + transports.RegionsServiceGrpcAsyncIOTransport, + ], +) +def test_regions_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() @@ -4996,7 +5588,9 @@ def test_regions_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = RegionsServiceClient.account_path(account) assert expected == actual @@ -5011,10 +5605,14 @@ def test_parse_account_path(): actual = RegionsServiceClient.parse_account_path(path) assert expected == actual + def test_region_path(): account = "whelk" region = "octopus" - expected = "accounts/{account}/regions/{region}".format(account=account, region=region, ) + expected = "accounts/{account}/regions/{region}".format( + account=account, + region=region, + ) actual = RegionsServiceClient.region_path(account, region) assert expected == actual @@ -5030,9 +5628,12 @@ def test_parse_region_path(): actual = RegionsServiceClient.parse_region_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 = RegionsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -5047,9 +5648,12 @@ def test_parse_common_billing_account_path(): actual = RegionsServiceClient.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 = RegionsServiceClient.common_folder_path(folder) assert expected == actual @@ -5064,9 +5668,12 @@ def test_parse_common_folder_path(): actual = RegionsServiceClient.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 = RegionsServiceClient.common_organization_path(organization) assert expected == actual @@ -5081,9 +5688,12 @@ def test_parse_common_organization_path(): actual = RegionsServiceClient.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 = RegionsServiceClient.common_project_path(project) assert expected == actual @@ -5098,10 +5708,14 @@ def test_parse_common_project_path(): actual = RegionsServiceClient.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 = RegionsServiceClient.common_location_path(project, location) assert expected == actual @@ -5121,14 +5735,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.RegionsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.RegionsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = RegionsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.RegionsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.RegionsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = RegionsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5139,10 +5757,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = RegionsServiceClient( - 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() @@ -5151,10 +5770,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = RegionsServiceAsyncClient( - 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() @@ -5162,10 +5782,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = RegionsServiceClient( - 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() @@ -5173,13 +5794,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = RegionsServiceClient( - 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: @@ -5188,10 +5808,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (RegionsServiceClient, transports.RegionsServiceGrpcTransport), - (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (RegionsServiceClient, transports.RegionsServiceGrpcTransport), + (RegionsServiceAsyncClient, transports.RegionsServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5206,7 +5830,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py similarity index 63% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py index 5918e0d8b4e3..322841f09a37 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_shipping_settings_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,45 +22,43 @@ 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.shopping.merchant_accounts_v1.services.shipping_settings_service import ShippingSettingsServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.shipping_settings_service import ShippingSettingsServiceClient -from google.shopping.merchant_accounts_v1.services.shipping_settings_service import transports -from google.shopping.merchant_accounts_v1.types import shippingsettings from google.shopping.type.types import types -import google.auth - +from google.shopping.merchant_accounts_v1.services.shipping_settings_service import ( + ShippingSettingsServiceAsyncClient, + ShippingSettingsServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import shippingsettings CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +73,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +85,27 @@ def async_anonymous_credentials(): return ga_credentials_async.AnonymousCredentials() return ga_credentials.AnonymousCredentials() + # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + # If default endpoint template is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint template so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) def test__get_default_mtls_endpoint(): @@ -105,101 +116,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert ShippingSettingsServiceClient._get_default_mtls_endpoint(None) is None - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ShippingSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + ShippingSettingsServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ShippingSettingsServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ShippingSettingsServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ShippingSettingsServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert ShippingSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (True, "auto", None) + assert ShippingSettingsServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert ShippingSettingsServiceClient._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: ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._read_environment_variables() == (False, "never", None) + assert ShippingSettingsServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "always", None) + assert ShippingSettingsServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", None) + assert ShippingSettingsServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, False) is None - assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + ShippingSettingsServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + ShippingSettingsServiceClient._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 ( + ShippingSettingsServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ShippingSettingsServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +@mock.patch.object( + ShippingSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceClient), +) +@mock.patch.object( + ShippingSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert ShippingSettingsServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ShippingSettingsServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ShippingSettingsServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ShippingSettingsServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + ShippingSettingsServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - ShippingSettingsServiceClient._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." + ShippingSettingsServiceClient._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 ShippingSettingsServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ShippingSettingsServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ShippingSettingsServiceClient._get_universe_domain(None, None) == ShippingSettingsServiceClient._DEFAULT_UNIVERSE + assert ( + ShippingSettingsServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ShippingSettingsServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ShippingSettingsServiceClient._get_universe_domain(None, None) + == ShippingSettingsServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: ShippingSettingsServiceClient._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) @@ -215,7 +370,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") @@ -228,14 +384,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", [ - (ShippingSettingsServiceClient, "grpc"), - (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), - (ShippingSettingsServiceClient, "rest"), -]) -def test_shipping_settings_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ShippingSettingsServiceClient, "grpc"), + (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), + (ShippingSettingsServiceClient, "rest"), + ], +) +def test_shipping_settings_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) @@ -243,52 +407,70 @@ def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, "grpc"), - (transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ShippingSettingsServiceRestTransport, "rest"), -]) -def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, "grpc"), + (transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ShippingSettingsServiceRestTransport, "rest"), + ], +) +def test_shipping_settings_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", [ - (ShippingSettingsServiceClient, "grpc"), - (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), - (ShippingSettingsServiceClient, "rest"), -]) -def test_shipping_settings_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ShippingSettingsServiceClient, "grpc"), + (ShippingSettingsServiceAsyncClient, "grpc_asyncio"), + (ShippingSettingsServiceClient, "rest"), + ], +) +def test_shipping_settings_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" ) @@ -304,30 +486,53 @@ def test_shipping_settings_service_client_get_transport_class(): assert transport == transports.ShippingSettingsServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), -]) -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) -def test_shipping_settings_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + "grpc", + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + ShippingSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceClient), +) +@mock.patch.object( + ShippingSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceAsyncClient), +) +def test_shipping_settings_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(ShippingSettingsServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(ShippingSettingsServiceClient, "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(ShippingSettingsServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(ShippingSettingsServiceClient, "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( @@ -345,13 +550,15 @@ def test_shipping_settings_service_client_client_options(client_class, transport # 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, @@ -363,7 +570,7 @@ def test_shipping_settings_service_client_client_options(client_class, transport # 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( @@ -383,23 +590,33 @@ def test_shipping_settings_service_client_client_options(client_class, transport 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", @@ -408,48 +625,102 @@ def test_shipping_settings_service_client_client_options(client_class, transport 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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "true"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", "false"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "true"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + "grpc", + "true", + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + "grpc", + "false", + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceRestTransport, + "rest", + "true", + ), + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + ShippingSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceClient), +) +@mock.patch.object( + ShippingSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_shipping_settings_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_shipping_settings_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 @@ -468,12 +739,22 @@ def test_shipping_settings_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 @@ -494,15 +775,22 @@ def test_shipping_settings_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, @@ -512,19 +800,33 @@ def test_shipping_settings_service_client_mtls_env_auto(client_class, transport_ ) -@pytest.mark.parametrize("client_class", [ - ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient -]) -@mock.patch.object(ShippingSettingsServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ShippingSettingsServiceAsyncClient)) -def test_shipping_settings_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient] +) +@mock.patch.object( + ShippingSettingsServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ShippingSettingsServiceClient), +) +@mock.patch.object( + ShippingSettingsServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ShippingSettingsServiceAsyncClient), +) +def test_shipping_settings_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 @@ -532,8 +834,12 @@ def test_shipping_settings_service_client_get_mtls_endpoint_and_cert_source(clie 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 @@ -551,16 +857,28 @@ def test_shipping_settings_service_client_get_mtls_endpoint_and_cert_source(clie # 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 @@ -570,34 +888,62 @@ def test_shipping_settings_service_client_get_mtls_endpoint_and_cert_source(clie 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", [ - ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient -]) -@mock.patch.object(ShippingSettingsServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceClient)) -@mock.patch.object(ShippingSettingsServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ShippingSettingsServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [ShippingSettingsServiceClient, ShippingSettingsServiceAsyncClient] +) +@mock.patch.object( + ShippingSettingsServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceClient), +) +@mock.patch.object( + ShippingSettingsServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ShippingSettingsServiceAsyncClient), +) def test_shipping_settings_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = ShippingSettingsServiceClient._DEFAULT_UNIVERSE - default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = ShippingSettingsServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ShippingSettingsServiceClient._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", @@ -620,11 +966,19 @@ def test_shipping_settings_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. @@ -632,27 +986,48 @@ def test_shipping_settings_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", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc"), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest"), -]) -def test_shipping_settings_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + "grpc", + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceRestTransport, + "rest", + ), + ], +) +def test_shipping_settings_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, @@ -661,24 +1036,45 @@ def test_shipping_settings_service_client_client_options_scopes(client_class, tr api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceRestTransport, "rest", None), -]) -def test_shipping_settings_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", + [ + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceRestTransport, + "rest", + None, + ), + ], +) +def test_shipping_settings_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, @@ -687,11 +1083,14 @@ def test_shipping_settings_service_client_client_options_credentials_file(client api_audience=None, ) + def test_shipping_settings_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = ShippingSettingsServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1105,38 @@ def test_shipping_settings_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport, "grpc", grpc_helpers), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_shipping_settings_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", + [ + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_shipping_settings_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, @@ -749,9 +1163,7 @@ def test_shipping_settings_service_client_create_channel_credentials_file(client 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, @@ -762,11 +1174,14 @@ def test_shipping_settings_service_client_create_channel_credentials_file(client ) -@pytest.mark.parametrize("request_type", [ - shippingsettings.GetShippingSettingsRequest, - dict, -]) -def test_get_shipping_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + shippingsettings.GetShippingSettingsRequest, + dict, + ], +) +def test_get_shipping_settings(request_type, transport: str = "grpc"): client = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,12 +1193,12 @@ def test_get_shipping_settings(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', + name="name_value", + etag="etag_value", ) response = client.get_shipping_settings(request) @@ -795,8 +1210,8 @@ def test_get_shipping_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" def test_get_shipping_settings_non_empty_request_with_auto_populated_field(): @@ -804,28 +1219,31 @@ def test_get_shipping_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ShippingSettingsServiceClient( 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 = shippingsettings.GetShippingSettingsRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_shipping_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_shipping_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == shippingsettings.GetShippingSettingsRequest( - name='name_value', + name="name_value", ) + def test_get_shipping_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -840,12 +1258,19 @@ def test_get_shipping_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_shipping_settings in client._transport._wrapped_methods + assert ( + client._transport.get_shipping_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_shipping_settings + ] = mock_rpc request = {} client.get_shipping_settings(request) @@ -858,8 +1283,11 @@ def test_get_shipping_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_shipping_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_shipping_settings_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: @@ -873,12 +1301,17 @@ async def test_get_shipping_settings_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_shipping_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_shipping_settings + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_shipping_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_shipping_settings + ] = mock_rpc request = {} await client.get_shipping_settings(request) @@ -892,8 +1325,12 @@ async def test_get_shipping_settings_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.GetShippingSettingsRequest): +async def test_get_shipping_settings_async( + transport: str = "grpc_asyncio", + request_type=shippingsettings.GetShippingSettingsRequest, +): client = ShippingSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -905,13 +1342,15 @@ async def test_get_shipping_settings_async(transport: str = 'grpc_asyncio', requ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings( + name="name_value", + etag="etag_value", + ) + ) response = await client.get_shipping_settings(request) # Establish that the underlying gRPC stub method was called. @@ -922,14 +1361,15 @@ async def test_get_shipping_settings_async(transport: str = 'grpc_asyncio', requ # Establish that the response is the type that we expect. assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio async def test_get_shipping_settings_async_from_dict(): await test_get_shipping_settings_async(request_type=dict) + def test_get_shipping_settings_field_headers(): client = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -939,12 +1379,12 @@ def test_get_shipping_settings_field_headers(): # a field header. Set these to a non-empty value. request = shippingsettings.GetShippingSettingsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: call.return_value = shippingsettings.ShippingSettings() client.get_shipping_settings(request) @@ -956,9 +1396,9 @@ def test_get_shipping_settings_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 @@ -971,13 +1411,15 @@ async def test_get_shipping_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = shippingsettings.GetShippingSettingsRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + type(client.transport.get_shipping_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings() + ) await client.get_shipping_settings(request) # Establish that the underlying gRPC stub method was called. @@ -988,9 +1430,9 @@ async def test_get_shipping_settings_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_shipping_settings_flattened(): @@ -1000,14 +1442,14 @@ def test_get_shipping_settings_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = shippingsettings.ShippingSettings() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_shipping_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1015,7 +1457,7 @@ def test_get_shipping_settings_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 @@ -1029,9 +1471,10 @@ def test_get_shipping_settings_flattened_error(): with pytest.raises(ValueError): client.get_shipping_settings( shippingsettings.GetShippingSettingsRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_shipping_settings_flattened_async(): client = ShippingSettingsServiceAsyncClient( @@ -1040,16 +1483,18 @@ async def test_get_shipping_settings_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = shippingsettings.ShippingSettings() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_shipping_settings( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1057,9 +1502,10 @@ async def test_get_shipping_settings_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_shipping_settings_flattened_error_async(): client = ShippingSettingsServiceAsyncClient( @@ -1071,15 +1517,18 @@ async def test_get_shipping_settings_flattened_error_async(): with pytest.raises(ValueError): await client.get_shipping_settings( shippingsettings.GetShippingSettingsRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - shippingsettings.InsertShippingSettingsRequest, - dict, -]) -def test_insert_shipping_settings(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + shippingsettings.InsertShippingSettingsRequest, + dict, + ], +) +def test_insert_shipping_settings(request_type, transport: str = "grpc"): client = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1091,12 +1540,12 @@ def test_insert_shipping_settings(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_shipping_settings), - '__call__') as call: + type(client.transport.insert_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', + name="name_value", + etag="etag_value", ) response = client.insert_shipping_settings(request) @@ -1108,8 +1557,8 @@ def test_insert_shipping_settings(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" def test_insert_shipping_settings_non_empty_request_with_auto_populated_field(): @@ -1117,28 +1566,31 @@ def test_insert_shipping_settings_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = ShippingSettingsServiceClient( 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 = shippingsettings.InsertShippingSettingsRequest( - 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_shipping_settings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.insert_shipping_settings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.insert_shipping_settings(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == shippingsettings.InsertShippingSettingsRequest( - parent='parent_value', + parent="parent_value", ) + def test_insert_shipping_settings_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1153,12 +1605,19 @@ def test_insert_shipping_settings_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert_shipping_settings in client._transport._wrapped_methods + assert ( + client._transport.insert_shipping_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_shipping_settings] = 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_shipping_settings + ] = mock_rpc request = {} client.insert_shipping_settings(request) @@ -1171,8 +1630,11 @@ def test_insert_shipping_settings_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_insert_shipping_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_insert_shipping_settings_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: @@ -1186,12 +1648,17 @@ async def test_insert_shipping_settings_async_use_cached_wrapped_rpc(transport: wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.insert_shipping_settings in client._client._transport._wrapped_methods + assert ( + client._client._transport.insert_shipping_settings + 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_shipping_settings] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.insert_shipping_settings + ] = mock_rpc request = {} await client.insert_shipping_settings(request) @@ -1205,8 +1672,12 @@ async def test_insert_shipping_settings_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_shipping_settings_async(transport: str = 'grpc_asyncio', request_type=shippingsettings.InsertShippingSettingsRequest): +async def test_insert_shipping_settings_async( + transport: str = "grpc_asyncio", + request_type=shippingsettings.InsertShippingSettingsRequest, +): client = ShippingSettingsServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1218,13 +1689,15 @@ async def test_insert_shipping_settings_async(transport: str = 'grpc_asyncio', r # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: + type(client.transport.insert_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings( + name="name_value", + etag="etag_value", + ) + ) response = await client.insert_shipping_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1235,14 +1708,15 @@ async def test_insert_shipping_settings_async(transport: str = 'grpc_asyncio', r # Establish that the response is the type that we expect. assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.asyncio async def test_insert_shipping_settings_async_from_dict(): await test_insert_shipping_settings_async(request_type=dict) + def test_insert_shipping_settings_field_headers(): client = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1252,12 +1726,12 @@ def test_insert_shipping_settings_field_headers(): # a field header. Set these to a non-empty value. request = shippingsettings.InsertShippingSettingsRequest() - 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_shipping_settings), - '__call__') as call: + type(client.transport.insert_shipping_settings), "__call__" + ) as call: call.return_value = shippingsettings.ShippingSettings() client.insert_shipping_settings(request) @@ -1269,9 +1743,9 @@ def test_insert_shipping_settings_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 @@ -1284,13 +1758,15 @@ async def test_insert_shipping_settings_field_headers_async(): # a field header. Set these to a non-empty value. request = shippingsettings.InsertShippingSettingsRequest() - 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_shipping_settings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings()) + type(client.transport.insert_shipping_settings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings() + ) await client.insert_shipping_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1301,9 +1777,9 @@ async def test_insert_shipping_settings_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_get_shipping_settings_rest_use_cached_wrapped_rpc(): @@ -1320,12 +1796,19 @@ def test_get_shipping_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_shipping_settings in client._transport._wrapped_methods + assert ( + client._transport.get_shipping_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_shipping_settings] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_shipping_settings + ] = mock_rpc request = {} client.get_shipping_settings(request) @@ -1340,55 +1823,60 @@ def test_get_shipping_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_shipping_settings_rest_required_fields(request_type=shippingsettings.GetShippingSettingsRequest): +def test_get_shipping_settings_rest_required_fields( + request_type=shippingsettings.GetShippingSettingsRequest, +): transport_class = transports.ShippingSettingsServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_shipping_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_shipping_settings._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_shipping_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_shipping_settings._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 = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = shippingsettings.ShippingSettings() # Mock the http request 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 @@ -1399,24 +1887,24 @@ def test_get_shipping_settings_rest_required_fields(request_type=shippingsetting return_value = shippingsettings.ShippingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_shipping_settings(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_shipping_settings_rest_unset_required_fields(): - transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.ShippingSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_shipping_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_shipping_settings_rest_flattened(): @@ -1426,16 +1914,16 @@ def test_get_shipping_settings_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 = shippingsettings.ShippingSettings() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/shippingSettings'} + sample_request = {"name": "accounts/sample1/shippingSettings"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1445,7 +1933,7 @@ def test_get_shipping_settings_rest_flattened(): # Convert return value to protobuf type return_value = shippingsettings.ShippingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1455,10 +1943,14 @@ def test_get_shipping_settings_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/shippingSettings}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/shippingSettings}" + % client.transport._host, + args[1], + ) -def test_get_shipping_settings_rest_flattened_error(transport: str = 'rest'): +def test_get_shipping_settings_rest_flattened_error(transport: str = "rest"): client = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1469,7 +1961,7 @@ def test_get_shipping_settings_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_shipping_settings( shippingsettings.GetShippingSettingsRequest(), - name='name_value', + name="name_value", ) @@ -1487,12 +1979,19 @@ def test_insert_shipping_settings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert_shipping_settings in client._transport._wrapped_methods + assert ( + client._transport.insert_shipping_settings + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = 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_shipping_settings] = 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_shipping_settings + ] = mock_rpc request = {} client.insert_shipping_settings(request) @@ -1507,57 +2006,62 @@ def test_insert_shipping_settings_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_insert_shipping_settings_rest_required_fields(request_type=shippingsettings.InsertShippingSettingsRequest): +def test_insert_shipping_settings_rest_required_fields( + request_type=shippingsettings.InsertShippingSettingsRequest, +): transport_class = transports.ShippingSettingsServiceRestTransport 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_shipping_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert_shipping_settings._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_shipping_settings._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert_shipping_settings._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 = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = shippingsettings.ShippingSettings() # Mock the http request 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() @@ -1567,24 +2071,32 @@ def test_insert_shipping_settings_rest_required_fields(request_type=shippingsett return_value = shippingsettings.ShippingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_shipping_settings(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_shipping_settings_rest_unset_required_fields(): - transport = transports.ShippingSettingsServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.ShippingSettingsServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.insert_shipping_settings._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "shippingSetting", ))) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "shippingSetting", + ) + ) + ) def test_credentials_transport_error(): @@ -1625,8 +2137,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = ShippingSettingsServiceClient( - 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. @@ -1648,6 +2159,7 @@ def test_transport_instance(): client = ShippingSettingsServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ShippingSettingsServiceGrpcTransport( @@ -1662,18 +2174,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.ShippingSettingsServiceGrpcTransport, - transports.ShippingSettingsServiceGrpcAsyncIOTransport, - transports.ShippingSettingsServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + transports.ShippingSettingsServiceRestTransport, + ], +) 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 = ShippingSettingsServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1683,8 +2200,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1699,8 +2215,8 @@ def test_get_shipping_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: call.return_value = shippingsettings.ShippingSettings() client.get_shipping_settings(request=None) @@ -1722,8 +2238,8 @@ def test_insert_shipping_settings_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: + type(client.transport.insert_shipping_settings), "__call__" + ) as call: call.return_value = shippingsettings.ShippingSettings() client.insert_shipping_settings(request=None) @@ -1744,8 +2260,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = ShippingSettingsServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1761,13 +2276,15 @@ async def test_get_shipping_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings( + name="name_value", + etag="etag_value", + ) + ) await client.get_shipping_settings(request=None) # Establish that the underlying stub method was called. @@ -1789,13 +2306,15 @@ async def test_insert_shipping_settings_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: + type(client.transport.insert_shipping_settings), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + shippingsettings.ShippingSettings( + name="name_value", + etag="etag_value", + ) + ) await client.insert_shipping_settings(request=None) # Establish that the underlying stub method was called. @@ -1813,20 +2332,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_shipping_settings_rest_bad_request(request_type=shippingsettings.GetShippingSettingsRequest): +def test_get_shipping_settings_rest_bad_request( + request_type=shippingsettings.GetShippingSettingsRequest, +): client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/shippingSettings'} + request_init = {"name": "accounts/sample1/shippingSettings"} 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() @@ -1835,26 +2357,28 @@ def test_get_shipping_settings_rest_bad_request(request_type=shippingsettings.Ge client.get_shipping_settings(request) -@pytest.mark.parametrize("request_type", [ - shippingsettings.GetShippingSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + shippingsettings.GetShippingSettingsRequest, + dict, + ], +) def test_get_shipping_settings_rest_call_success(request_type): client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/shippingSettings'} + request_init = {"name": "accounts/sample1/shippingSettings"} request = request_type(**request_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 = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', + name="name_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -1864,34 +2388,45 @@ def test_get_shipping_settings_rest_call_success(request_type): # Convert return value to protobuf type return_value = shippingsettings.ShippingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_shipping_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_shipping_settings_rest_interceptors(null_interceptor): transport = transports.ShippingSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.ShippingSettingsServiceRestInterceptor(), + ) client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings") as post, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_get_shipping_settings") 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.ShippingSettingsServiceRestInterceptor, "post_get_shipping_settings" + ) as post, mock.patch.object( + transports.ShippingSettingsServiceRestInterceptor, + "post_get_shipping_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.ShippingSettingsServiceRestInterceptor, "pre_get_shipping_settings" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = shippingsettings.GetShippingSettingsRequest.pb(shippingsettings.GetShippingSettingsRequest()) + pb_message = shippingsettings.GetShippingSettingsRequest.pb( + shippingsettings.GetShippingSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -1902,11 +2437,13 @@ def test_get_shipping_settings_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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) + return_value = shippingsettings.ShippingSettings.to_json( + shippingsettings.ShippingSettings() + ) req.return_value.content = return_value request = shippingsettings.GetShippingSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -1914,27 +2451,36 @@ def test_get_shipping_settings_rest_interceptors(null_interceptor): post.return_value = shippingsettings.ShippingSettings() post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata - client.get_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_shipping_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_insert_shipping_settings_rest_bad_request(request_type=shippingsettings.InsertShippingSettingsRequest): +def test_insert_shipping_settings_rest_bad_request( + request_type=shippingsettings.InsertShippingSettingsRequest, +): client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -1943,25 +2489,176 @@ def test_insert_shipping_settings_rest_bad_request(request_type=shippingsettings client.insert_shipping_settings(request) -@pytest.mark.parametrize("request_type", [ - shippingsettings.InsertShippingSettingsRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + shippingsettings.InsertShippingSettingsRequest, + dict, + ], +) def test_insert_shipping_settings_rest_call_success(request_type): client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["shipping_setting"] = {'name': 'name_value', 'services': [{'service_name': 'service_name_value', 'active': True, 'delivery_countries': ['delivery_countries_value1', 'delivery_countries_value2'], 'currency_code': 'currency_code_value', 'delivery_time': {'min_transit_days': 1720, 'max_transit_days': 1722, 'cutoff_time': {'hour': 446, 'minute': 658, 'time_zone': 'time_zone_value'}, 'min_handling_days': 1784, 'max_handling_days': 1786, 'transit_time_table': {'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'transit_time_labels': ['transit_time_labels_value1', 'transit_time_labels_value2'], 'rows': [{'values': [{'min_transit_days': 1720, 'max_transit_days': 1722}]}]}, 'handling_business_day_config': {'business_days': [1]}, 'transit_business_day_config': {}, 'warehouse_based_delivery_times': [{'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'warehouse': 'warehouse_value'}]}, 'rate_groups': [{'applicable_shipping_labels': ['applicable_shipping_labels_value1', 'applicable_shipping_labels_value2'], 'single_value': {'no_shipping': True, 'flat_rate': {'amount_micros': 1408, 'currency_code': 'currency_code_value'}, 'price_percentage': 'price_percentage_value', 'carrier_rate': 'carrier_rate_value', 'subtable': 'subtable_value'}, 'main_table': {'name': 'name_value', 'row_headers': {'prices': {}, 'weights': [{'amount_micros': 1408, 'unit': 1}], 'number_of_items': ['number_of_items_value1', 'number_of_items_value2'], 'postal_code_group_names': ['postal_code_group_names_value1', 'postal_code_group_names_value2'], 'locations': [{'location_ids': ['location_ids_value1', 'location_ids_value2']}]}, 'column_headers': {}, 'rows': [{'cells': {}}]}, 'subtables': {}, 'carrier_rates': [{'name': 'name_value', 'carrier': 'carrier_value', 'carrier_service': 'carrier_service_value', 'origin_postal_code': 'origin_postal_code_value', 'percentage_adjustment': 'percentage_adjustment_value', 'flat_adjustment': {}}], 'name': 'name_value'}], 'shipment_type': 1, 'minimum_order_value': {}, 'minimum_order_value_table': {'store_code_set_with_movs': [{'store_codes': ['store_codes_value1', 'store_codes_value2'], 'value': {}}]}, 'store_config': {'store_service_type': 1, 'store_codes': ['store_codes_value1', 'store_codes_value2'], 'cutoff_config': {'local_cutoff_time': {'hour': 446, 'minute': 658}, 'store_close_offset_hours': 2584, 'no_delivery_post_cutoff': True}, 'service_radius': {'value': 541, 'unit': 1}}, 'loyalty_programs': [{'program_label': 'program_label_value', 'loyalty_program_tiers': [{'tier_label': 'tier_label_value'}]}]}], 'warehouses': [{'name': 'name_value', 'shipping_address': {'street_address': 'street_address_value', 'city': 'city_value', 'administrative_area': 'administrative_area_value', 'postal_code': 'postal_code_value', 'region_code': 'region_code_value'}, 'cutoff_time': {'hour': 446, 'minute': 658}, 'handling_days': 1365, 'business_day_config': {}}], 'etag': 'etag_value'} + request_init = {"parent": "accounts/sample1"} + request_init["shipping_setting"] = { + "name": "name_value", + "services": [ + { + "service_name": "service_name_value", + "active": True, + "delivery_countries": [ + "delivery_countries_value1", + "delivery_countries_value2", + ], + "currency_code": "currency_code_value", + "delivery_time": { + "min_transit_days": 1720, + "max_transit_days": 1722, + "cutoff_time": { + "hour": 446, + "minute": 658, + "time_zone": "time_zone_value", + }, + "min_handling_days": 1784, + "max_handling_days": 1786, + "transit_time_table": { + "postal_code_group_names": [ + "postal_code_group_names_value1", + "postal_code_group_names_value2", + ], + "transit_time_labels": [ + "transit_time_labels_value1", + "transit_time_labels_value2", + ], + "rows": [ + { + "values": [ + {"min_transit_days": 1720, "max_transit_days": 1722} + ] + } + ], + }, + "handling_business_day_config": {"business_days": [1]}, + "transit_business_day_config": {}, + "warehouse_based_delivery_times": [ + { + "carrier": "carrier_value", + "carrier_service": "carrier_service_value", + "warehouse": "warehouse_value", + } + ], + }, + "rate_groups": [ + { + "applicable_shipping_labels": [ + "applicable_shipping_labels_value1", + "applicable_shipping_labels_value2", + ], + "single_value": { + "no_shipping": True, + "flat_rate": { + "amount_micros": 1408, + "currency_code": "currency_code_value", + }, + "price_percentage": "price_percentage_value", + "carrier_rate": "carrier_rate_value", + "subtable": "subtable_value", + }, + "main_table": { + "name": "name_value", + "row_headers": { + "prices": {}, + "weights": [{"amount_micros": 1408, "unit": 1}], + "number_of_items": [ + "number_of_items_value1", + "number_of_items_value2", + ], + "postal_code_group_names": [ + "postal_code_group_names_value1", + "postal_code_group_names_value2", + ], + "locations": [ + { + "location_ids": [ + "location_ids_value1", + "location_ids_value2", + ] + } + ], + }, + "column_headers": {}, + "rows": [{"cells": {}}], + }, + "subtables": {}, + "carrier_rates": [ + { + "name": "name_value", + "carrier": "carrier_value", + "carrier_service": "carrier_service_value", + "origin_postal_code": "origin_postal_code_value", + "percentage_adjustment": "percentage_adjustment_value", + "flat_adjustment": {}, + } + ], + "name": "name_value", + } + ], + "shipment_type": 1, + "minimum_order_value": {}, + "minimum_order_value_table": { + "store_code_set_with_movs": [ + { + "store_codes": ["store_codes_value1", "store_codes_value2"], + "value": {}, + } + ] + }, + "store_config": { + "store_service_type": 1, + "store_codes": ["store_codes_value1", "store_codes_value2"], + "cutoff_config": { + "local_cutoff_time": {"hour": 446, "minute": 658}, + "store_close_offset_hours": 2584, + "no_delivery_post_cutoff": True, + }, + "service_radius": {"value": 541, "unit": 1}, + }, + "loyalty_programs": [ + { + "program_label": "program_label_value", + "loyalty_program_tiers": [{"tier_label": "tier_label_value"}], + } + ], + } + ], + "warehouses": [ + { + "name": "name_value", + "shipping_address": { + "street_address": "street_address_value", + "city": "city_value", + "administrative_area": "administrative_area_value", + "postal_code": "postal_code_value", + "region_code": "region_code_value", + }, + "cutoff_time": {"hour": 446, "minute": 658}, + "handling_days": 1365, + "business_day_config": {}, + } + ], + "etag": "etag_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 = shippingsettings.InsertShippingSettingsRequest.meta.fields["shipping_setting"] + test_field = shippingsettings.InsertShippingSettingsRequest.meta.fields[ + "shipping_setting" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -1975,7 +2672,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 @@ -1989,7 +2686,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["shipping_setting"].items(): # pragma: NO COVER + for field, value in request_init["shipping_setting"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2004,12 +2701,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") @@ -2022,11 +2723,11 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = shippingsettings.ShippingSettings( - name='name_value', - etag='etag_value', + name="name_value", + etag="etag_value", ) # Wrap the value into a proper Response obj @@ -2036,34 +2737,47 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = shippingsettings.ShippingSettings.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_shipping_settings(request) # Establish that the response is the type that we expect. assert isinstance(response, shippingsettings.ShippingSettings) - assert response.name == 'name_value' - assert response.etag == 'etag_value' + assert response.name == "name_value" + assert response.etag == "etag_value" @pytest.mark.parametrize("null_interceptor", [True, False]) def test_insert_shipping_settings_rest_interceptors(null_interceptor): transport = transports.ShippingSettingsServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ShippingSettingsServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.ShippingSettingsServiceRestInterceptor(), + ) client = ShippingSettingsServiceClient(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.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings") as post, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "post_insert_shipping_settings_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ShippingSettingsServiceRestInterceptor, "pre_insert_shipping_settings") 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.ShippingSettingsServiceRestInterceptor, + "post_insert_shipping_settings", + ) as post, mock.patch.object( + transports.ShippingSettingsServiceRestInterceptor, + "post_insert_shipping_settings_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.ShippingSettingsServiceRestInterceptor, + "pre_insert_shipping_settings", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = shippingsettings.InsertShippingSettingsRequest.pb(shippingsettings.InsertShippingSettingsRequest()) + pb_message = shippingsettings.InsertShippingSettingsRequest.pb( + shippingsettings.InsertShippingSettingsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2074,11 +2788,13 @@ def test_insert_shipping_settings_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 = shippingsettings.ShippingSettings.to_json(shippingsettings.ShippingSettings()) + return_value = shippingsettings.ShippingSettings.to_json( + shippingsettings.ShippingSettings() + ) req.return_value.content = return_value request = shippingsettings.InsertShippingSettingsRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2086,16 +2802,22 @@ def test_insert_shipping_settings_rest_interceptors(null_interceptor): post.return_value = shippingsettings.ShippingSettings() post_with_metadata.return_value = shippingsettings.ShippingSettings(), metadata - client.insert_shipping_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.insert_shipping_settings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = ShippingSettingsServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2110,8 +2832,8 @@ def test_get_shipping_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_shipping_settings), - '__call__') as call: + type(client.transport.get_shipping_settings), "__call__" + ) as call: client.get_shipping_settings(request=None) # Establish that the underlying stub method was called. @@ -2132,8 +2854,8 @@ def test_insert_shipping_settings_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.insert_shipping_settings), - '__call__') as call: + type(client.transport.insert_shipping_settings), "__call__" + ) as call: client.insert_shipping_settings(request=None) # Establish that the underlying stub method was called. @@ -2154,18 +2876,21 @@ def test_transport_grpc_default(): transports.ShippingSettingsServiceGrpcTransport, ) + def test_shipping_settings_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ShippingSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_shipping_settings_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.ShippingSettingsServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2174,8 +2899,8 @@ def test_shipping_settings_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_shipping_settings', - 'insert_shipping_settings', + "get_shipping_settings", + "insert_shipping_settings", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2186,7 +2911,7 @@ def test_shipping_settings_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2195,25 +2920,30 @@ def test_shipping_settings_service_base_transport(): def test_shipping_settings_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_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._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_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ShippingSettingsServiceTransport( 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_shipping_settings_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_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.shipping_settings_service.transports.ShippingSettingsServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ShippingSettingsServiceTransport() @@ -2222,14 +2952,12 @@ def test_shipping_settings_service_base_transport_with_adc(): def test_shipping_settings_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) ShippingSettingsServiceClient() 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, ) @@ -2244,12 +2972,12 @@ def test_shipping_settings_service_auth_adc(): def test_shipping_settings_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", ) @@ -2263,48 +2991,47 @@ def test_shipping_settings_service_transport_auth_adc(transport_class): ], ) def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, grpc_helpers), - (transports.ShippingSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.ShippingSettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_shipping_settings_service_transport_create_channel(transport_class, grpc_helpers): +def test_shipping_settings_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, @@ -2315,9 +3042,15 @@ def test_shipping_settings_service_transport_create_channel(transport_class, grp ) -@pytest.mark.parametrize("transport_class", [transports.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + ], +) def test_shipping_settings_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2327,7 +3060,7 @@ def test_shipping_settings_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", @@ -2348,61 +3081,77 @@ def test_shipping_settings_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_shipping_settings_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.ShippingSettingsServiceRestTransport ( - 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.ShippingSettingsServiceRestTransport( + 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_shipping_settings_service_host_no_port(transport_name): client = ShippingSettingsServiceClient( 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_shipping_settings_service_host_with_port(transport_name): client = ShippingSettingsServiceClient( 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_shipping_settings_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -2420,8 +3169,10 @@ def test_shipping_settings_service_client_transport_session_collision(transport_ session1 = client1.transport.insert_shipping_settings._session session2 = client2.transport.insert_shipping_settings._session assert session1 != session2 + + def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport( @@ -2434,7 +3185,7 @@ def test_shipping_settings_service_grpc_transport_channel(): def test_shipping_settings_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.ShippingSettingsServiceGrpcAsyncIOTransport( @@ -2448,12 +3199,22 @@ def test_shipping_settings_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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + ], +) def test_shipping_settings_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 @@ -2462,7 +3223,7 @@ def test_shipping_settings_service_transport_channel_mtls_with_client_cert_sourc 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", @@ -2492,17 +3253,23 @@ def test_shipping_settings_service_transport_channel_mtls_with_client_cert_sourc # 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.ShippingSettingsServiceGrpcTransport, transports.ShippingSettingsServiceGrpcAsyncIOTransport]) -def test_shipping_settings_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ShippingSettingsServiceGrpcTransport, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + ], +) +def test_shipping_settings_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() @@ -2532,7 +3299,9 @@ def test_shipping_settings_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = ShippingSettingsServiceClient.account_path(account) assert expected == actual @@ -2547,9 +3316,12 @@ def test_parse_account_path(): actual = ShippingSettingsServiceClient.parse_account_path(path) assert expected == actual + def test_shipping_settings_path(): account = "whelk" - expected = "accounts/{account}/shippingSettings".format(account=account, ) + expected = "accounts/{account}/shippingSettings".format( + account=account, + ) actual = ShippingSettingsServiceClient.shipping_settings_path(account) assert expected == actual @@ -2564,9 +3336,12 @@ def test_parse_shipping_settings_path(): actual = ShippingSettingsServiceClient.parse_shipping_settings_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = ShippingSettingsServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -2581,9 +3356,12 @@ def test_parse_common_billing_account_path(): actual = ShippingSettingsServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = ShippingSettingsServiceClient.common_folder_path(folder) assert expected == actual @@ -2598,9 +3376,12 @@ def test_parse_common_folder_path(): actual = ShippingSettingsServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = ShippingSettingsServiceClient.common_organization_path(organization) assert expected == actual @@ -2615,9 +3396,12 @@ def test_parse_common_organization_path(): actual = ShippingSettingsServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = ShippingSettingsServiceClient.common_project_path(project) assert expected == actual @@ -2632,10 +3416,14 @@ def test_parse_common_project_path(): actual = ShippingSettingsServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = ShippingSettingsServiceClient.common_location_path(project, location) assert expected == actual @@ -2655,14 +3443,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.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.ShippingSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: client = ShippingSettingsServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.ShippingSettingsServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.ShippingSettingsServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = ShippingSettingsServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -2673,10 +3465,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = ShippingSettingsServiceClient( - 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() @@ -2685,10 +3478,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = ShippingSettingsServiceAsyncClient( - 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() @@ -2696,10 +3490,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = ShippingSettingsServiceClient( - 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() @@ -2707,13 +3502,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = ShippingSettingsServiceClient( - 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: @@ -2722,10 +3516,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (ShippingSettingsServiceClient, transports.ShippingSettingsServiceGrpcTransport), - (ShippingSettingsServiceAsyncClient, transports.ShippingSettingsServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + ShippingSettingsServiceClient, + transports.ShippingSettingsServiceGrpcTransport, + ), + ( + ShippingSettingsServiceAsyncClient, + transports.ShippingSettingsServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2740,7 +3544,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py similarity index 62% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py index 6c2a2184becb..1b10899c4341 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_agreement_state_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,45 +22,45 @@ 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.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import TermsOfServiceAgreementStateServiceClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import transports -from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind -import google.auth - +from google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service import ( + TermsOfServiceAgreementStateServiceAsyncClient, + TermsOfServiceAgreementStateServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import ( + termsofserviceagreementstate, + termsofservicekind, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -74,9 +75,11 @@ async def mock_async_gen(data, chunk_size=1): chunk = data[i : i + chunk_size] yield chunk.encode("utf-8") + def client_cert_source_callback(): return b"cert bytes", b"key bytes" + # TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. # See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. def async_anonymous_credentials(): @@ -84,17 +87,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(): @@ -104,102 +117,264 @@ def test__get_default_mtls_endpoint(): sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(None) is None - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint(None) + is None + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint( + api_endpoint + ) + == api_mtls_endpoint + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint( + api_mtls_endpoint + ) + == api_mtls_endpoint + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint( + sandbox_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_default_mtls_endpoint( + non_googleapi + ) + == non_googleapi + ) + def test__read_environment_variables(): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (True, "auto", None) + assert ( + TermsOfServiceAgreementStateServiceClient._read_environment_variables() + == (True, "auto", None) + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + assert ( + TermsOfServiceAgreementStateServiceClient._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: TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "never", None) + assert ( + TermsOfServiceAgreementStateServiceClient._read_environment_variables() + == (False, "never", None) + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "always", None) + assert ( + TermsOfServiceAgreementStateServiceClient._read_environment_variables() + == (False, "always", None) + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", None) + assert ( + TermsOfServiceAgreementStateServiceClient._read_environment_variables() + == (False, "auto", None) + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert ( + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, False) is None - assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, False) + is None + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + TermsOfServiceAgreementStateServiceClient._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 ( + TermsOfServiceAgreementStateServiceClient._get_client_cert_source( + None, True + ) + is mock_default_cert_source + ) + assert ( + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert TermsOfServiceAgreementStateServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) +@mock.patch.object( + TermsOfServiceAgreementStateServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient), +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + ) - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert TermsOfServiceAgreementStateServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == TermsOfServiceAgreementStateServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - TermsOfServiceAgreementStateServiceClient._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." + TermsOfServiceAgreementStateServiceClient._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 TermsOfServiceAgreementStateServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, None) == TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + assert ( + TermsOfServiceAgreementStateServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_universe_domain( + None, universe_domain_env + ) + == universe_domain_env + ) + assert ( + TermsOfServiceAgreementStateServiceClient._get_universe_domain(None, None) + == TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: TermsOfServiceAgreementStateServiceClient._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) @@ -215,7 +390,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") @@ -228,14 +404,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", [ - (TermsOfServiceAgreementStateServiceClient, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, "rest"), -]) -def test_terms_of_service_agreement_state_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (TermsOfServiceAgreementStateServiceClient, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, "rest"), + ], +) +def test_terms_of_service_agreement_state_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) @@ -243,52 +427,73 @@ def test_terms_of_service_agreement_state_service_client_from_service_account_in 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.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), + ( + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), + ], +) +def test_terms_of_service_agreement_state_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", [ - (TermsOfServiceAgreementStateServiceClient, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, "rest"), -]) -def test_terms_of_service_agreement_state_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (TermsOfServiceAgreementStateServiceClient, "grpc"), + (TermsOfServiceAgreementStateServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceAgreementStateServiceClient, "rest"), + ], +) +def test_terms_of_service_agreement_state_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" ) @@ -304,30 +509,57 @@ def test_terms_of_service_agreement_state_service_client_get_transport_class(): assert transport == transports.TermsOfServiceAgreementStateServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) -def test_terms_of_service_agreement_state_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + "grpc", + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient), +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient), +) +def test_terms_of_service_agreement_state_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(TermsOfServiceAgreementStateServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object( + TermsOfServiceAgreementStateServiceClient, "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(TermsOfServiceAgreementStateServiceClient, 'get_transport_class') as gtc: + with mock.patch.object( + TermsOfServiceAgreementStateServiceClient, "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( @@ -345,13 +577,15 @@ def test_terms_of_service_agreement_state_service_client_client_options(client_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, @@ -363,7 +597,7 @@ def test_terms_of_service_agreement_state_service_client_client_options(client_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( @@ -383,23 +617,33 @@ def test_terms_of_service_agreement_state_service_client_client_options(client_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", @@ -408,48 +652,102 @@ def test_terms_of_service_agreement_state_service_client_client_options(client_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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "true"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", "false"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "true"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + "grpc", + "true", + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + "grpc", + "false", + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceRestTransport, + "rest", + "true", + ), + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient), +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_terms_of_service_agreement_state_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_terms_of_service_agreement_state_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 @@ -468,12 +766,22 @@ def test_terms_of_service_agreement_state_service_client_mtls_env_auto(client_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 @@ -494,15 +802,22 @@ def test_terms_of_service_agreement_state_service_client_mtls_env_auto(client_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, @@ -512,19 +827,37 @@ def test_terms_of_service_agreement_state_service_client_mtls_env_auto(client_cl ) -@pytest.mark.parametrize("client_class", [ - TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceAgreementStateServiceAsyncClient)) -def test_terms_of_service_agreement_state_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", + [ + TermsOfServiceAgreementStateServiceClient, + TermsOfServiceAgreementStateServiceAsyncClient, + ], +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TermsOfServiceAgreementStateServiceClient), +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TermsOfServiceAgreementStateServiceAsyncClient), +) +def test_terms_of_service_agreement_state_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 @@ -532,8 +865,12 @@ def test_terms_of_service_agreement_state_service_client_get_mtls_endpoint_and_c 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 @@ -551,16 +888,28 @@ def test_terms_of_service_agreement_state_service_client_get_mtls_endpoint_and_c # 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 @@ -570,34 +919,72 @@ def test_terms_of_service_agreement_state_service_client_get_mtls_endpoint_and_c 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", [ - TermsOfServiceAgreementStateServiceClient, TermsOfServiceAgreementStateServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceAgreementStateServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient)) -@mock.patch.object(TermsOfServiceAgreementStateServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient)) -def test_terms_of_service_agreement_state_service_client_client_api_endpoint(client_class): +@pytest.mark.parametrize( + "client_class", + [ + TermsOfServiceAgreementStateServiceClient, + TermsOfServiceAgreementStateServiceAsyncClient, + ], +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceClient), +) +@mock.patch.object( + TermsOfServiceAgreementStateServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceAgreementStateServiceAsyncClient), +) +def test_terms_of_service_agreement_state_service_client_client_api_endpoint( + client_class, +): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = TermsOfServiceAgreementStateServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = ( + TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + ) mock_universe = "bar.com" - mock_endpoint = TermsOfServiceAgreementStateServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = ( + TermsOfServiceAgreementStateServiceClient._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", @@ -620,11 +1007,19 @@ def test_terms_of_service_agreement_state_service_client_client_api_endpoint(cli 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. @@ -632,27 +1027,48 @@ def test_terms_of_service_agreement_state_service_client_client_api_endpoint(cli 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", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc"), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest"), -]) -def test_terms_of_service_agreement_state_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + "grpc", + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceRestTransport, + "rest", + ), + ], +) +def test_terms_of_service_agreement_state_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, @@ -661,24 +1077,45 @@ def test_terms_of_service_agreement_state_service_client_client_options_scopes(c api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceRestTransport, "rest", None), -]) -def test_terms_of_service_agreement_state_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", + [ + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceRestTransport, + "rest", + None, + ), + ], +) +def test_terms_of_service_agreement_state_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, @@ -687,11 +1124,14 @@ def test_terms_of_service_agreement_state_service_client_client_options_credenti api_audience=None, ) + def test_terms_of_service_agreement_state_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = TermsOfServiceAgreementStateServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -706,23 +1146,38 @@ def test_terms_of_service_agreement_state_service_client_client_options_from_dic ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_terms_of_service_agreement_state_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", + [ + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_terms_of_service_agreement_state_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, @@ -749,9 +1204,7 @@ def test_terms_of_service_agreement_state_service_client_create_channel_credenti 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, @@ -762,11 +1215,14 @@ def test_terms_of_service_agreement_state_service_client_create_channel_credenti ) -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, - dict, -]) -def test_get_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, + ], +) +def test_get_terms_of_service_agreement_state(request_type, transport: str = "grpc"): client = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -778,12 +1234,12 @@ def test_get_terms_of_service_agreement_state(request_type, transport: str = 'gr # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, ) response = client.get_terms_of_service_agreement_state(request) @@ -795,10 +1251,15 @@ def test_get_terms_of_service_agreement_state(request_type, transport: str = 'gr assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert isinstance( + response, termsofserviceagreementstate.TermsOfServiceAgreementState + ) + assert response.name == "name_value" + assert response.region_code == "region_code_value" + assert ( + response.terms_of_service_kind + == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + ) def test_get_terms_of_service_agreement_state_non_empty_request_with_auto_populated_field(): @@ -806,28 +1267,33 @@ def test_get_terms_of_service_agreement_state_non_empty_request_with_auto_popula # automatically populated, according to AIP-4235, with non-empty requests. client = TermsOfServiceAgreementStateServiceClient( 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 = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_terms_of_service_agreement_state(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( - name='name_value', + assert args[ + 0 + ] == termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest( + name="name_value", ) + def test_get_terms_of_service_agreement_state_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -842,12 +1308,19 @@ def test_get_terms_of_service_agreement_state_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_terms_of_service_agreement_state in client._transport._wrapped_methods + assert ( + client._transport.get_terms_of_service_agreement_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_terms_of_service_agreement_state + ] = mock_rpc request = {} client.get_terms_of_service_agreement_state(request) @@ -860,8 +1333,11 @@ def test_get_terms_of_service_agreement_state_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_terms_of_service_agreement_state_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_terms_of_service_agreement_state_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: @@ -875,12 +1351,17 @@ async def test_get_terms_of_service_agreement_state_async_use_cached_wrapped_rpc wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_terms_of_service_agreement_state in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_terms_of_service_agreement_state + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service_agreement_state] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_terms_of_service_agreement_state + ] = mock_rpc request = {} await client.get_terms_of_service_agreement_state(request) @@ -894,8 +1375,12 @@ async def test_get_terms_of_service_agreement_state_async_use_cached_wrapped_rpc assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): +async def test_get_terms_of_service_agreement_state_async( + transport: str = "grpc_asyncio", + request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, +): client = TermsOfServiceAgreementStateServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -907,14 +1392,16 @@ async def test_get_terms_of_service_agreement_state_async(transport: str = 'grpc # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState( + name="name_value", + region_code="region_code_value", + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + ) response = await client.get_terms_of_service_agreement_state(request) # Establish that the underlying gRPC stub method was called. @@ -924,16 +1411,22 @@ async def test_get_terms_of_service_agreement_state_async(transport: str = 'grpc assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert isinstance( + response, termsofserviceagreementstate.TermsOfServiceAgreementState + ) + assert response.name == "name_value" + assert response.region_code == "region_code_value" + assert ( + response.terms_of_service_kind + == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + ) @pytest.mark.asyncio async def test_get_terms_of_service_agreement_state_async_from_dict(): await test_get_terms_of_service_agreement_state_async(request_type=dict) + def test_get_terms_of_service_agreement_state_field_headers(): client = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -943,12 +1436,12 @@ def test_get_terms_of_service_agreement_state_field_headers(): # a field header. Set these to a non-empty value. request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() client.get_terms_of_service_agreement_state(request) @@ -960,9 +1453,9 @@ def test_get_terms_of_service_agreement_state_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 @@ -975,13 +1468,15 @@ async def test_get_terms_of_service_agreement_state_field_headers_async(): # a field header. Set these to a non-empty value. request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState() + ) await client.get_terms_of_service_agreement_state(request) # Establish that the underlying gRPC stub method was called. @@ -992,9 +1487,9 @@ async def test_get_terms_of_service_agreement_state_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_terms_of_service_agreement_state_flattened(): @@ -1004,14 +1499,14 @@ def test_get_terms_of_service_agreement_state_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_terms_of_service_agreement_state( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1019,7 +1514,7 @@ def test_get_terms_of_service_agreement_state_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 @@ -1033,9 +1528,10 @@ def test_get_terms_of_service_agreement_state_flattened_error(): with pytest.raises(ValueError): client.get_terms_of_service_agreement_state( termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_terms_of_service_agreement_state_flattened_async(): client = TermsOfServiceAgreementStateServiceAsyncClient( @@ -1044,16 +1540,18 @@ async def test_get_terms_of_service_agreement_state_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_terms_of_service_agreement_state( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1061,9 +1559,10 @@ async def test_get_terms_of_service_agreement_state_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_terms_of_service_agreement_state_flattened_error_async(): client = TermsOfServiceAgreementStateServiceAsyncClient( @@ -1075,15 +1574,20 @@ async def test_get_terms_of_service_agreement_state_flattened_error_async(): with pytest.raises(ValueError): await client.get_terms_of_service_agreement_state( termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, - dict, -]) -def test_retrieve_for_application_terms_of_service_agreement_state(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + dict, + ], +) +def test_retrieve_for_application_terms_of_service_agreement_state( + request_type, transport: str = "grpc" +): client = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1095,27 +1599,39 @@ def test_retrieve_for_application_terms_of_service_agreement_state(request_type, # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, ) - response = client.retrieve_for_application_terms_of_service_agreement_state(request) + response = client.retrieve_for_application_terms_of_service_agreement_state( + request + ) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert isinstance( + response, termsofserviceagreementstate.TermsOfServiceAgreementState + ) + assert response.name == "name_value" + assert response.region_code == "region_code_value" + assert ( + response.terms_of_service_kind + == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + ) def test_retrieve_for_application_terms_of_service_agreement_state_non_empty_request_with_auto_populated_field(): @@ -1123,28 +1639,38 @@ def test_retrieve_for_application_terms_of_service_agreement_state_non_empty_req # automatically populated, according to AIP-4235, with non-empty requests. client = TermsOfServiceAgreementStateServiceClient( 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - 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.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.retrieve_for_application_terms_of_service_agreement_state(request=request) + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.retrieve_for_application_terms_of_service_agreement_state( + request=request + ) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( - parent='parent_value', + assert args[ + 0 + ] == termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest( + parent="parent_value", ) + def test_retrieve_for_application_terms_of_service_agreement_state_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1159,12 +1685,19 @@ def test_retrieve_for_application_terms_of_service_agreement_state_use_cached_wr wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods + assert ( + client._transport.retrieve_for_application_terms_of_service_agreement_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_for_application_terms_of_service_agreement_state + ] = mock_rpc request = {} client.retrieve_for_application_terms_of_service_agreement_state(request) @@ -1177,8 +1710,11 @@ def test_retrieve_for_application_terms_of_service_agreement_state_use_cached_wr assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_retrieve_for_application_terms_of_service_agreement_state_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_retrieve_for_application_terms_of_service_agreement_state_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: @@ -1192,12 +1728,17 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_async_u wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.retrieve_for_application_terms_of_service_agreement_state in client._client._transport._wrapped_methods + assert ( + client._client._transport.retrieve_for_application_terms_of_service_agreement_state + 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.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_for_application_terms_of_service_agreement_state + ] = mock_rpc request = {} await client.retrieve_for_application_terms_of_service_agreement_state(request) @@ -1211,8 +1752,12 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_async_u assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_retrieve_for_application_terms_of_service_agreement_state_async(transport: str = 'grpc_asyncio', request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): +async def test_retrieve_for_application_terms_of_service_agreement_state_async( + transport: str = "grpc_asyncio", + request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, +): client = TermsOfServiceAgreementStateServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1224,32 +1769,51 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_async(t # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) - response = await client.retrieve_for_application_terms_of_service_agreement_state(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState( + name="name_value", + region_code="region_code_value", + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + ) + response = ( + await client.retrieve_for_application_terms_of_service_agreement_state( + request + ) + ) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert isinstance( + response, termsofserviceagreementstate.TermsOfServiceAgreementState + ) + assert response.name == "name_value" + assert response.region_code == "region_code_value" + assert ( + response.terms_of_service_kind + == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + ) @pytest.mark.asyncio async def test_retrieve_for_application_terms_of_service_agreement_state_async_from_dict(): - await test_retrieve_for_application_terms_of_service_agreement_state_async(request_type=dict) + await test_retrieve_for_application_terms_of_service_agreement_state_async( + request_type=dict + ) + def test_retrieve_for_application_terms_of_service_agreement_state_field_headers(): client = TermsOfServiceAgreementStateServiceClient( @@ -1258,14 +1822,19 @@ def test_retrieve_for_application_terms_of_service_agreement_state_field_headers # 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) - 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.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() client.retrieve_for_application_terms_of_service_agreement_state(request) @@ -1277,9 +1846,9 @@ def test_retrieve_for_application_terms_of_service_agreement_state_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 @@ -1290,15 +1859,22 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_field_h # 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 = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) - 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.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState() + ) await client.retrieve_for_application_terms_of_service_agreement_state(request) # Establish that the underlying gRPC stub method was called. @@ -1309,9 +1885,9 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_field_h # 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_retrieve_for_application_terms_of_service_agreement_state_flattened(): @@ -1321,14 +1897,17 @@ def test_retrieve_for_application_terms_of_service_agreement_state_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.retrieve_for_application_terms_of_service_agreement_state( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1336,7 +1915,7 @@ def test_retrieve_for_application_terms_of_service_agreement_state_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 @@ -1350,9 +1929,10 @@ def test_retrieve_for_application_terms_of_service_agreement_state_flattened_err with pytest.raises(ValueError): client.retrieve_for_application_terms_of_service_agreement_state( termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_retrieve_for_application_terms_of_service_agreement_state_flattened_async(): client = TermsOfServiceAgreementStateServiceAsyncClient( @@ -1361,16 +1941,23 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_flatten # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.retrieve_for_application_terms_of_service_agreement_state( - parent='parent_value', + response = ( + await client.retrieve_for_application_terms_of_service_agreement_state( + parent="parent_value", + ) ) # Establish that the underlying call was made with the expected @@ -1378,9 +1965,10 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_flatten 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_retrieve_for_application_terms_of_service_agreement_state_flattened_error_async(): client = TermsOfServiceAgreementStateServiceAsyncClient( @@ -1392,7 +1980,7 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_flatten with pytest.raises(ValueError): await client.retrieve_for_application_terms_of_service_agreement_state( termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1410,12 +1998,19 @@ def test_get_terms_of_service_agreement_state_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_terms_of_service_agreement_state in client._transport._wrapped_methods + assert ( + client._transport.get_terms_of_service_agreement_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service_agreement_state] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_terms_of_service_agreement_state + ] = mock_rpc request = {} client.get_terms_of_service_agreement_state(request) @@ -1430,55 +2025,60 @@ def test_get_terms_of_service_agreement_state_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): +def test_get_terms_of_service_agreement_state_rest_required_fields( + request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, +): transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() # Mock the http request 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 @@ -1486,27 +2086,31 @@ def test_get_terms_of_service_agreement_state_rest_required_fields(request_type= response_value.status_code = 200 # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(return_value) + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_terms_of_service_agreement_state(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_terms_of_service_agreement_state_rest_unset_required_fields(): - transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.TermsOfServiceAgreementStateServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.get_terms_of_service_agreement_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + unset_fields = ( + transport.get_terms_of_service_agreement_state._get_unset_required_fields({}) + ) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_terms_of_service_agreement_state_rest_flattened(): @@ -1516,16 +2120,18 @@ def test_get_terms_of_service_agreement_state_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 = termsofserviceagreementstate.TermsOfServiceAgreementState() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/termsOfServiceAgreementStates/sample2'} + sample_request = { + "name": "accounts/sample1/termsOfServiceAgreementStates/sample2" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1533,9 +2139,11 @@ def test_get_terms_of_service_agreement_state_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(return_value) + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1545,10 +2153,16 @@ def test_get_terms_of_service_agreement_state_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/termsOfServiceAgreementStates/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/termsOfServiceAgreementStates/*}" + % client.transport._host, + args[1], + ) -def test_get_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): +def test_get_terms_of_service_agreement_state_rest_flattened_error( + transport: str = "rest", +): client = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1559,7 +2173,7 @@ def test_get_terms_of_service_agreement_state_rest_flattened_error(transport: st with pytest.raises(ValueError): client.get_terms_of_service_agreement_state( termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest(), - name='name_value', + name="name_value", ) @@ -1577,12 +2191,19 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_use_cach wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.retrieve_for_application_terms_of_service_agreement_state in client._transport._wrapped_methods + assert ( + client._transport.retrieve_for_application_terms_of_service_agreement_state + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_for_application_terms_of_service_agreement_state] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_for_application_terms_of_service_agreement_state + ] = mock_rpc request = {} client.retrieve_for_application_terms_of_service_agreement_state(request) @@ -1597,55 +2218,64 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_use_cach assert mock_rpc.call_count == 2 -def test_retrieve_for_application_terms_of_service_agreement_state_rest_required_fields(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): +def test_retrieve_for_application_terms_of_service_agreement_state_rest_required_fields( + request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, +): transport_class = transports.TermsOfServiceAgreementStateServiceRestTransport 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()).retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_for_application_terms_of_service_agreement_state._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()).retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_for_application_terms_of_service_agreement_state._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 = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() # Mock the http request 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 @@ -1653,27 +2283,33 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_required response_value.status_code = 200 # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(return_value) + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.retrieve_for_application_terms_of_service_agreement_state(request) + response = client.retrieve_for_application_terms_of_service_agreement_state( + 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_retrieve_for_application_terms_of_service_agreement_state_rest_unset_required_fields(): - transport = transports.TermsOfServiceAgreementStateServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.TermsOfServiceAgreementStateServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) + unset_fields = transport.retrieve_for_application_terms_of_service_agreement_state._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(()) & set(("parent",))) def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened(): @@ -1683,16 +2319,16 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattene ) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -1700,9 +2336,11 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattene response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(return_value) + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1712,10 +2350,16 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattene # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/termsOfServiceAgreementStates:retrieveForApplication" + % client.transport._host, + args[1], + ) -def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened_error(transport: str = 'rest'): +def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattened_error( + transport: str = "rest", +): client = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1726,7 +2370,7 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_flattene with pytest.raises(ValueError): client.retrieve_for_application_terms_of_service_agreement_state( termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1768,8 +2412,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = TermsOfServiceAgreementStateServiceClient( - 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. @@ -1791,6 +2434,7 @@ def test_transport_instance(): client = TermsOfServiceAgreementStateServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TermsOfServiceAgreementStateServiceGrpcTransport( @@ -1805,18 +2449,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.TermsOfServiceAgreementStateServiceGrpcTransport, - transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, - transports.TermsOfServiceAgreementStateServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + transports.TermsOfServiceAgreementStateServiceRestTransport, + ], +) 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 = TermsOfServiceAgreementStateServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -1826,8 +2475,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -1842,15 +2490,17 @@ def test_get_terms_of_service_agreement_state_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() client.get_terms_of_service_agreement_state(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + request_msg = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + ) assert args[0] == request_msg @@ -1865,30 +2515,34 @@ def test_retrieve_for_application_terms_of_service_agreement_state_empty_call_gr # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: call.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() client.retrieve_for_application_terms_of_service_agreement_state(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request_msg = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) assert args[0] == request_msg def test_transport_kind_grpc_asyncio(): - transport = TermsOfServiceAgreementStateServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) + transport = TermsOfServiceAgreementStateServiceAsyncClient.get_transport_class( + "grpc_asyncio" + )(credentials=async_anonymous_credentials()) assert transport.kind == "grpc_asyncio" def test_initialize_client_w_grpc_asyncio(): client = TermsOfServiceAgreementStateServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -1904,20 +2558,24 @@ async def test_get_terms_of_service_agreement_state_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState( + name="name_value", + region_code="region_code_value", + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + ) await client.get_terms_of_service_agreement_state(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + request_msg = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + ) assert args[0] == request_msg @@ -1933,20 +2591,29 @@ async def test_retrieve_for_application_terms_of_service_agreement_state_empty_c # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - )) - await client.retrieve_for_application_terms_of_service_agreement_state(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofserviceagreementstate.TermsOfServiceAgreementState( + name="name_value", + region_code="region_code_value", + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + ) + ) + await client.retrieve_for_application_terms_of_service_agreement_state( + request=None + ) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request_msg = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) assert args[0] == request_msg @@ -1958,20 +2625,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest): +def test_get_terms_of_service_agreement_state_rest_bad_request( + request_type=termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, +): client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/sample2'} + request_init = {"name": "accounts/sample1/termsOfServiceAgreementStates/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() @@ -1980,27 +2650,29 @@ def test_get_terms_of_service_agreement_state_rest_bad_request(request_type=term client.get_terms_of_service_agreement_state(request) -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest, + dict, + ], +) def test_get_terms_of_service_agreement_state_rest_call_success(request_type): client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/termsOfServiceAgreementStates/sample2'} + request_init = {"name": "accounts/sample1/termsOfServiceAgreementStates/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 = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + name="name_value", + region_code="region_code_value", + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, ) # Wrap the value into a proper Response obj @@ -2008,37 +2680,59 @@ def test_get_terms_of_service_agreement_state_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(return_value) + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_terms_of_service_agreement_state(request) # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert isinstance( + response, termsofserviceagreementstate.TermsOfServiceAgreementState + ) + assert response.name == "name_value" + assert response.region_code == "region_code_value" + assert ( + response.terms_of_service_kind + == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_terms_of_service_agreement_state_rest_interceptors(null_interceptor): transport = transports.TermsOfServiceAgreementStateServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), + ) client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state") as post, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_get_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_get_terms_of_service_agreement_state") 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.TermsOfServiceAgreementStateServiceRestInterceptor, + "post_get_terms_of_service_agreement_state", + ) as post, mock.patch.object( + transports.TermsOfServiceAgreementStateServiceRestInterceptor, + "post_get_terms_of_service_agreement_state_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.TermsOfServiceAgreementStateServiceRestInterceptor, + "pre_get_terms_of_service_agreement_state", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest()) + pb_message = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest.pb( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + ) + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2049,39 +2743,55 @@ def test_get_terms_of_service_agreement_state_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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) + return_value = ( + termsofserviceagreementstate.TermsOfServiceAgreementState.to_json( + termsofserviceagreementstate.TermsOfServiceAgreementState() + ) + ) req.return_value.content = return_value request = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata + post_with_metadata.return_value = ( + termsofserviceagreementstate.TermsOfServiceAgreementState(), + metadata, + ) - client.get_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_terms_of_service_agreement_state( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_request(request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest): +def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_request( + request_type=termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, +): client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -2090,27 +2800,31 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_bad_requ client.retrieve_for_application_terms_of_service_agreement_state(request) -@pytest.mark.parametrize("request_type", [ - termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, - dict, -]) -def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_success(request_type): +@pytest.mark.parametrize( + "request_type", + [ + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest, + dict, + ], +) +def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_success( + request_type, +): client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = termsofserviceagreementstate.TermsOfServiceAgreementState( - name='name_value', - region_code='region_code_value', - terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + name="name_value", + region_code="region_code_value", + terms_of_service_kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, ) # Wrap the value into a proper Response obj @@ -2118,37 +2832,61 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_call_suc response_value.status_code = 200 # Convert return value to protobuf type - return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb(return_value) + return_value = termsofserviceagreementstate.TermsOfServiceAgreementState.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.retrieve_for_application_terms_of_service_agreement_state(request) + response = client.retrieve_for_application_terms_of_service_agreement_state( + request + ) # Establish that the response is the type that we expect. - assert isinstance(response, termsofserviceagreementstate.TermsOfServiceAgreementState) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' - assert response.terms_of_service_kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + assert isinstance( + response, termsofserviceagreementstate.TermsOfServiceAgreementState + ) + assert response.name == "name_value" + assert response.region_code == "region_code_value" + assert ( + response.terms_of_service_kind + == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_retrieve_for_application_terms_of_service_agreement_state_rest_interceptors(null_interceptor): +def test_retrieve_for_application_terms_of_service_agreement_state_rest_interceptors( + null_interceptor, +): transport = transports.TermsOfServiceAgreementStateServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.TermsOfServiceAgreementStateServiceRestInterceptor(), + ) client = TermsOfServiceAgreementStateServiceClient(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.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state") as post, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "post_retrieve_for_application_terms_of_service_agreement_state_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceAgreementStateServiceRestInterceptor, "pre_retrieve_for_application_terms_of_service_agreement_state") 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.TermsOfServiceAgreementStateServiceRestInterceptor, + "post_retrieve_for_application_terms_of_service_agreement_state", + ) as post, mock.patch.object( + transports.TermsOfServiceAgreementStateServiceRestInterceptor, + "post_retrieve_for_application_terms_of_service_agreement_state_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.TermsOfServiceAgreementStateServiceRestInterceptor, + "pre_retrieve_for_application_terms_of_service_agreement_state", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.pb(termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest()) + pb_message = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest.pb( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2159,28 +2897,43 @@ def test_retrieve_for_application_terms_of_service_agreement_state_rest_intercep 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 = termsofserviceagreementstate.TermsOfServiceAgreementState.to_json(termsofserviceagreementstate.TermsOfServiceAgreementState()) + return_value = ( + termsofserviceagreementstate.TermsOfServiceAgreementState.to_json( + termsofserviceagreementstate.TermsOfServiceAgreementState() + ) + ) req.return_value.content = return_value - request = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() - metadata =[ + request = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState() - post_with_metadata.return_value = termsofserviceagreementstate.TermsOfServiceAgreementState(), metadata + post_with_metadata.return_value = ( + termsofserviceagreementstate.TermsOfServiceAgreementState(), + metadata, + ) - client.retrieve_for_application_terms_of_service_agreement_state(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.retrieve_for_application_terms_of_service_agreement_state( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = TermsOfServiceAgreementStateServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2195,14 +2948,16 @@ def test_get_terms_of_service_agreement_state_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service_agreement_state), - '__call__') as call: + type(client.transport.get_terms_of_service_agreement_state), "__call__" + ) as call: client.get_terms_of_service_agreement_state(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + request_msg = ( + termsofserviceagreementstate.GetTermsOfServiceAgreementStateRequest() + ) assert args[0] == request_msg @@ -2217,14 +2972,19 @@ def test_retrieve_for_application_terms_of_service_agreement_state_empty_call_re # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.retrieve_for_application_terms_of_service_agreement_state), - '__call__') as call: + type( + client.transport.retrieve_for_application_terms_of_service_agreement_state + ), + "__call__", + ) as call: client.retrieve_for_application_terms_of_service_agreement_state(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + request_msg = ( + termsofserviceagreementstate.RetrieveForApplicationTermsOfServiceAgreementStateRequest() + ) assert args[0] == request_msg @@ -2239,18 +2999,21 @@ def test_transport_grpc_default(): transports.TermsOfServiceAgreementStateServiceGrpcTransport, ) + def test_terms_of_service_agreement_state_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TermsOfServiceAgreementStateServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_terms_of_service_agreement_state_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.TermsOfServiceAgreementStateServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2259,8 +3022,8 @@ def test_terms_of_service_agreement_state_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_terms_of_service_agreement_state', - 'retrieve_for_application_terms_of_service_agreement_state', + "get_terms_of_service_agreement_state", + "retrieve_for_application_terms_of_service_agreement_state", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2271,7 +3034,7 @@ def test_terms_of_service_agreement_state_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2280,25 +3043,30 @@ def test_terms_of_service_agreement_state_service_base_transport(): def test_terms_of_service_agreement_state_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_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._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_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TermsOfServiceAgreementStateServiceTransport( 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_terms_of_service_agreement_state_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_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.terms_of_service_agreement_state_service.transports.TermsOfServiceAgreementStateServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TermsOfServiceAgreementStateServiceTransport() @@ -2307,14 +3075,12 @@ def test_terms_of_service_agreement_state_service_base_transport_with_adc(): def test_terms_of_service_agreement_state_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) TermsOfServiceAgreementStateServiceClient() 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, ) @@ -2329,12 +3095,12 @@ def test_terms_of_service_agreement_state_service_auth_adc(): def test_terms_of_service_agreement_state_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", ) @@ -2347,49 +3113,53 @@ def test_terms_of_service_agreement_state_service_transport_auth_adc(transport_c transports.TermsOfServiceAgreementStateServiceRestTransport, ], ) -def test_terms_of_service_agreement_state_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'] +def test_terms_of_service_agreement_state_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: + 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.TermsOfServiceAgreementStateServiceGrpcTransport, grpc_helpers), - (transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, grpc_helpers_async) + ( + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + grpc_helpers_async, + ), ], ) -def test_terms_of_service_agreement_state_service_transport_create_channel(transport_class, grpc_helpers): +def test_terms_of_service_agreement_state_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, @@ -2400,9 +3170,15 @@ def test_terms_of_service_agreement_state_service_transport_create_channel(trans ) -@pytest.mark.parametrize("transport_class", [transports.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + ], +) def test_terms_of_service_agreement_state_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2412,7 +3188,7 @@ def test_terms_of_service_agreement_state_service_grpc_transport_client_cert_sou 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", @@ -2433,62 +3209,80 @@ def test_terms_of_service_agreement_state_service_grpc_transport_client_cert_sou 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_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceRestTransport ( - 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.TermsOfServiceAgreementStateServiceRestTransport( + 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_terms_of_service_agreement_state_service_host_no_port(transport_name): client = TermsOfServiceAgreementStateServiceClient( 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_terms_of_service_agreement_state_service_host_with_port(transport_name): client = TermsOfServiceAgreementStateServiceClient( 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", -]) -def test_terms_of_service_agreement_state_service_client_transport_session_collision(transport_name): + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_terms_of_service_agreement_state_service_client_transport_session_collision( + transport_name, +): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() client1 = TermsOfServiceAgreementStateServiceClient( @@ -2502,11 +3296,17 @@ def test_terms_of_service_agreement_state_service_client_transport_session_colli session1 = client1.transport.get_terms_of_service_agreement_state._session session2 = client2.transport.get_terms_of_service_agreement_state._session assert session1 != session2 - session1 = client1.transport.retrieve_for_application_terms_of_service_agreement_state._session - session2 = client2.transport.retrieve_for_application_terms_of_service_agreement_state._session + session1 = ( + client1.transport.retrieve_for_application_terms_of_service_agreement_state._session + ) + session2 = ( + client2.transport.retrieve_for_application_terms_of_service_agreement_state._session + ) assert session1 != session2 + + def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport( @@ -2519,7 +3319,7 @@ def test_terms_of_service_agreement_state_service_grpc_transport_channel(): def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport( @@ -2533,12 +3333,22 @@ def test_terms_of_service_agreement_state_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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + ], +) def test_terms_of_service_agreement_state_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 @@ -2547,7 +3357,7 @@ def test_terms_of_service_agreement_state_service_transport_channel_mtls_with_cl 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", @@ -2577,9 +3387,15 @@ def test_terms_of_service_agreement_state_service_transport_channel_mtls_with_cl # 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.TermsOfServiceAgreementStateServiceGrpcTransport, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + ], +) def test_terms_of_service_agreement_state_service_transport_channel_mtls_with_adc( - transport_class + transport_class, ): mock_ssl_cred = mock.Mock() with mock.patch.multiple( @@ -2587,7 +3403,9 @@ def test_terms_of_service_agreement_state_service_transport_channel_mtls_with_ad __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() @@ -2617,7 +3435,9 @@ def test_terms_of_service_agreement_state_service_transport_channel_mtls_with_ad def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = TermsOfServiceAgreementStateServiceClient.account_path(account) assert expected == actual @@ -2632,9 +3452,12 @@ def test_parse_account_path(): actual = TermsOfServiceAgreementStateServiceClient.parse_account_path(path) assert expected == actual + def test_terms_of_service_path(): version = "whelk" - expected = "termsOfService/{version}".format(version=version, ) + expected = "termsOfService/{version}".format( + version=version, + ) actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_path(version) assert expected == actual @@ -2649,11 +3472,19 @@ def test_parse_terms_of_service_path(): actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_path(path) assert expected == actual + def test_terms_of_service_agreement_state_path(): account = "oyster" identifier = "nudibranch" - expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) - actual = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(account, identifier) + expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format( + account=account, + identifier=identifier, + ) + actual = ( + TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path( + account, identifier + ) + ) assert expected == actual @@ -2662,16 +3493,27 @@ def test_parse_terms_of_service_agreement_state_path(): "account": "cuttlefish", "identifier": "mussel", } - path = TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path(**expected) + path = ( + TermsOfServiceAgreementStateServiceClient.terms_of_service_agreement_state_path( + **expected + ) + ) # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path(path) + actual = TermsOfServiceAgreementStateServiceClient.parse_terms_of_service_agreement_state_path( + path + ) assert expected == actual + def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(billing_account) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = TermsOfServiceAgreementStateServiceClient.common_billing_account_path( + billing_account + ) assert expected == actual @@ -2679,15 +3521,24 @@ def test_parse_common_billing_account_path(): expected = { "billing_account": "nautilus", } - path = TermsOfServiceAgreementStateServiceClient.common_billing_account_path(**expected) + path = TermsOfServiceAgreementStateServiceClient.common_billing_account_path( + **expected + ) # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path(path) + actual = ( + TermsOfServiceAgreementStateServiceClient.parse_common_billing_account_path( + path + ) + ) assert expected == actual + def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = TermsOfServiceAgreementStateServiceClient.common_folder_path(folder) assert expected == actual @@ -2702,10 +3553,15 @@ def test_parse_common_folder_path(): actual = TermsOfServiceAgreementStateServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = TermsOfServiceAgreementStateServiceClient.common_organization_path(organization) + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = TermsOfServiceAgreementStateServiceClient.common_organization_path( + organization + ) assert expected == actual @@ -2713,15 +3569,22 @@ def test_parse_common_organization_path(): expected = { "organization": "clam", } - path = TermsOfServiceAgreementStateServiceClient.common_organization_path(**expected) + path = TermsOfServiceAgreementStateServiceClient.common_organization_path( + **expected + ) # Check that the path construction is reversible. - actual = TermsOfServiceAgreementStateServiceClient.parse_common_organization_path(path) + actual = TermsOfServiceAgreementStateServiceClient.parse_common_organization_path( + path + ) assert expected == actual + def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = TermsOfServiceAgreementStateServiceClient.common_project_path(project) assert expected == actual @@ -2736,11 +3599,17 @@ def test_parse_common_project_path(): actual = TermsOfServiceAgreementStateServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = TermsOfServiceAgreementStateServiceClient.common_location_path(project, location) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = TermsOfServiceAgreementStateServiceClient.common_location_path( + project, location + ) assert expected == actual @@ -2759,15 +3628,23 @@ 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.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.TermsOfServiceAgreementStateServiceTransport, + "_prep_wrapped_messages", + ) as prep: client = TermsOfServiceAgreementStateServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.TermsOfServiceAgreementStateServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = TermsOfServiceAgreementStateServiceClient.get_transport_class() + with mock.patch.object( + transports.TermsOfServiceAgreementStateServiceTransport, + "_prep_wrapped_messages", + ) as prep: + transport_class = ( + TermsOfServiceAgreementStateServiceClient.get_transport_class() + ) transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, @@ -2777,10 +3654,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = TermsOfServiceAgreementStateServiceClient( - 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() @@ -2789,10 +3667,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = TermsOfServiceAgreementStateServiceAsyncClient( - 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() @@ -2800,10 +3679,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = TermsOfServiceAgreementStateServiceClient( - 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() @@ -2811,13 +3691,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = TermsOfServiceAgreementStateServiceClient( - 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: @@ -2826,10 +3705,20 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (TermsOfServiceAgreementStateServiceClient, transports.TermsOfServiceAgreementStateServiceGrpcTransport), - (TermsOfServiceAgreementStateServiceAsyncClient, transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + ( + TermsOfServiceAgreementStateServiceClient, + transports.TermsOfServiceAgreementStateServiceGrpcTransport, + ), + ( + TermsOfServiceAgreementStateServiceAsyncClient, + transports.TermsOfServiceAgreementStateServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -2844,7 +3733,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py similarity index 67% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py index 6106a91fa450..ba5cbf44c877 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_terms_of_service_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,46 +22,46 @@ 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.shopping.merchant_accounts_v1.services.terms_of_service_service import TermsOfServiceServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_service import TermsOfServiceServiceClient -from google.shopping.merchant_accounts_v1.services.terms_of_service_service import transports -from google.shopping.merchant_accounts_v1.types import termsofservice -from google.shopping.merchant_accounts_v1.types import termsofserviceagreementstate -from google.shopping.merchant_accounts_v1.types import termsofservicekind -import google.auth - +from google.shopping.merchant_accounts_v1.services.terms_of_service_service import ( + TermsOfServiceServiceAsyncClient, + TermsOfServiceServiceClient, + transports, +) +from google.shopping.merchant_accounts_v1.types import ( + termsofservice, + termsofserviceagreementstate, + termsofservicekind, +) CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -75,9 +76,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(): @@ -85,17 +88,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(): @@ -106,101 +119,245 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert TermsOfServiceServiceClient._get_default_mtls_endpoint(None) is None - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert TermsOfServiceServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + TermsOfServiceServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + TermsOfServiceServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TermsOfServiceServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + TermsOfServiceServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + def test__read_environment_variables(): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + assert TermsOfServiceServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (True, "auto", None) + assert TermsOfServiceServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + assert TermsOfServiceServiceClient._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: TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._read_environment_variables() == (False, "never", None) + assert TermsOfServiceServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "always", None) + assert TermsOfServiceServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", None) + assert TermsOfServiceServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, False) is None - assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + TermsOfServiceServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + TermsOfServiceServiceClient._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 ( + TermsOfServiceServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert TermsOfServiceServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +@mock.patch.object( + TermsOfServiceServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceClient), +) +@mock.patch.object( + TermsOfServiceServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert TermsOfServiceServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert TermsOfServiceServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == TermsOfServiceServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + TermsOfServiceServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - TermsOfServiceServiceClient._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." + TermsOfServiceServiceClient._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 TermsOfServiceServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert TermsOfServiceServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert TermsOfServiceServiceClient._get_universe_domain(None, None) == TermsOfServiceServiceClient._DEFAULT_UNIVERSE + assert ( + TermsOfServiceServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + TermsOfServiceServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + TermsOfServiceServiceClient._get_universe_domain(None, None) + == TermsOfServiceServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: TermsOfServiceServiceClient._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) @@ -216,7 +373,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") @@ -229,14 +387,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", [ - (TermsOfServiceServiceClient, "grpc"), - (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceServiceClient, "rest"), -]) -def test_terms_of_service_service_client_from_service_account_info(client_class, transport_name): + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (TermsOfServiceServiceClient, "grpc"), + (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceServiceClient, "rest"), + ], +) +def test_terms_of_service_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) @@ -244,52 +410,70 @@ def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, "grpc"), - (transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.TermsOfServiceServiceRestTransport, "rest"), -]) -def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, "grpc"), + (transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.TermsOfServiceServiceRestTransport, "rest"), + ], +) +def test_terms_of_service_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", [ - (TermsOfServiceServiceClient, "grpc"), - (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), - (TermsOfServiceServiceClient, "rest"), -]) -def test_terms_of_service_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (TermsOfServiceServiceClient, "grpc"), + (TermsOfServiceServiceAsyncClient, "grpc_asyncio"), + (TermsOfServiceServiceClient, "rest"), + ], +) +def test_terms_of_service_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" ) @@ -305,30 +489,53 @@ def test_terms_of_service_service_client_get_transport_class(): assert transport == transports.TermsOfServiceServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), -]) -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) -def test_terms_of_service_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceGrpcTransport, + "grpc", + ), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + TermsOfServiceServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceClient), +) +@mock.patch.object( + TermsOfServiceServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceAsyncClient), +) +def test_terms_of_service_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(TermsOfServiceServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(TermsOfServiceServiceClient, "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(TermsOfServiceServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(TermsOfServiceServiceClient, "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( @@ -346,13 +553,15 @@ def test_terms_of_service_service_client_client_options(client_class, transport_ # 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, @@ -364,7 +573,7 @@ def test_terms_of_service_service_client_client_options(client_class, transport_ # 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( @@ -384,23 +593,33 @@ def test_terms_of_service_service_client_client_options(client_class, transport_ 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", @@ -409,48 +628,102 @@ def test_terms_of_service_service_client_client_options(client_class, transport_ 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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "true"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", "false"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "true"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceGrpcTransport, + "grpc", + "true", + ), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceGrpcTransport, + "grpc", + "false", + ), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceRestTransport, + "rest", + "true", + ), + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + TermsOfServiceServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceClient), +) +@mock.patch.object( + TermsOfServiceServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_terms_of_service_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_terms_of_service_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 @@ -469,12 +742,22 @@ def test_terms_of_service_service_client_mtls_env_auto(client_class, transport_c # 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 @@ -495,15 +778,22 @@ def test_terms_of_service_service_client_mtls_env_auto(client_class, transport_c ) # 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, @@ -513,19 +803,33 @@ def test_terms_of_service_service_client_mtls_env_auto(client_class, transport_c ) -@pytest.mark.parametrize("client_class", [ - TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(TermsOfServiceServiceAsyncClient)) -def test_terms_of_service_service_client_get_mtls_endpoint_and_cert_source(client_class): +@pytest.mark.parametrize( + "client_class", [TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient] +) +@mock.patch.object( + TermsOfServiceServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TermsOfServiceServiceClient), +) +@mock.patch.object( + TermsOfServiceServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(TermsOfServiceServiceAsyncClient), +) +def test_terms_of_service_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 @@ -533,8 +837,12 @@ def test_terms_of_service_service_client_get_mtls_endpoint_and_cert_source(clien 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 @@ -552,16 +860,28 @@ def test_terms_of_service_service_client_get_mtls_endpoint_and_cert_source(clien # 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 @@ -571,34 +891,62 @@ def test_terms_of_service_service_client_get_mtls_endpoint_and_cert_source(clien 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", [ - TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient -]) -@mock.patch.object(TermsOfServiceServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceClient)) -@mock.patch.object(TermsOfServiceServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(TermsOfServiceServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [TermsOfServiceServiceClient, TermsOfServiceServiceAsyncClient] +) +@mock.patch.object( + TermsOfServiceServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceClient), +) +@mock.patch.object( + TermsOfServiceServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(TermsOfServiceServiceAsyncClient), +) def test_terms_of_service_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = TermsOfServiceServiceClient._DEFAULT_UNIVERSE - default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = TermsOfServiceServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = TermsOfServiceServiceClient._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", @@ -621,11 +969,19 @@ def test_terms_of_service_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. @@ -633,27 +989,48 @@ def test_terms_of_service_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", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc"), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest"), -]) -def test_terms_of_service_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceGrpcTransport, + "grpc", + ), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceRestTransport, + "rest", + ), + ], +) +def test_terms_of_service_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, @@ -662,24 +1039,45 @@ def test_terms_of_service_service_client_client_options_scopes(client_class, tra api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceRestTransport, "rest", None), -]) -def test_terms_of_service_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", + [ + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceRestTransport, + "rest", + None, + ), + ], +) +def test_terms_of_service_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, @@ -688,11 +1086,14 @@ def test_terms_of_service_service_client_client_options_credentials_file(client_ api_audience=None, ) + def test_terms_of_service_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = TermsOfServiceServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -707,23 +1108,38 @@ def test_terms_of_service_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport, "grpc", grpc_helpers), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_terms_of_service_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", + [ + ( + TermsOfServiceServiceClient, + transports.TermsOfServiceServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_terms_of_service_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, @@ -750,9 +1166,7 @@ def test_terms_of_service_service_client_create_channel_credentials_file(client_ 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, @@ -763,11 +1177,14 @@ def test_terms_of_service_service_client_create_channel_credentials_file(client_ ) -@pytest.mark.parametrize("request_type", [ - termsofservice.GetTermsOfServiceRequest, - dict, -]) -def test_get_terms_of_service(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + termsofservice.GetTermsOfServiceRequest, + dict, + ], +) +def test_get_terms_of_service(request_type, transport: str = "grpc"): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -779,14 +1196,14 @@ def test_get_terms_of_service(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', + file_uri="file_uri_value", external=True, ) response = client.get_terms_of_service(request) @@ -799,10 +1216,10 @@ def test_get_terms_of_service(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' + assert response.file_uri == "file_uri_value" assert response.external is True @@ -811,28 +1228,31 @@ def test_get_terms_of_service_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = TermsOfServiceServiceClient( 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 = termsofservice.GetTermsOfServiceRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.get_terms_of_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_terms_of_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == termsofservice.GetTermsOfServiceRequest( - name='name_value', + name="name_value", ) + def test_get_terms_of_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -847,12 +1267,18 @@ def test_get_terms_of_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_terms_of_service in client._transport._wrapped_methods + assert ( + client._transport.get_terms_of_service in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_terms_of_service + ] = mock_rpc request = {} client.get_terms_of_service(request) @@ -865,8 +1291,11 @@ def test_get_terms_of_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_terms_of_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_terms_of_service_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: @@ -880,12 +1309,17 @@ async def test_get_terms_of_service_async_use_cached_wrapped_rpc(transport: str wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_terms_of_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_terms_of_service + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_terms_of_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_terms_of_service + ] = mock_rpc request = {} await client.get_terms_of_service(request) @@ -899,8 +1333,12 @@ async def test_get_terms_of_service_async_use_cached_wrapped_rpc(transport: str assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.GetTermsOfServiceRequest): +async def test_get_terms_of_service_async( + transport: str = "grpc_asyncio", + request_type=termsofservice.GetTermsOfServiceRequest, +): client = TermsOfServiceServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -912,16 +1350,18 @@ async def test_get_terms_of_service_async(transport: str = 'grpc_asyncio', reque # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.TermsOfService( + name="name_value", + region_code="region_code_value", + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri="file_uri_value", + external=True, + ) + ) response = await client.get_terms_of_service(request) # Establish that the underlying gRPC stub method was called. @@ -932,10 +1372,10 @@ async def test_get_terms_of_service_async(transport: str = 'grpc_asyncio', reque # Establish that the response is the type that we expect. assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' + assert response.file_uri == "file_uri_value" assert response.external is True @@ -943,6 +1383,7 @@ async def test_get_terms_of_service_async(transport: str = 'grpc_asyncio', reque async def test_get_terms_of_service_async_from_dict(): await test_get_terms_of_service_async(request_type=dict) + def test_get_terms_of_service_field_headers(): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -952,12 +1393,12 @@ def test_get_terms_of_service_field_headers(): # a field header. Set these to a non-empty value. request = termsofservice.GetTermsOfServiceRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: call.return_value = termsofservice.TermsOfService() client.get_terms_of_service(request) @@ -969,9 +1410,9 @@ def test_get_terms_of_service_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 @@ -984,13 +1425,15 @@ async def test_get_terms_of_service_field_headers_async(): # a field header. Set these to a non-empty value. request = termsofservice.GetTermsOfServiceRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) + type(client.transport.get_terms_of_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.TermsOfService() + ) await client.get_terms_of_service(request) # Establish that the underlying gRPC stub method was called. @@ -1001,9 +1444,9 @@ async def test_get_terms_of_service_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_terms_of_service_flattened(): @@ -1013,14 +1456,14 @@ def test_get_terms_of_service_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofservice.TermsOfService() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_terms_of_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1028,7 +1471,7 @@ def test_get_terms_of_service_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 @@ -1042,9 +1485,10 @@ def test_get_terms_of_service_flattened_error(): with pytest.raises(ValueError): client.get_terms_of_service( termsofservice.GetTermsOfServiceRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_terms_of_service_flattened_async(): client = TermsOfServiceServiceAsyncClient( @@ -1053,16 +1497,18 @@ async def test_get_terms_of_service_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofservice.TermsOfService() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.TermsOfService() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_terms_of_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1070,9 +1516,10 @@ async def test_get_terms_of_service_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_terms_of_service_flattened_error_async(): client = TermsOfServiceServiceAsyncClient( @@ -1084,15 +1531,18 @@ async def test_get_terms_of_service_flattened_error_async(): with pytest.raises(ValueError): await client.get_terms_of_service( termsofservice.GetTermsOfServiceRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - termsofservice.RetrieveLatestTermsOfServiceRequest, - dict, -]) -def test_retrieve_latest_terms_of_service(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + termsofservice.RetrieveLatestTermsOfServiceRequest, + dict, + ], +) +def test_retrieve_latest_terms_of_service(request_type, transport: str = "grpc"): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1104,14 +1554,14 @@ def test_retrieve_latest_terms_of_service(request_type, transport: str = 'grpc') # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: + type(client.transport.retrieve_latest_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', + name="name_value", + region_code="region_code_value", kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', + file_uri="file_uri_value", external=True, ) response = client.retrieve_latest_terms_of_service(request) @@ -1124,10 +1574,10 @@ def test_retrieve_latest_terms_of_service(request_type, transport: str = 'grpc') # Establish that the response is the type that we expect. assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' + assert response.file_uri == "file_uri_value" assert response.external is True @@ -1136,28 +1586,31 @@ def test_retrieve_latest_terms_of_service_non_empty_request_with_auto_populated_ # automatically populated, according to AIP-4235, with non-empty requests. client = TermsOfServiceServiceClient( 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 = termsofservice.RetrieveLatestTermsOfServiceRequest( - region_code='region_code_value', + region_code="region_code_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.retrieve_latest_terms_of_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.retrieve_latest_terms_of_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == termsofservice.RetrieveLatestTermsOfServiceRequest( - region_code='region_code_value', + region_code="region_code_value", ) + def test_retrieve_latest_terms_of_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1172,12 +1625,19 @@ def test_retrieve_latest_terms_of_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.retrieve_latest_terms_of_service in client._transport._wrapped_methods + assert ( + client._transport.retrieve_latest_terms_of_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_latest_terms_of_service + ] = mock_rpc request = {} client.retrieve_latest_terms_of_service(request) @@ -1190,8 +1650,11 @@ def test_retrieve_latest_terms_of_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_retrieve_latest_terms_of_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_retrieve_latest_terms_of_service_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: @@ -1205,12 +1668,17 @@ async def test_retrieve_latest_terms_of_service_async_use_cached_wrapped_rpc(tra wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.retrieve_latest_terms_of_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.retrieve_latest_terms_of_service + 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.retrieve_latest_terms_of_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_latest_terms_of_service + ] = mock_rpc request = {} await client.retrieve_latest_terms_of_service(request) @@ -1224,8 +1692,12 @@ async def test_retrieve_latest_terms_of_service_async_use_cached_wrapped_rpc(tra assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_retrieve_latest_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): +async def test_retrieve_latest_terms_of_service_async( + transport: str = "grpc_asyncio", + request_type=termsofservice.RetrieveLatestTermsOfServiceRequest, +): client = TermsOfServiceServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1237,16 +1709,18 @@ async def test_retrieve_latest_terms_of_service_async(transport: str = 'grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: + type(client.transport.retrieve_latest_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.TermsOfService( + name="name_value", + region_code="region_code_value", + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri="file_uri_value", + external=True, + ) + ) response = await client.retrieve_latest_terms_of_service(request) # Establish that the underlying gRPC stub method was called. @@ -1257,10 +1731,10 @@ async def test_retrieve_latest_terms_of_service_async(transport: str = 'grpc_asy # Establish that the response is the type that we expect. assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' + assert response.file_uri == "file_uri_value" assert response.external is True @@ -1269,11 +1743,14 @@ async def test_retrieve_latest_terms_of_service_async_from_dict(): await test_retrieve_latest_terms_of_service_async(request_type=dict) -@pytest.mark.parametrize("request_type", [ - termsofservice.AcceptTermsOfServiceRequest, - dict, -]) -def test_accept_terms_of_service(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + termsofservice.AcceptTermsOfServiceRequest, + dict, + ], +) +def test_accept_terms_of_service(request_type, transport: str = "grpc"): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1285,11 +1762,10 @@ def test_accept_terms_of_service(request_type, transport: str = 'grpc'): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = termsofservice.AcceptTermsOfServiceResponse( - ) + call.return_value = termsofservice.AcceptTermsOfServiceResponse() response = client.accept_terms_of_service(request) # Establish that the underlying gRPC stub method was called. @@ -1307,32 +1783,35 @@ def test_accept_terms_of_service_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = TermsOfServiceServiceClient( 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 = termsofservice.AcceptTermsOfServiceRequest( - name='name_value', - account='account_value', - region_code='region_code_value', + name="name_value", + account="account_value", + region_code="region_code_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + type(client.transport.accept_terms_of_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.accept_terms_of_service(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == termsofservice.AcceptTermsOfServiceRequest( - name='name_value', - account='account_value', - region_code='region_code_value', + name="name_value", + account="account_value", + region_code="region_code_value", ) + def test_accept_terms_of_service_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1347,12 +1826,19 @@ def test_accept_terms_of_service_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.accept_terms_of_service in client._transport._wrapped_methods + assert ( + client._transport.accept_terms_of_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.accept_terms_of_service + ] = mock_rpc request = {} client.accept_terms_of_service(request) @@ -1365,8 +1851,11 @@ def test_accept_terms_of_service_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_accept_terms_of_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_accept_terms_of_service_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: @@ -1380,12 +1869,17 @@ async def test_accept_terms_of_service_async_use_cached_wrapped_rpc(transport: s wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.accept_terms_of_service in client._client._transport._wrapped_methods + assert ( + client._client._transport.accept_terms_of_service + 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.accept_terms_of_service] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.accept_terms_of_service + ] = mock_rpc request = {} await client.accept_terms_of_service(request) @@ -1399,8 +1893,12 @@ async def test_accept_terms_of_service_async_use_cached_wrapped_rpc(transport: s assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_accept_terms_of_service_async(transport: str = 'grpc_asyncio', request_type=termsofservice.AcceptTermsOfServiceRequest): +async def test_accept_terms_of_service_async( + transport: str = "grpc_asyncio", + request_type=termsofservice.AcceptTermsOfServiceRequest, +): client = TermsOfServiceServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1412,11 +1910,12 @@ async def test_accept_terms_of_service_async(transport: str = 'grpc_asyncio', re # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.AcceptTermsOfServiceResponse() + ) response = await client.accept_terms_of_service(request) # Establish that the underlying gRPC stub method was called. @@ -1433,6 +1932,7 @@ async def test_accept_terms_of_service_async(transport: str = 'grpc_asyncio', re async def test_accept_terms_of_service_async_from_dict(): await test_accept_terms_of_service_async(request_type=dict) + def test_accept_terms_of_service_field_headers(): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1442,12 +1942,12 @@ def test_accept_terms_of_service_field_headers(): # a field header. Set these to a non-empty value. request = termsofservice.AcceptTermsOfServiceRequest() - 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.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: call.return_value = termsofservice.AcceptTermsOfServiceResponse() client.accept_terms_of_service(request) @@ -1459,9 +1959,9 @@ def test_accept_terms_of_service_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 @@ -1474,13 +1974,15 @@ async def test_accept_terms_of_service_field_headers_async(): # a field header. Set these to a non-empty value. request = termsofservice.AcceptTermsOfServiceRequest() - 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.accept_terms_of_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse()) + type(client.transport.accept_terms_of_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.AcceptTermsOfServiceResponse() + ) await client.accept_terms_of_service(request) # Establish that the underlying gRPC stub method was called. @@ -1491,9 +1993,9 @@ async def test_accept_terms_of_service_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_accept_terms_of_service_flattened(): @@ -1503,14 +2005,14 @@ def test_accept_terms_of_service_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofservice.AcceptTermsOfServiceResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.accept_terms_of_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1518,7 +2020,7 @@ def test_accept_terms_of_service_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 @@ -1532,9 +2034,10 @@ def test_accept_terms_of_service_flattened_error(): with pytest.raises(ValueError): client.accept_terms_of_service( termsofservice.AcceptTermsOfServiceRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_accept_terms_of_service_flattened_async(): client = TermsOfServiceServiceAsyncClient( @@ -1543,16 +2046,18 @@ async def test_accept_terms_of_service_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = termsofservice.AcceptTermsOfServiceResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.AcceptTermsOfServiceResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.accept_terms_of_service( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1560,9 +2065,10 @@ async def test_accept_terms_of_service_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_accept_terms_of_service_flattened_error_async(): client = TermsOfServiceServiceAsyncClient( @@ -1574,7 +2080,7 @@ async def test_accept_terms_of_service_flattened_error_async(): with pytest.raises(ValueError): await client.accept_terms_of_service( termsofservice.AcceptTermsOfServiceRequest(), - name='name_value', + name="name_value", ) @@ -1592,12 +2098,18 @@ def test_get_terms_of_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_terms_of_service in client._transport._wrapped_methods + assert ( + client._transport.get_terms_of_service in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_terms_of_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_terms_of_service + ] = mock_rpc request = {} client.get_terms_of_service(request) @@ -1612,55 +2124,60 @@ def test_get_terms_of_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_get_terms_of_service_rest_required_fields(request_type=termsofservice.GetTermsOfServiceRequest): +def test_get_terms_of_service_rest_required_fields( + request_type=termsofservice.GetTermsOfServiceRequest, +): transport_class = transports.TermsOfServiceServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_terms_of_service._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terms_of_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_terms_of_service._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 = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = termsofservice.TermsOfService() # Mock the http request 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 @@ -1671,24 +2188,24 @@ def test_get_terms_of_service_rest_required_fields(request_type=termsofservice.G return_value = termsofservice.TermsOfService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_terms_of_service(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_terms_of_service_rest_unset_required_fields(): - transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_terms_of_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_terms_of_service_rest_flattened(): @@ -1698,16 +2215,16 @@ def test_get_terms_of_service_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 = termsofservice.TermsOfService() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'termsOfService/sample1'} + sample_request = {"name": "termsOfService/sample1"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -1717,7 +2234,7 @@ def test_get_terms_of_service_rest_flattened(): # Convert return value to protobuf type return_value = termsofservice.TermsOfService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1727,10 +2244,12 @@ def test_get_terms_of_service_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=termsOfService/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=termsOfService/*}" % client.transport._host, args[1] + ) -def test_get_terms_of_service_rest_flattened_error(transport: str = 'rest'): +def test_get_terms_of_service_rest_flattened_error(transport: str = "rest"): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1741,7 +2260,7 @@ def test_get_terms_of_service_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_terms_of_service( termsofservice.GetTermsOfServiceRequest(), - name='name_value', + name="name_value", ) @@ -1759,12 +2278,19 @@ def test_retrieve_latest_terms_of_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.retrieve_latest_terms_of_service in client._transport._wrapped_methods + assert ( + client._transport.retrieve_latest_terms_of_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.retrieve_latest_terms_of_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.retrieve_latest_terms_of_service + ] = mock_rpc request = {} client.retrieve_latest_terms_of_service(request) @@ -1779,60 +2305,70 @@ def test_retrieve_latest_terms_of_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_retrieve_latest_terms_of_service_rest_required_fields(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): +def test_retrieve_latest_terms_of_service_rest_required_fields( + request_type=termsofservice.RetrieveLatestTermsOfServiceRequest, +): transport_class = transports.TermsOfServiceServiceRestTransport request_init = {} request_init["region_code"] = "" 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 assert "regionCode" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "regionCode" in jsonified_request assert jsonified_request["regionCode"] == request_init["region_code"] - jsonified_request["regionCode"] = 'region_code_value' + jsonified_request["regionCode"] = "region_code_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_latest_terms_of_service._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("kind", "region_code", )) + assert not set(unset_fields) - set( + ( + "kind", + "region_code", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "regionCode" in jsonified_request - assert jsonified_request["regionCode"] == 'region_code_value' + assert jsonified_request["regionCode"] == "region_code_value" client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = termsofservice.TermsOfService() # Mock the http request 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 @@ -1843,7 +2379,7 @@ def test_retrieve_latest_terms_of_service_rest_required_fields(request_type=term return_value = termsofservice.TermsOfService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1854,17 +2390,34 @@ def test_retrieve_latest_terms_of_service_rest_required_fields(request_type=term "regionCode", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_retrieve_latest_terms_of_service_rest_unset_required_fields(): - transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) - unset_fields = transport.retrieve_latest_terms_of_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(("kind", "regionCode", )) & set(("regionCode", "kind", ))) + unset_fields = ( + transport.retrieve_latest_terms_of_service._get_unset_required_fields({}) + ) + assert set(unset_fields) == ( + set( + ( + "kind", + "regionCode", + ) + ) + & set( + ( + "regionCode", + "kind", + ) + ) + ) def test_accept_terms_of_service_rest_use_cached_wrapped_rpc(): @@ -1881,12 +2434,19 @@ def test_accept_terms_of_service_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.accept_terms_of_service in client._transport._wrapped_methods + assert ( + client._transport.accept_terms_of_service + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.accept_terms_of_service] = mock_rpc + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.accept_terms_of_service + ] = mock_rpc request = {} client.accept_terms_of_service(request) @@ -1901,7 +2461,9 @@ def test_accept_terms_of_service_rest_use_cached_wrapped_rpc(): assert mock_rpc.call_count == 2 -def test_accept_terms_of_service_rest_required_fields(request_type=termsofservice.AcceptTermsOfServiceRequest): +def test_accept_terms_of_service_rest_required_fields( + request_type=termsofservice.AcceptTermsOfServiceRequest, +): transport_class = transports.TermsOfServiceServiceRestTransport request_init = {} @@ -1910,16 +2472,17 @@ def test_accept_terms_of_service_rest_required_fields(request_type=termsofservic request_init["region_code"] = "" 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 assert "account" not in jsonified_request assert "regionCode" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).accept_terms_of_service._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1928,44 +2491,51 @@ def test_accept_terms_of_service_rest_required_fields(request_type=termsofservic assert "regionCode" in jsonified_request assert jsonified_request["regionCode"] == request_init["region_code"] - jsonified_request["name"] = 'name_value' - jsonified_request["account"] = 'account_value' - jsonified_request["regionCode"] = 'region_code_value' + jsonified_request["name"] = "name_value" + jsonified_request["account"] = "account_value" + jsonified_request["regionCode"] = "region_code_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).accept_terms_of_service._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).accept_terms_of_service._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("account", "region_code", )) + assert not set(unset_fields) - set( + ( + "account", + "region_code", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" assert "account" in jsonified_request - assert jsonified_request["account"] == 'account_value' + assert jsonified_request["account"] == "account_value" assert "regionCode" in jsonified_request - assert jsonified_request["regionCode"] == 'region_code_value' + assert jsonified_request["regionCode"] == "region_code_value" client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = termsofservice.AcceptTermsOfServiceResponse() # Mock the http request 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.return_value = transcode_result @@ -1976,7 +2546,7 @@ def test_accept_terms_of_service_rest_required_fields(request_type=termsofservic return_value = termsofservice.AcceptTermsOfServiceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -1991,17 +2561,33 @@ def test_accept_terms_of_service_rest_required_fields(request_type=termsofservic "regionCode", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_accept_terms_of_service_rest_unset_required_fields(): - transport = transports.TermsOfServiceServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.TermsOfServiceServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.accept_terms_of_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(("account", "regionCode", )) & set(("name", "account", "regionCode", ))) + assert set(unset_fields) == ( + set( + ( + "account", + "regionCode", + ) + ) + & set( + ( + "name", + "account", + "regionCode", + ) + ) + ) def test_accept_terms_of_service_rest_flattened(): @@ -2011,16 +2597,16 @@ def test_accept_terms_of_service_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 = termsofservice.AcceptTermsOfServiceResponse() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'termsOfService/sample1'} + sample_request = {"name": "termsOfService/sample1"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2030,7 +2616,7 @@ def test_accept_terms_of_service_rest_flattened(): # Convert return value to protobuf type return_value = termsofservice.AcceptTermsOfServiceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2040,10 +2626,13 @@ def test_accept_terms_of_service_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=termsOfService/*}:accept" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=termsOfService/*}:accept" % client.transport._host, + args[1], + ) -def test_accept_terms_of_service_rest_flattened_error(transport: str = 'rest'): +def test_accept_terms_of_service_rest_flattened_error(transport: str = "rest"): client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2054,7 +2643,7 @@ def test_accept_terms_of_service_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.accept_terms_of_service( termsofservice.AcceptTermsOfServiceRequest(), - name='name_value', + name="name_value", ) @@ -2096,8 +2685,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = TermsOfServiceServiceClient( - 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. @@ -2119,6 +2707,7 @@ def test_transport_instance(): client = TermsOfServiceServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TermsOfServiceServiceGrpcTransport( @@ -2133,18 +2722,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.TermsOfServiceServiceGrpcTransport, - transports.TermsOfServiceServiceGrpcAsyncIOTransport, - transports.TermsOfServiceServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + transports.TermsOfServiceServiceRestTransport, + ], +) 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 = TermsOfServiceServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -2154,8 +2748,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -2170,8 +2763,8 @@ def test_get_terms_of_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: call.return_value = termsofservice.TermsOfService() client.get_terms_of_service(request=None) @@ -2193,8 +2786,8 @@ def test_retrieve_latest_terms_of_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: + type(client.transport.retrieve_latest_terms_of_service), "__call__" + ) as call: call.return_value = termsofservice.TermsOfService() client.retrieve_latest_terms_of_service(request=None) @@ -2216,8 +2809,8 @@ def test_accept_terms_of_service_empty_call_grpc(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: call.return_value = termsofservice.AcceptTermsOfServiceResponse() client.accept_terms_of_service(request=None) @@ -2238,8 +2831,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = TermsOfServiceServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -2255,16 +2847,18 @@ async def test_get_terms_of_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.TermsOfService( + name="name_value", + region_code="region_code_value", + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri="file_uri_value", + external=True, + ) + ) await client.get_terms_of_service(request=None) # Establish that the underlying stub method was called. @@ -2286,16 +2880,18 @@ async def test_retrieve_latest_terms_of_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: + type(client.transport.retrieve_latest_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.TermsOfService( + name="name_value", + region_code="region_code_value", + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri="file_uri_value", + external=True, + ) + ) await client.retrieve_latest_terms_of_service(request=None) # Establish that the underlying stub method was called. @@ -2317,11 +2913,12 @@ async def test_accept_terms_of_service_empty_call_grpc_asyncio(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(termsofservice.AcceptTermsOfServiceResponse( - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + termsofservice.AcceptTermsOfServiceResponse() + ) await client.accept_terms_of_service(request=None) # Establish that the underlying stub method was called. @@ -2339,20 +2936,23 @@ def test_transport_kind_rest(): assert transport.kind == "rest" -def test_get_terms_of_service_rest_bad_request(request_type=termsofservice.GetTermsOfServiceRequest): +def test_get_terms_of_service_rest_bad_request( + request_type=termsofservice.GetTermsOfServiceRequest, +): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} + request_init = {"name": "termsOfService/sample1"} 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() @@ -2361,29 +2961,31 @@ def test_get_terms_of_service_rest_bad_request(request_type=termsofservice.GetTe client.get_terms_of_service(request) -@pytest.mark.parametrize("request_type", [ - termsofservice.GetTermsOfServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + termsofservice.GetTermsOfServiceRequest, + dict, + ], +) def test_get_terms_of_service_rest_call_success(request_type): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} + request_init = {"name": "termsOfService/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, + name="name_value", + region_code="region_code_value", + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri="file_uri_value", + external=True, ) # Wrap the value into a proper Response obj @@ -2393,17 +2995,17 @@ def test_get_terms_of_service_rest_call_success(request_type): # Convert return value to protobuf type return_value = termsofservice.TermsOfService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_terms_of_service(request) # Establish that the response is the type that we expect. assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' + assert response.file_uri == "file_uri_value" assert response.external is True @@ -2411,19 +3013,30 @@ def test_get_terms_of_service_rest_call_success(request_type): def test_get_terms_of_service_rest_interceptors(null_interceptor): transport = transports.TermsOfServiceServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.TermsOfServiceServiceRestInterceptor(), + ) client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service") as post, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_get_terms_of_service") 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.TermsOfServiceServiceRestInterceptor, "post_get_terms_of_service" + ) as post, mock.patch.object( + transports.TermsOfServiceServiceRestInterceptor, + "post_get_terms_of_service_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.TermsOfServiceServiceRestInterceptor, "pre_get_terms_of_service" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = termsofservice.GetTermsOfServiceRequest.pb(termsofservice.GetTermsOfServiceRequest()) + pb_message = termsofservice.GetTermsOfServiceRequest.pb( + termsofservice.GetTermsOfServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2434,11 +3047,13 @@ def test_get_terms_of_service_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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) + return_value = termsofservice.TermsOfService.to_json( + termsofservice.TermsOfService() + ) req.return_value.content = return_value request = termsofservice.GetTermsOfServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2446,27 +3061,36 @@ def test_get_terms_of_service_rest_interceptors(null_interceptor): post.return_value = termsofservice.TermsOfService() post_with_metadata.return_value = termsofservice.TermsOfService(), metadata - client.get_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_terms_of_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_retrieve_latest_terms_of_service_rest_bad_request(request_type=termsofservice.RetrieveLatestTermsOfServiceRequest): +def test_retrieve_latest_terms_of_service_rest_bad_request( + request_type=termsofservice.RetrieveLatestTermsOfServiceRequest, +): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = mock.Mock() - json_return_value = '' + json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 response_value.request = mock.Mock() @@ -2475,14 +3099,16 @@ def test_retrieve_latest_terms_of_service_rest_bad_request(request_type=termsofs client.retrieve_latest_terms_of_service(request) -@pytest.mark.parametrize("request_type", [ - termsofservice.RetrieveLatestTermsOfServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + termsofservice.RetrieveLatestTermsOfServiceRequest, + dict, + ], +) def test_retrieve_latest_terms_of_service_rest_call_success(request_type): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding @@ -2490,14 +3116,14 @@ def test_retrieve_latest_terms_of_service_rest_call_success(request_type): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = termsofservice.TermsOfService( - name='name_value', - region_code='region_code_value', - kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, - file_uri='file_uri_value', - external=True, + name="name_value", + region_code="region_code_value", + kind=termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER, + file_uri="file_uri_value", + external=True, ) # Wrap the value into a proper Response obj @@ -2507,17 +3133,17 @@ def test_retrieve_latest_terms_of_service_rest_call_success(request_type): # Convert return value to protobuf type return_value = termsofservice.TermsOfService.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.retrieve_latest_terms_of_service(request) # Establish that the response is the type that we expect. assert isinstance(response, termsofservice.TermsOfService) - assert response.name == 'name_value' - assert response.region_code == 'region_code_value' + assert response.name == "name_value" + assert response.region_code == "region_code_value" assert response.kind == termsofservicekind.TermsOfServiceKind.MERCHANT_CENTER - assert response.file_uri == 'file_uri_value' + assert response.file_uri == "file_uri_value" assert response.external is True @@ -2525,19 +3151,32 @@ def test_retrieve_latest_terms_of_service_rest_call_success(request_type): def test_retrieve_latest_terms_of_service_rest_interceptors(null_interceptor): transport = transports.TermsOfServiceServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.TermsOfServiceServiceRestInterceptor(), + ) client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service") as post, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_retrieve_latest_terms_of_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_retrieve_latest_terms_of_service") 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.TermsOfServiceServiceRestInterceptor, + "post_retrieve_latest_terms_of_service", + ) as post, mock.patch.object( + transports.TermsOfServiceServiceRestInterceptor, + "post_retrieve_latest_terms_of_service_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.TermsOfServiceServiceRestInterceptor, + "pre_retrieve_latest_terms_of_service", + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = termsofservice.RetrieveLatestTermsOfServiceRequest.pb(termsofservice.RetrieveLatestTermsOfServiceRequest()) + pb_message = termsofservice.RetrieveLatestTermsOfServiceRequest.pb( + termsofservice.RetrieveLatestTermsOfServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2548,11 +3187,13 @@ def test_retrieve_latest_terms_of_service_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 = termsofservice.TermsOfService.to_json(termsofservice.TermsOfService()) + return_value = termsofservice.TermsOfService.to_json( + termsofservice.TermsOfService() + ) req.return_value.content = return_value request = termsofservice.RetrieveLatestTermsOfServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -2560,27 +3201,36 @@ def test_retrieve_latest_terms_of_service_rest_interceptors(null_interceptor): post.return_value = termsofservice.TermsOfService() post_with_metadata.return_value = termsofservice.TermsOfService(), metadata - client.retrieve_latest_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.retrieve_latest_terms_of_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() -def test_accept_terms_of_service_rest_bad_request(request_type=termsofservice.AcceptTermsOfServiceRequest): +def test_accept_terms_of_service_rest_bad_request( + request_type=termsofservice.AcceptTermsOfServiceRequest, +): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} + request_init = {"name": "termsOfService/sample1"} 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() @@ -2589,25 +3239,26 @@ def test_accept_terms_of_service_rest_bad_request(request_type=termsofservice.Ac client.accept_terms_of_service(request) -@pytest.mark.parametrize("request_type", [ - termsofservice.AcceptTermsOfServiceRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + termsofservice.AcceptTermsOfServiceRequest, + dict, + ], +) def test_accept_terms_of_service_rest_call_success(request_type): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'termsOfService/sample1'} + request_init = {"name": "termsOfService/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = termsofservice.AcceptTermsOfServiceResponse( - ) + return_value = termsofservice.AcceptTermsOfServiceResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -2616,7 +3267,7 @@ def test_accept_terms_of_service_rest_call_success(request_type): # Convert return value to protobuf type return_value = termsofservice.AcceptTermsOfServiceResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.accept_terms_of_service(request) @@ -2629,19 +3280,30 @@ def test_accept_terms_of_service_rest_call_success(request_type): def test_accept_terms_of_service_rest_interceptors(null_interceptor): transport = transports.TermsOfServiceServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.TermsOfServiceServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.TermsOfServiceServiceRestInterceptor(), + ) client = TermsOfServiceServiceClient(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.TermsOfServiceServiceRestInterceptor, "post_accept_terms_of_service") as post, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "post_accept_terms_of_service_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.TermsOfServiceServiceRestInterceptor, "pre_accept_terms_of_service") 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.TermsOfServiceServiceRestInterceptor, "post_accept_terms_of_service" + ) as post, mock.patch.object( + transports.TermsOfServiceServiceRestInterceptor, + "post_accept_terms_of_service_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.TermsOfServiceServiceRestInterceptor, "pre_accept_terms_of_service" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = termsofservice.AcceptTermsOfServiceRequest.pb(termsofservice.AcceptTermsOfServiceRequest()) + pb_message = termsofservice.AcceptTermsOfServiceRequest.pb( + termsofservice.AcceptTermsOfServiceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2652,28 +3314,39 @@ def test_accept_terms_of_service_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 = termsofservice.AcceptTermsOfServiceResponse.to_json(termsofservice.AcceptTermsOfServiceResponse()) + return_value = termsofservice.AcceptTermsOfServiceResponse.to_json( + termsofservice.AcceptTermsOfServiceResponse() + ) req.return_value.content = return_value request = termsofservice.AcceptTermsOfServiceRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = termsofservice.AcceptTermsOfServiceResponse() - post_with_metadata.return_value = termsofservice.AcceptTermsOfServiceResponse(), metadata + post_with_metadata.return_value = ( + termsofservice.AcceptTermsOfServiceResponse(), + metadata, + ) - client.accept_terms_of_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.accept_terms_of_service( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = TermsOfServiceServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -2688,8 +3361,8 @@ def test_get_terms_of_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_terms_of_service), - '__call__') as call: + type(client.transport.get_terms_of_service), "__call__" + ) as call: client.get_terms_of_service(request=None) # Establish that the underlying stub method was called. @@ -2710,8 +3383,8 @@ def test_retrieve_latest_terms_of_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.retrieve_latest_terms_of_service), - '__call__') as call: + type(client.transport.retrieve_latest_terms_of_service), "__call__" + ) as call: client.retrieve_latest_terms_of_service(request=None) # Establish that the underlying stub method was called. @@ -2732,8 +3405,8 @@ def test_accept_terms_of_service_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.accept_terms_of_service), - '__call__') as call: + type(client.transport.accept_terms_of_service), "__call__" + ) as call: client.accept_terms_of_service(request=None) # Establish that the underlying stub method was called. @@ -2754,18 +3427,21 @@ def test_transport_grpc_default(): transports.TermsOfServiceServiceGrpcTransport, ) + def test_terms_of_service_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TermsOfServiceServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_terms_of_service_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.TermsOfServiceServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -2774,9 +3450,9 @@ def test_terms_of_service_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_terms_of_service', - 'retrieve_latest_terms_of_service', - 'accept_terms_of_service', + "get_terms_of_service", + "retrieve_latest_terms_of_service", + "accept_terms_of_service", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2787,7 +3463,7 @@ def test_terms_of_service_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -2796,25 +3472,30 @@ def test_terms_of_service_service_base_transport(): def test_terms_of_service_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_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._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_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TermsOfServiceServiceTransport( 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_terms_of_service_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_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.terms_of_service_service.transports.TermsOfServiceServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TermsOfServiceServiceTransport() @@ -2823,14 +3504,12 @@ def test_terms_of_service_service_base_transport_with_adc(): def test_terms_of_service_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) TermsOfServiceServiceClient() 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, ) @@ -2845,12 +3524,12 @@ def test_terms_of_service_service_auth_adc(): def test_terms_of_service_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", ) @@ -2864,48 +3543,47 @@ def test_terms_of_service_service_transport_auth_adc(transport_class): ], ) def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, grpc_helpers), - (transports.TermsOfServiceServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.TermsOfServiceServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -def test_terms_of_service_service_transport_create_channel(transport_class, grpc_helpers): +def test_terms_of_service_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, @@ -2916,9 +3594,15 @@ def test_terms_of_service_service_transport_create_channel(transport_class, grpc ) -@pytest.mark.parametrize("transport_class", [transports.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + ], +) def test_terms_of_service_service_grpc_transport_client_cert_source_for_mtls( - transport_class + transport_class, ): cred = ga_credentials.AnonymousCredentials() @@ -2928,7 +3612,7 @@ def test_terms_of_service_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", @@ -2949,61 +3633,77 @@ def test_terms_of_service_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_terms_of_service_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.TermsOfServiceServiceRestTransport ( - 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.TermsOfServiceServiceRestTransport( + 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_terms_of_service_service_host_no_port(transport_name): client = TermsOfServiceServiceClient( 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_terms_of_service_service_host_with_port(transport_name): client = TermsOfServiceServiceClient( 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_terms_of_service_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3024,8 +3724,10 @@ def test_terms_of_service_service_client_transport_session_collision(transport_n session1 = client1.transport.accept_terms_of_service._session session2 = client2.transport.accept_terms_of_service._session assert session1 != session2 + + def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport( @@ -3038,7 +3740,7 @@ def test_terms_of_service_service_grpc_transport_channel(): def test_terms_of_service_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.TermsOfServiceServiceGrpcAsyncIOTransport( @@ -3052,12 +3754,22 @@ def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + ], +) def test_terms_of_service_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 @@ -3066,7 +3778,7 @@ def test_terms_of_service_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", @@ -3096,17 +3808,23 @@ def test_terms_of_service_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.TermsOfServiceServiceGrpcTransport, transports.TermsOfServiceServiceGrpcAsyncIOTransport]) -def test_terms_of_service_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.TermsOfServiceServiceGrpcTransport, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + ], +) +def test_terms_of_service_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() @@ -3136,7 +3854,9 @@ def test_terms_of_service_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = TermsOfServiceServiceClient.account_path(account) assert expected == actual @@ -3151,9 +3871,12 @@ def test_parse_account_path(): actual = TermsOfServiceServiceClient.parse_account_path(path) assert expected == actual + def test_terms_of_service_path(): version = "whelk" - expected = "termsOfService/{version}".format(version=version, ) + expected = "termsOfService/{version}".format( + version=version, + ) actual = TermsOfServiceServiceClient.terms_of_service_path(version) assert expected == actual @@ -3168,11 +3891,17 @@ def test_parse_terms_of_service_path(): actual = TermsOfServiceServiceClient.parse_terms_of_service_path(path) assert expected == actual + def test_terms_of_service_agreement_state_path(): account = "oyster" identifier = "nudibranch" - expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format(account=account, identifier=identifier, ) - actual = TermsOfServiceServiceClient.terms_of_service_agreement_state_path(account, identifier) + expected = "accounts/{account}/termsOfServiceAgreementStates/{identifier}".format( + account=account, + identifier=identifier, + ) + actual = TermsOfServiceServiceClient.terms_of_service_agreement_state_path( + account, identifier + ) assert expected == actual @@ -3184,12 +3913,17 @@ def test_parse_terms_of_service_agreement_state_path(): path = TermsOfServiceServiceClient.terms_of_service_agreement_state_path(**expected) # Check that the path construction is reversible. - actual = TermsOfServiceServiceClient.parse_terms_of_service_agreement_state_path(path) + actual = TermsOfServiceServiceClient.parse_terms_of_service_agreement_state_path( + path + ) assert expected == actual + def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = TermsOfServiceServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -3204,9 +3938,12 @@ def test_parse_common_billing_account_path(): actual = TermsOfServiceServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = TermsOfServiceServiceClient.common_folder_path(folder) assert expected == actual @@ -3221,9 +3958,12 @@ def test_parse_common_folder_path(): actual = TermsOfServiceServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = TermsOfServiceServiceClient.common_organization_path(organization) assert expected == actual @@ -3238,9 +3978,12 @@ def test_parse_common_organization_path(): actual = TermsOfServiceServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = TermsOfServiceServiceClient.common_project_path(project) assert expected == actual @@ -3255,10 +3998,14 @@ def test_parse_common_project_path(): actual = TermsOfServiceServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = TermsOfServiceServiceClient.common_location_path(project, location) assert expected == actual @@ -3278,14 +4025,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.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.TermsOfServiceServiceTransport, "_prep_wrapped_messages" + ) as prep: client = TermsOfServiceServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.TermsOfServiceServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.TermsOfServiceServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = TermsOfServiceServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -3296,10 +4047,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = TermsOfServiceServiceClient( - 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() @@ -3308,10 +4060,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = TermsOfServiceServiceAsyncClient( - 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() @@ -3319,10 +4072,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = TermsOfServiceServiceClient( - 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() @@ -3330,13 +4084,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = TermsOfServiceServiceClient( - 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: @@ -3345,10 +4098,17 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport), - (TermsOfServiceServiceAsyncClient, transports.TermsOfServiceServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (TermsOfServiceServiceClient, transports.TermsOfServiceServiceGrpcTransport), + ( + TermsOfServiceServiceAsyncClient, + transports.TermsOfServiceServiceGrpcAsyncIOTransport, + ), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -3363,7 +4123,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-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_user_service.py similarity index 72% rename from owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py rename to packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_user_service.py index 55cb564a9d26..4b1e39f884ca 100644 --- a/owl-bot-staging/google-shopping-merchant-accounts/v1/tests/unit/gapic/merchant_accounts_v1/test_user_service.py +++ b/packages/google-shopping-merchant-accounts/tests/unit/gapic/merchant_accounts_v1/test_user_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,48 +22,46 @@ 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 field_mask_pb2 # type: ignore -from google.shopping.merchant_accounts_v1.services.user_service import UserServiceAsyncClient -from google.shopping.merchant_accounts_v1.services.user_service import UserServiceClient -from google.shopping.merchant_accounts_v1.services.user_service import pagers -from google.shopping.merchant_accounts_v1.services.user_service import transports + +from google.shopping.merchant_accounts_v1.services.user_service import ( + UserServiceAsyncClient, + UserServiceClient, + pagers, + transports, +) from google.shopping.merchant_accounts_v1.types import accessright from google.shopping.merchant_accounts_v1.types import user from google.shopping.merchant_accounts_v1.types import user as gsma_user -import google.auth - - CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -77,9 +76,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(): @@ -87,17 +88,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(): @@ -108,12 +119,24 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert UserServiceClient._get_default_mtls_endpoint(None) is None - assert UserServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ( + UserServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + UserServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + UserServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + UserServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) assert UserServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + def test__read_environment_variables(): assert UserServiceClient._read_environment_variables() == (False, "auto", None) @@ -123,16 +146,25 @@ def test__read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): assert UserServiceClient._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: UserServiceClient._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 UserServiceClient._read_environment_variables() == (False, "never", None) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert UserServiceClient._read_environment_variables() == (False, "always", None) + assert UserServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): assert UserServiceClient._read_environment_variables() == (False, "auto", None) @@ -140,69 +172,156 @@ def test__read_environment_variables(): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError) as excinfo: UserServiceClient._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 UserServiceClient._read_environment_variables() == (False, "auto", "foo.com") + assert UserServiceClient._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 UserServiceClient._get_client_cert_source(None, False) is None - assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert UserServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + assert ( + UserServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + UserServiceClient._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 UserServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert UserServiceClient._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 ( + UserServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + UserServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) + +@mock.patch.object( + UserServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceClient), +) +@mock.patch.object( + UserServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceAsyncClient), +) def test__get_api_endpoint(): api_override = "foo.com" mock_client_cert_source = mock.Mock() default_universe = UserServiceClient._DEFAULT_UNIVERSE - default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) - assert UserServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == UserServiceClient.DEFAULT_MTLS_ENDPOINT - assert UserServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert UserServiceClient._get_api_endpoint(None, None, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT - assert UserServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == UserServiceClient.DEFAULT_MTLS_ENDPOINT - assert UserServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert UserServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + assert ( + UserServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + UserServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == UserServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + UserServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + UserServiceClient._get_api_endpoint(None, None, default_universe, "always") + == UserServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + UserServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == UserServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + UserServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + UserServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) with pytest.raises(MutualTLSChannelError) as excinfo: - UserServiceClient._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." + UserServiceClient._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 UserServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert UserServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert UserServiceClient._get_universe_domain(None, None) == UserServiceClient._DEFAULT_UNIVERSE + assert ( + UserServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + UserServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + UserServiceClient._get_universe_domain(None, None) + == UserServiceClient._DEFAULT_UNIVERSE + ) with pytest.raises(ValueError) as excinfo: UserServiceClient._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) @@ -218,7 +337,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") @@ -231,14 +351,20 @@ def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): client._add_cred_info_for_auth_errors(error) assert error.details == [] -@pytest.mark.parametrize("client_class,transport_name", [ - (UserServiceClient, "grpc"), - (UserServiceAsyncClient, "grpc_asyncio"), - (UserServiceClient, "rest"), -]) + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (UserServiceClient, "grpc"), + (UserServiceAsyncClient, "grpc_asyncio"), + (UserServiceClient, "rest"), + ], +) def test_user_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) @@ -246,52 +372,68 @@ def test_user_service_client_from_service_account_info(client_class, transport_n 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.UserServiceGrpcTransport, "grpc"), - (transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.UserServiceRestTransport, "rest"), -]) -def test_user_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.UserServiceGrpcTransport, "grpc"), + (transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserServiceRestTransport, "rest"), + ], +) +def test_user_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", [ - (UserServiceClient, "grpc"), - (UserServiceAsyncClient, "grpc_asyncio"), - (UserServiceClient, "rest"), -]) +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (UserServiceClient, "grpc"), + (UserServiceAsyncClient, "grpc_asyncio"), + (UserServiceClient, "rest"), + ], +) def test_user_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" ) @@ -307,30 +449,45 @@ def test_user_service_client_get_transport_class(): assert transport == transports.UserServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserServiceClient, transports.UserServiceRestTransport, "rest"), -]) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) -def test_user_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + ( + UserServiceAsyncClient, + transports.UserServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + UserServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceClient), +) +@mock.patch.object( + UserServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceAsyncClient), +) +def test_user_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(UserServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(UserServiceClient, "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(UserServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(UserServiceClient, "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( @@ -348,13 +505,15 @@ def test_user_service_client_client_options(client_class, transport_class, trans # 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, @@ -366,7 +525,7 @@ def test_user_service_client_client_options(client_class, transport_class, trans # 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( @@ -386,23 +545,33 @@ def test_user_service_client_client_options(client_class, transport_class, trans 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", @@ -411,48 +580,82 @@ def test_user_service_client_client_options(client_class, transport_class, trans 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", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "true"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "false"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (UserServiceClient, transports.UserServiceRestTransport, "rest", "true"), - (UserServiceClient, transports.UserServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "true"), + ( + UserServiceAsyncClient, + transports.UserServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", "false"), + ( + UserServiceAsyncClient, + transports.UserServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (UserServiceClient, transports.UserServiceRestTransport, "rest", "true"), + (UserServiceClient, transports.UserServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + UserServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceClient), +) +@mock.patch.object( + UserServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_user_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 @@ -471,12 +674,22 @@ def test_user_service_client_mtls_env_auto(client_class, transport_class, transp # 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 @@ -497,15 +710,22 @@ def test_user_service_client_mtls_env_auto(client_class, transport_class, transp ) # 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, @@ -515,19 +735,27 @@ def test_user_service_client_mtls_env_auto(client_class, transport_class, transp ) -@pytest.mark.parametrize("client_class", [ - UserServiceClient, UserServiceAsyncClient -]) -@mock.patch.object(UserServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceAsyncClient)) +@pytest.mark.parametrize("client_class", [UserServiceClient, UserServiceAsyncClient]) +@mock.patch.object( + UserServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserServiceClient) +) +@mock.patch.object( + UserServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(UserServiceAsyncClient), +) def test_user_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 @@ -535,8 +763,12 @@ def test_user_service_client_get_mtls_endpoint_and_cert_source(client_class): with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) assert api_endpoint == mock_api_endpoint assert cert_source is None @@ -554,16 +786,28 @@ def test_user_service_client_get_mtls_endpoint_and_cert_source(client_class): # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @@ -573,34 +817,60 @@ def test_user_service_client_get_mtls_endpoint_and_cert_source(client_class): with pytest.raises(MutualTLSChannelError) as excinfo: client_class.get_mtls_endpoint_and_cert_source() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) # 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", [ - UserServiceClient, UserServiceAsyncClient -]) -@mock.patch.object(UserServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceClient)) -@mock.patch.object(UserServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(UserServiceAsyncClient)) +@pytest.mark.parametrize("client_class", [UserServiceClient, UserServiceAsyncClient]) +@mock.patch.object( + UserServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceClient), +) +@mock.patch.object( + UserServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(UserServiceAsyncClient), +) def test_user_service_client_client_api_endpoint(client_class): mock_client_cert_source = client_cert_source_callback api_override = "foo.com" default_universe = UserServiceClient._DEFAULT_UNIVERSE - default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + default_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) mock_universe = "bar.com" - mock_endpoint = UserServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + mock_endpoint = UserServiceClient._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", @@ -623,11 +893,19 @@ def test_user_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. @@ -635,27 +913,40 @@ def test_user_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", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserServiceClient, transports.UserServiceRestTransport, "rest"), -]) -def test_user_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc"), + ( + UserServiceAsyncClient, + transports.UserServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (UserServiceClient, transports.UserServiceRestTransport, "rest"), + ], +) +def test_user_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, @@ -664,24 +955,35 @@ def test_user_service_client_client_options_scopes(client_class, transport_class api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (UserServiceClient, transports.UserServiceRestTransport, "rest", None), -]) -def test_user_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", + [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), + ( + UserServiceAsyncClient, + transports.UserServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (UserServiceClient, transports.UserServiceRestTransport, "rest", None), + ], +) +def test_user_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, @@ -690,12 +992,13 @@ def test_user_service_client_client_options_credentials_file(client_class, trans api_audience=None, ) + def test_user_service_client_client_options_from_dict(): - with mock.patch('google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None - client = UserServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) + client = UserServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) grpc_transport.assert_called_once_with( credentials=None, credentials_file=None, @@ -709,23 +1012,33 @@ def test_user_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_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", + [ + (UserServiceClient, transports.UserServiceGrpcTransport, "grpc", grpc_helpers), + ( + UserServiceAsyncClient, + transports.UserServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_user_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, @@ -752,9 +1065,7 @@ def test_user_service_client_create_channel_credentials_file(client_class, trans 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, @@ -765,11 +1076,14 @@ def test_user_service_client_create_channel_credentials_file(client_class, trans ) -@pytest.mark.parametrize("request_type", [ - user.GetUserRequest, - dict, -]) -def test_get_user(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + user.GetUserRequest, + dict, + ], +) +def test_get_user(request_type, transport: str = "grpc"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -780,12 +1094,10 @@ def test_get_user(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = user.User( - name='name_value', + name="name_value", state=user.User.State.PENDING, access_rights=[accessright.AccessRight.STANDARD], ) @@ -799,7 +1111,7 @@ def test_get_user(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -809,28 +1121,29 @@ def test_get_user_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = UserServiceClient( 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 = user.GetUserRequest( - name='name_value', + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.get_user), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == user.GetUserRequest( - name='name_value', + name="name_value", ) + def test_get_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -849,7 +1162,9 @@ def test_get_user_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_user] = mock_rpc request = {} client.get_user(request) @@ -863,6 +1178,7 @@ def test_get_user_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -878,12 +1194,17 @@ async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.get_user in client._client._transport._wrapped_methods + assert ( + client._client._transport.get_user + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_user] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.get_user + ] = mock_rpc request = {} await client.get_user(request) @@ -897,8 +1218,11 @@ async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=user.GetUserRequest): +async def test_get_user_async( + transport: str = "grpc_asyncio", request_type=user.GetUserRequest +): client = UserServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -909,15 +1233,15 @@ async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=user request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user.User( + name="name_value", + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + ) response = await client.get_user(request) # Establish that the underlying gRPC stub method was called. @@ -928,7 +1252,7 @@ async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=user # Establish that the response is the type that we expect. assert isinstance(response, user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -937,6 +1261,7 @@ async def test_get_user_async(transport: str = 'grpc_asyncio', request_type=user async def test_get_user_async_from_dict(): await test_get_user_async(request_type=dict) + def test_get_user_field_headers(): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -946,12 +1271,10 @@ def test_get_user_field_headers(): # a field header. Set these to a non-empty value. request = user.GetUserRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = user.User() client.get_user(request) @@ -963,9 +1286,9 @@ def test_get_user_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 @@ -978,12 +1301,10 @@ async def test_get_user_field_headers_async(): # a field header. Set these to a non-empty value. request = user.GetUserRequest() - request.name = 'name_value' + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User()) await client.get_user(request) @@ -995,9 +1316,9 @@ async def test_get_user_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_user_flattened(): @@ -1006,15 +1327,13 @@ def test_get_user_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = user.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_user( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1022,7 +1341,7 @@ def test_get_user_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 @@ -1036,9 +1355,10 @@ def test_get_user_flattened_error(): with pytest.raises(ValueError): client.get_user( user.GetUserRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_user_flattened_async(): client = UserServiceAsyncClient( @@ -1046,9 +1366,7 @@ async def test_get_user_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = user.User() @@ -1056,7 +1374,7 @@ async def test_get_user_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_user( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1064,9 +1382,10 @@ async def test_get_user_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_user_flattened_error_async(): client = UserServiceAsyncClient( @@ -1078,15 +1397,18 @@ async def test_get_user_flattened_error_async(): with pytest.raises(ValueError): await client.get_user( user.GetUserRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gsma_user.CreateUserRequest, - dict, -]) -def test_create_user(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gsma_user.CreateUserRequest, + dict, + ], +) +def test_create_user(request_type, transport: str = "grpc"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1097,12 +1419,10 @@ def test_create_user(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_user.User( - name='name_value', + name="name_value", state=gsma_user.User.State.PENDING, access_rights=[accessright.AccessRight.STANDARD], ) @@ -1116,7 +1436,7 @@ def test_create_user(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == gsma_user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -1126,30 +1446,31 @@ def test_create_user_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = UserServiceClient( 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 = gsma_user.CreateUserRequest( - parent='parent_value', - user_id='user_id_value', + parent="parent_value", + user_id="user_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == gsma_user.CreateUserRequest( - parent='parent_value', - user_id='user_id_value', + parent="parent_value", + user_id="user_id_value", ) + def test_create_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1168,7 +1489,9 @@ def test_create_user_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.create_user] = mock_rpc request = {} client.create_user(request) @@ -1182,8 +1505,11 @@ def test_create_user_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_user_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: @@ -1197,12 +1523,17 @@ async def test_create_user_async_use_cached_wrapped_rpc(transport: str = "grpc_a wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.create_user in client._client._transport._wrapped_methods + assert ( + client._client._transport.create_user + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_user] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.create_user + ] = mock_rpc request = {} await client.create_user(request) @@ -1216,8 +1547,11 @@ async def test_create_user_async_use_cached_wrapped_rpc(transport: str = "grpc_a assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.CreateUserRequest): +async def test_create_user_async( + transport: str = "grpc_asyncio", request_type=gsma_user.CreateUserRequest +): client = UserServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1228,15 +1562,15 @@ async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=g request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_user.User( + name="name_value", + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + ) response = await client.create_user(request) # Establish that the underlying gRPC stub method was called. @@ -1247,7 +1581,7 @@ async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=g # Establish that the response is the type that we expect. assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == gsma_user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -1256,6 +1590,7 @@ async def test_create_user_async(transport: str = 'grpc_asyncio', request_type=g async def test_create_user_async_from_dict(): await test_create_user_async(request_type=dict) + def test_create_user_field_headers(): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1265,12 +1600,10 @@ def test_create_user_field_headers(): # a field header. Set these to a non-empty value. request = gsma_user.CreateUserRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: call.return_value = gsma_user.User() client.create_user(request) @@ -1282,9 +1615,9 @@ def test_create_user_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 @@ -1297,12 +1630,10 @@ async def test_create_user_field_headers_async(): # a field header. Set these to a non-empty value. request = gsma_user.CreateUserRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) await client.create_user(request) @@ -1314,9 +1645,9 @@ async def test_create_user_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_user_flattened(): @@ -1325,17 +1656,15 @@ def test_create_user_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_user.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_user( - parent='parent_value', - user=gsma_user.User(name='name_value'), - user_id='user_id_value', + parent="parent_value", + user=gsma_user.User(name="name_value"), + user_id="user_id_value", ) # Establish that the underlying call was made with the expected @@ -1343,13 +1672,13 @@ def test_create_user_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].user - mock_val = gsma_user.User(name='name_value') + mock_val = gsma_user.User(name="name_value") assert arg == mock_val arg = args[0].user_id - mock_val = 'user_id_value' + mock_val = "user_id_value" assert arg == mock_val @@ -1363,11 +1692,12 @@ def test_create_user_flattened_error(): with pytest.raises(ValueError): client.create_user( gsma_user.CreateUserRequest(), - parent='parent_value', - user=gsma_user.User(name='name_value'), - user_id='user_id_value', + parent="parent_value", + user=gsma_user.User(name="name_value"), + user_id="user_id_value", ) + @pytest.mark.asyncio async def test_create_user_flattened_async(): client = UserServiceAsyncClient( @@ -1375,9 +1705,7 @@ async def test_create_user_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_user.User() @@ -1385,9 +1713,9 @@ async def test_create_user_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.create_user( - parent='parent_value', - user=gsma_user.User(name='name_value'), - user_id='user_id_value', + parent="parent_value", + user=gsma_user.User(name="name_value"), + user_id="user_id_value", ) # Establish that the underlying call was made with the expected @@ -1395,15 +1723,16 @@ async def test_create_user_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].user - mock_val = gsma_user.User(name='name_value') + mock_val = gsma_user.User(name="name_value") assert arg == mock_val arg = args[0].user_id - mock_val = 'user_id_value' + mock_val = "user_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_user_flattened_error_async(): client = UserServiceAsyncClient( @@ -1415,17 +1744,20 @@ async def test_create_user_flattened_error_async(): with pytest.raises(ValueError): await client.create_user( gsma_user.CreateUserRequest(), - parent='parent_value', - user=gsma_user.User(name='name_value'), - user_id='user_id_value', + parent="parent_value", + user=gsma_user.User(name="name_value"), + user_id="user_id_value", ) -@pytest.mark.parametrize("request_type", [ - user.DeleteUserRequest, - dict, -]) -def test_delete_user(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + user.DeleteUserRequest, + dict, + ], +) +def test_delete_user(request_type, transport: str = "grpc"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1436,9 +1768,7 @@ def test_delete_user(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None response = client.delete_user(request) @@ -1458,28 +1788,29 @@ def test_delete_user_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = UserServiceClient( 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 = user.DeleteUserRequest( - 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_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.delete_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == user.DeleteUserRequest( - name='name_value', + name="name_value", ) + def test_delete_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -1498,7 +1829,9 @@ def test_delete_user_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc request = {} client.delete_user(request) @@ -1512,8 +1845,11 @@ def test_delete_user_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_user_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: @@ -1527,12 +1863,17 @@ async def test_delete_user_async_use_cached_wrapped_rpc(transport: str = "grpc_a wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.delete_user in client._client._transport._wrapped_methods + assert ( + client._client._transport.delete_user + 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_user] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.delete_user + ] = mock_rpc request = {} await client.delete_user(request) @@ -1546,8 +1887,11 @@ async def test_delete_user_async_use_cached_wrapped_rpc(transport: str = "grpc_a assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_delete_user_async(transport: str = 'grpc_asyncio', request_type=user.DeleteUserRequest): +async def test_delete_user_async( + transport: str = "grpc_asyncio", request_type=user.DeleteUserRequest +): client = UserServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1558,9 +1902,7 @@ async def test_delete_user_async(transport: str = 'grpc_asyncio', request_type=u request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) response = await client.delete_user(request) @@ -1579,6 +1921,7 @@ async def test_delete_user_async(transport: str = 'grpc_asyncio', request_type=u async def test_delete_user_async_from_dict(): await test_delete_user_async(request_type=dict) + def test_delete_user_field_headers(): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1588,12 +1931,10 @@ def test_delete_user_field_headers(): # a field header. Set these to a non-empty value. request = user.DeleteUserRequest() - 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_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: call.return_value = None client.delete_user(request) @@ -1605,9 +1946,9 @@ def test_delete_user_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 @@ -1620,12 +1961,10 @@ async def test_delete_user_field_headers_async(): # a field header. Set these to a non-empty value. request = user.DeleteUserRequest() - 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_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_user(request) @@ -1637,9 +1976,9 @@ async def test_delete_user_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_user_flattened(): @@ -1648,15 +1987,13 @@ def test_delete_user_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__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_user( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1664,7 +2001,7 @@ def test_delete_user_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 @@ -1678,9 +2015,10 @@ def test_delete_user_flattened_error(): with pytest.raises(ValueError): client.delete_user( user.DeleteUserRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_user_flattened_async(): client = UserServiceAsyncClient( @@ -1688,9 +2026,7 @@ async def test_delete_user_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None @@ -1698,7 +2034,7 @@ async def test_delete_user_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.delete_user( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1706,9 +2042,10 @@ async def test_delete_user_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_user_flattened_error_async(): client = UserServiceAsyncClient( @@ -1720,15 +2057,18 @@ async def test_delete_user_flattened_error_async(): with pytest.raises(ValueError): await client.delete_user( user.DeleteUserRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - gsma_user.UpdateUserRequest, - dict, -]) -def test_update_user(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + gsma_user.UpdateUserRequest, + dict, + ], +) +def test_update_user(request_type, transport: str = "grpc"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1739,12 +2079,10 @@ def test_update_user(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_user.User( - name='name_value', + name="name_value", state=gsma_user.User.State.PENDING, access_rights=[accessright.AccessRight.STANDARD], ) @@ -1758,7 +2096,7 @@ def test_update_user(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == gsma_user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -1768,25 +2106,24 @@ def test_update_user_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = UserServiceClient( 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 = gsma_user.UpdateUserRequest( - ) + request = gsma_user.UpdateUserRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gsma_user.UpdateUserRequest( - ) + assert args[0] == gsma_user.UpdateUserRequest() + def test_update_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -1806,7 +2143,9 @@ def test_update_user_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_user] = mock_rpc request = {} client.update_user(request) @@ -1820,8 +2159,11 @@ def test_update_user_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_update_user_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: @@ -1835,12 +2177,17 @@ async def test_update_user_async_use_cached_wrapped_rpc(transport: str = "grpc_a wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.update_user in client._client._transport._wrapped_methods + assert ( + client._client._transport.update_user + in client._client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_user] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.update_user + ] = mock_rpc request = {} await client.update_user(request) @@ -1854,8 +2201,11 @@ async def test_update_user_async_use_cached_wrapped_rpc(transport: str = "grpc_a assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=gsma_user.UpdateUserRequest): +async def test_update_user_async( + transport: str = "grpc_asyncio", request_type=gsma_user.UpdateUserRequest +): client = UserServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -1866,15 +2216,15 @@ async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=g request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_user.User( + name="name_value", + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + ) response = await client.update_user(request) # Establish that the underlying gRPC stub method was called. @@ -1885,7 +2235,7 @@ async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=g # Establish that the response is the type that we expect. assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == gsma_user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -1894,6 +2244,7 @@ async def test_update_user_async(transport: str = 'grpc_asyncio', request_type=g async def test_update_user_async_from_dict(): await test_update_user_async(request_type=dict) + def test_update_user_field_headers(): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1903,12 +2254,10 @@ def test_update_user_field_headers(): # a field header. Set these to a non-empty value. request = gsma_user.UpdateUserRequest() - request.user.name = 'name_value' + request.user.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: call.return_value = gsma_user.User() client.update_user(request) @@ -1920,9 +2269,9 @@ def test_update_user_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'user.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "user.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1935,12 +2284,10 @@ async def test_update_user_field_headers_async(): # a field header. Set these to a non-empty value. request = gsma_user.UpdateUserRequest() - request.user.name = 'name_value' + request.user.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User()) await client.update_user(request) @@ -1952,9 +2299,9 @@ async def test_update_user_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'user.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "user.name=name_value", + ) in kw["metadata"] def test_update_user_flattened(): @@ -1963,16 +2310,14 @@ def test_update_user_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_user.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_user( - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + user=gsma_user.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1980,10 +2325,10 @@ def test_update_user_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].user - mock_val = gsma_user.User(name='name_value') + mock_val = gsma_user.User(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1997,10 +2342,11 @@ def test_update_user_flattened_error(): with pytest.raises(ValueError): client.update_user( gsma_user.UpdateUserRequest(), - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + user=gsma_user.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_user_flattened_async(): client = UserServiceAsyncClient( @@ -2008,9 +2354,7 @@ async def test_update_user_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gsma_user.User() @@ -2018,8 +2362,8 @@ async def test_update_user_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_user( - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + user=gsma_user.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -2027,12 +2371,13 @@ async def test_update_user_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].user - mock_val = gsma_user.User(name='name_value') + mock_val = gsma_user.User(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_user_flattened_error_async(): client = UserServiceAsyncClient( @@ -2044,16 +2389,19 @@ async def test_update_user_flattened_error_async(): with pytest.raises(ValueError): await client.update_user( gsma_user.UpdateUserRequest(), - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + user=gsma_user.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - user.ListUsersRequest, - dict, -]) -def test_list_users(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + user.ListUsersRequest, + dict, + ], +) +def test_list_users(request_type, transport: str = "grpc"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2064,12 +2412,10 @@ def test_list_users(request_type, transport: str = 'grpc'): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = user.ListUsersResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_users(request) @@ -2081,7 +2427,7 @@ def test_list_users(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_users_non_empty_request_with_auto_populated_field(): @@ -2089,30 +2435,31 @@ def test_list_users_non_empty_request_with_auto_populated_field(): # automatically populated, according to AIP-4235, with non-empty requests. client = UserServiceClient( 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 = user.ListUsersRequest( - 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_users), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_users(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == user.ListUsersRequest( - parent='parent_value', - page_token='page_token_value', + parent="parent_value", + page_token="page_token_value", ) + def test_list_users_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -2131,7 +2478,9 @@ def test_list_users_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_users] = mock_rpc request = {} client.list_users(request) @@ -2145,6 +2494,7 @@ def test_list_users_use_cached_wrapped_rpc(): assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2160,12 +2510,17 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as wrapper_fn.reset_mock() # Ensure method has been cached - assert client._client._transport.list_users in client._client._transport._wrapped_methods + assert ( + client._client._transport.list_users + 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_users] = mock_rpc + client._client._transport._wrapped_methods[ + client._client._transport.list_users + ] = mock_rpc request = {} await client.list_users(request) @@ -2179,8 +2534,11 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 + @pytest.mark.asyncio -async def test_list_users_async(transport: str = 'grpc_asyncio', request_type=user.ListUsersRequest): +async def test_list_users_async( + transport: str = "grpc_asyncio", request_type=user.ListUsersRequest +): client = UserServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2191,13 +2549,13 @@ async def test_list_users_async(transport: str = 'grpc_asyncio', request_type=us request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user.ListUsersResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_users(request) # Establish that the underlying gRPC stub method was called. @@ -2208,13 +2566,14 @@ async def test_list_users_async(transport: str = 'grpc_asyncio', request_type=us # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListUsersAsyncPager) - 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_users_async_from_dict(): await test_list_users_async(request_type=dict) + def test_list_users_field_headers(): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2224,12 +2583,10 @@ def test_list_users_field_headers(): # a field header. Set these to a non-empty value. request = user.ListUsersRequest() - 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_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: call.return_value = user.ListUsersResponse() client.list_users(request) @@ -2241,9 +2598,9 @@ def test_list_users_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 @@ -2256,13 +2613,13 @@ async def test_list_users_field_headers_async(): # a field header. Set these to a non-empty value. request = user.ListUsersRequest() - 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_users), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user.ListUsersResponse() + ) await client.list_users(request) # Establish that the underlying gRPC stub method was called. @@ -2273,9 +2630,9 @@ async def test_list_users_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_users_flattened(): @@ -2284,15 +2641,13 @@ def test_list_users_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = user.ListUsersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_users( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -2300,7 +2655,7 @@ def test_list_users_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 @@ -2314,9 +2669,10 @@ def test_list_users_flattened_error(): with pytest.raises(ValueError): client.list_users( user.ListUsersRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_users_flattened_async(): client = UserServiceAsyncClient( @@ -2324,17 +2680,17 @@ async def test_list_users_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = user.ListUsersResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user.ListUsersResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_users( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -2342,9 +2698,10 @@ async def test_list_users_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_users_flattened_error_async(): client = UserServiceAsyncClient( @@ -2356,7 +2713,7 @@ async def test_list_users_flattened_error_async(): with pytest.raises(ValueError): await client.list_users( user.ListUsersRequest(), - parent='parent_value', + parent="parent_value", ) @@ -2367,9 +2724,7 @@ def test_list_users_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_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( user.ListUsersResponse( @@ -2378,17 +2733,17 @@ def test_list_users_pager(transport_name: str = "grpc"): user.User(), user.User(), ], - next_page_token='abc', + next_page_token="abc", ), user.ListUsersResponse( users=[], - next_page_token='def', + next_page_token="def", ), user.ListUsersResponse( users=[ user.User(), ], - next_page_token='ghi', + next_page_token="ghi", ), user.ListUsersResponse( users=[ @@ -2403,9 +2758,7 @@ def test_list_users_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_users(request={}, retry=retry, timeout=timeout) @@ -2415,8 +2768,9 @@ def test_list_users_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, user.User) - for i in results) + assert all(isinstance(i, user.User) for i in results) + + def test_list_users_pages(transport_name: str = "grpc"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2424,9 +2778,7 @@ def test_list_users_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_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( user.ListUsersResponse( @@ -2435,17 +2787,17 @@ def test_list_users_pages(transport_name: str = "grpc"): user.User(), user.User(), ], - next_page_token='abc', + next_page_token="abc", ), user.ListUsersResponse( users=[], - next_page_token='def', + next_page_token="def", ), user.ListUsersResponse( users=[ user.User(), ], - next_page_token='ghi', + next_page_token="ghi", ), user.ListUsersResponse( users=[ @@ -2456,9 +2808,10 @@ def test_list_users_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_users(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_users_async_pager(): client = UserServiceAsyncClient( @@ -2467,8 +2820,8 @@ async def test_list_users_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_users), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( user.ListUsersResponse( @@ -2477,17 +2830,17 @@ async def test_list_users_async_pager(): user.User(), user.User(), ], - next_page_token='abc', + next_page_token="abc", ), user.ListUsersResponse( users=[], - next_page_token='def', + next_page_token="def", ), user.ListUsersResponse( users=[ user.User(), ], - next_page_token='ghi', + next_page_token="ghi", ), user.ListUsersResponse( users=[ @@ -2497,15 +2850,16 @@ async def test_list_users_async_pager(): ), RuntimeError, ) - async_pager = await client.list_users(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_users( + 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, user.User) - for i in responses) + assert all(isinstance(i, user.User) for i in responses) @pytest.mark.asyncio @@ -2516,8 +2870,8 @@ async def test_list_users_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_users), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( user.ListUsersResponse( @@ -2526,17 +2880,17 @@ async def test_list_users_async_pages(): user.User(), user.User(), ], - next_page_token='abc', + next_page_token="abc", ), user.ListUsersResponse( users=[], - next_page_token='def', + next_page_token="def", ), user.ListUsersResponse( users=[ user.User(), ], - next_page_token='ghi', + next_page_token="ghi", ), user.ListUsersResponse( users=[ @@ -2549,11 +2903,11 @@ async def test_list_users_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_users(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 @@ -2575,7 +2929,9 @@ def test_get_user_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.get_user] = mock_rpc request = {} @@ -2598,48 +2954,51 @@ def test_get_user_rest_required_fields(request_type=user.GetUserRequest): request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_user._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_user._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 = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = user.User() # Mock the http request 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 @@ -2650,24 +3009,24 @@ def test_get_user_rest_required_fields(request_type=user.GetUserRequest): return_value = user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_user(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_get_user_rest_flattened(): @@ -2677,16 +3036,16 @@ def test_get_user_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 = user.User() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'accounts/sample1/users/sample2'} + sample_request = {"name": "accounts/sample1/users/sample2"} # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2696,7 +3055,7 @@ def test_get_user_rest_flattened(): # Convert return value to protobuf type return_value = user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2706,10 +3065,12 @@ def test_get_user_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/users/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/users/*}" % client.transport._host, args[1] + ) -def test_get_user_rest_flattened_error(transport: str = 'rest'): +def test_get_user_rest_flattened_error(transport: str = "rest"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2720,7 +3081,7 @@ def test_get_user_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_user( user.GetUserRequest(), - name='name_value', + name="name_value", ) @@ -2742,7 +3103,9 @@ def test_create_user_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.create_user] = mock_rpc request = {} @@ -2766,58 +3129,61 @@ def test_create_user_rest_required_fields(request_type=gsma_user.CreateUserReque request_init["user_id"] = "" 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 assert "userId" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_user._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "userId" in jsonified_request assert jsonified_request["userId"] == request_init["user_id"] - jsonified_request["parent"] = 'parent_value' - jsonified_request["userId"] = 'user_id_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["userId"] = "user_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_user._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("user_id", )) + assert not set(unset_fields) - set(("user_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" assert "userId" in jsonified_request - assert jsonified_request["userId"] == 'user_id_value' + assert jsonified_request["userId"] == "user_id_value" client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gsma_user.User() # Mock the http request 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() @@ -2827,7 +3193,7 @@ def test_create_user_rest_required_fields(request_type=gsma_user.CreateUserReque return_value = gsma_user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2838,17 +3204,27 @@ def test_create_user_rest_required_fields(request_type=gsma_user.CreateUserReque "userId", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(("userId", )) & set(("parent", "userId", ))) + assert set(unset_fields) == ( + set(("userId",)) + & set( + ( + "parent", + "userId", + ) + ) + ) def test_create_user_rest_flattened(): @@ -2858,18 +3234,18 @@ def test_create_user_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 = gsma_user.User() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - user=gsma_user.User(name='name_value'), - user_id='user_id_value', + parent="parent_value", + user=gsma_user.User(name="name_value"), + user_id="user_id_value", ) mock_args.update(sample_request) @@ -2879,7 +3255,7 @@ def test_create_user_rest_flattened(): # Convert return value to protobuf type return_value = gsma_user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -2889,10 +3265,12 @@ def test_create_user_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/users" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/users" % client.transport._host, args[1] + ) -def test_create_user_rest_flattened_error(transport: str = 'rest'): +def test_create_user_rest_flattened_error(transport: str = "rest"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2903,9 +3281,9 @@ def test_create_user_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_user( gsma_user.CreateUserRequest(), - parent='parent_value', - user=gsma_user.User(name='name_value'), - user_id='user_id_value', + parent="parent_value", + user=gsma_user.User(name="name_value"), + user_id="user_id_value", ) @@ -2927,7 +3305,9 @@ def test_delete_user_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc request = {} @@ -2950,73 +3330,76 @@ def test_delete_user_rest_required_fields(request_type=user.DeleteUserRequest): 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_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_user._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_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_user._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 = UserServiceClient( 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_user(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_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) def test_delete_user_rest_flattened(): @@ -3026,24 +3409,24 @@ def test_delete_user_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/users/sample2'} + sample_request = {"name": "accounts/sample1/users/sample2"} # 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"} @@ -3053,10 +3436,12 @@ def test_delete_user_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{name=accounts/*/users/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{name=accounts/*/users/*}" % client.transport._host, args[1] + ) -def test_delete_user_rest_flattened_error(transport: str = 'rest'): +def test_delete_user_rest_flattened_error(transport: str = "rest"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3067,7 +3452,7 @@ def test_delete_user_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_user( user.DeleteUserRequest(), - name='name_value', + name="name_value", ) @@ -3089,7 +3474,9 @@ def test_update_user_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.update_user] = mock_rpc request = {} @@ -3111,48 +3498,51 @@ def test_update_user_rest_required_fields(request_type=gsma_user.UpdateUserReque request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_user._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_user._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_user._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gsma_user.User() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. pb_request = request_type.pb(request) transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3162,24 +3552,24 @@ def test_update_user_rest_required_fields(request_type=gsma_user.UpdateUserReque return_value = gsma_user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_user(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_user_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_user._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("user", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("user",))) def test_update_user_rest_flattened(): @@ -3189,17 +3579,17 @@ def test_update_user_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 = gsma_user.User() # get arguments that satisfy an http rule for this method - sample_request = {'user': {'name': 'accounts/sample1/users/sample2'}} + sample_request = {"user": {"name": "accounts/sample1/users/sample2"}} # get truthy value for each flattened field mock_args = dict( - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + user=gsma_user.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -3209,7 +3599,7 @@ def test_update_user_rest_flattened(): # Convert return value to protobuf type return_value = gsma_user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3219,10 +3609,13 @@ def test_update_user_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{user.name=accounts/*/users/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{user.name=accounts/*/users/*}" % client.transport._host, + args[1], + ) -def test_update_user_rest_flattened_error(transport: str = 'rest'): +def test_update_user_rest_flattened_error(transport: str = "rest"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3233,8 +3626,8 @@ def test_update_user_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_user( gsma_user.UpdateUserRequest(), - user=gsma_user.User(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + user=gsma_user.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -3256,7 +3649,9 @@ def test_list_users_rest_use_cached_wrapped_rpc(): # Replace cached wrapped function with mock mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client._transport._wrapped_methods[client._transport.list_users] = mock_rpc request = {} @@ -3279,50 +3674,58 @@ def test_list_users_rest_required_fields(request_type=user.ListUsersRequest): 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_users._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_users._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_users._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_users._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 = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = user.ListUsersResponse() # Mock the http request 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 @@ -3333,24 +3736,32 @@ def test_list_users_rest_required_fields(request_type=user.ListUsersRequest): return_value = user.ListUsersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_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_users(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_users_rest_unset_required_fields(): - transport = transports.UserServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.UserServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_users._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_users_rest_flattened(): @@ -3360,16 +3771,16 @@ def test_list_users_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 = user.ListUsersResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'accounts/sample1'} + sample_request = {"parent": "accounts/sample1"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -3379,7 +3790,7 @@ def test_list_users_rest_flattened(): # Convert return value to protobuf type return_value = user.ListUsersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} @@ -3389,10 +3800,12 @@ def test_list_users_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/accounts/v1/{parent=accounts/*}/users" % client.transport._host, args[1]) + assert path_template.validate( + "%s/accounts/v1/{parent=accounts/*}/users" % client.transport._host, args[1] + ) -def test_list_users_rest_flattened_error(transport: str = 'rest'): +def test_list_users_rest_flattened_error(transport: str = "rest"): client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3403,20 +3816,20 @@ def test_list_users_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_users( user.ListUsersRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_users_rest_pager(transport: str = 'rest'): +def test_list_users_rest_pager(transport: str = "rest"): client = UserServiceClient( 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 = ( user.ListUsersResponse( @@ -3425,17 +3838,17 @@ def test_list_users_rest_pager(transport: str = 'rest'): user.User(), user.User(), ], - next_page_token='abc', + next_page_token="abc", ), user.ListUsersResponse( users=[], - next_page_token='def', + next_page_token="def", ), user.ListUsersResponse( users=[ user.User(), ], - next_page_token='ghi', + next_page_token="ghi", ), user.ListUsersResponse( users=[ @@ -3451,21 +3864,20 @@ def test_list_users_rest_pager(transport: str = 'rest'): response = tuple(user.ListUsersResponse.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'} + sample_request = {"parent": "accounts/sample1"} pager = client.list_users(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, user.User) - for i in results) + assert all(isinstance(i, user.User) for i in results) pages = list(client.list_users(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 @@ -3507,8 +3919,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = UserServiceClient( - 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. @@ -3530,6 +3941,7 @@ def test_transport_instance(): client = UserServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.UserServiceGrpcTransport( @@ -3544,18 +3956,23 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.UserServiceGrpcTransport, - transports.UserServiceGrpcAsyncIOTransport, - transports.UserServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.UserServiceGrpcTransport, + transports.UserServiceGrpcAsyncIOTransport, + transports.UserServiceRestTransport, + ], +) 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 = UserServiceClient.get_transport_class("grpc")( credentials=ga_credentials.AnonymousCredentials() @@ -3565,8 +3982,7 @@ def test_transport_kind_grpc(): def test_initialize_client_w_grpc(): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" ) assert client is not None @@ -3580,9 +3996,7 @@ def test_get_user_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = user.User() client.get_user(request=None) @@ -3603,9 +4017,7 @@ def test_create_user_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: call.return_value = gsma_user.User() client.create_user(request=None) @@ -3626,9 +4038,7 @@ def test_delete_user_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: call.return_value = None client.delete_user(request=None) @@ -3649,9 +4059,7 @@ def test_update_user_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: call.return_value = gsma_user.User() client.update_user(request=None) @@ -3672,9 +4080,7 @@ def test_list_users_empty_call_grpc(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: call.return_value = user.ListUsersResponse() client.list_users(request=None) @@ -3695,8 +4101,7 @@ def test_transport_kind_grpc_asyncio(): def test_initialize_client_w_grpc_asyncio(): client = UserServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" + credentials=async_anonymous_credentials(), transport="grpc_asyncio" ) assert client is not None @@ -3711,15 +4116,15 @@ async def test_get_user_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user.User( + name="name_value", + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + ) await client.get_user(request=None) # Establish that the underlying stub method was called. @@ -3740,15 +4145,15 @@ async def test_create_user_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_user.User( + name="name_value", + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + ) await client.create_user(request=None) # Establish that the underlying stub method was called. @@ -3769,9 +4174,7 @@ async def test_delete_user_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) await client.delete_user(request=None) @@ -3794,15 +4197,15 @@ async def test_update_user_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gsma_user.User( + name="name_value", + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], + ) + ) await client.update_user(request=None) # Establish that the underlying stub method was called. @@ -3823,13 +4226,13 @@ async def test_list_users_empty_call_grpc_asyncio(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user.ListUsersResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + user.ListUsersResponse( + next_page_token="next_page_token_value", + ) + ) await client.list_users(request=None) # Establish that the underlying stub method was called. @@ -3849,18 +4252,19 @@ def test_transport_kind_rest(): def test_get_user_rest_bad_request(request_type=user.GetUserRequest): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2'} + request_init = {"name": "accounts/sample1/users/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() @@ -3869,27 +4273,29 @@ def test_get_user_rest_bad_request(request_type=user.GetUserRequest): client.get_user(request) -@pytest.mark.parametrize("request_type", [ - user.GetUserRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + user.GetUserRequest, + dict, + ], +) def test_get_user_rest_call_success(request_type): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2'} + request_init = {"name": "accounts/sample1/users/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 = user.User( - name='name_value', - state=user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], + name="name_value", + state=user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], ) # Wrap the value into a proper Response obj @@ -3899,14 +4305,14 @@ def test_get_user_rest_call_success(request_type): # Convert return value to protobuf type return_value = user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_user(request) # Establish that the response is the type that we expect. assert isinstance(response, user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -3915,15 +4321,23 @@ def test_get_user_rest_call_success(request_type): def test_get_user_rest_interceptors(null_interceptor): transport = transports.UserServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.UserServiceRestInterceptor(), + ) client = UserServiceClient(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.UserServiceRestInterceptor, "post_get_user") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_get_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_get_user") 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.UserServiceRestInterceptor, "post_get_user" + ) as post, mock.patch.object( + transports.UserServiceRestInterceptor, "post_get_user_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.UserServiceRestInterceptor, "pre_get_user" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -3942,7 +4356,7 @@ def test_get_user_rest_interceptors(null_interceptor): req.return_value.content = return_value request = user.GetUserRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -3950,7 +4364,13 @@ def test_get_user_rest_interceptors(null_interceptor): post.return_value = user.User() post_with_metadata.return_value = user.User(), metadata - client.get_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_user( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -3959,18 +4379,19 @@ def test_get_user_rest_interceptors(null_interceptor): def test_create_user_rest_bad_request(request_type=gsma_user.CreateUserRequest): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -3979,19 +4400,21 @@ def test_create_user_rest_bad_request(request_type=gsma_user.CreateUserRequest): client.create_user(request) -@pytest.mark.parametrize("request_type", [ - gsma_user.CreateUserRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gsma_user.CreateUserRequest, + dict, + ], +) def test_create_user_rest_call_success(request_type): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} - request_init["user"] = {'name': 'name_value', 'state': 1, 'access_rights': [1]} + request_init = {"parent": "accounts/sample1"} + request_init["user"] = {"name": "name_value", "state": 1, "access_rights": [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 @@ -4011,7 +4434,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 @@ -4025,7 +4448,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["user"].items(): # pragma: NO COVER + for field, value in request_init["user"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4040,12 +4463,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") @@ -4058,12 +4485,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 = gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], + name="name_value", + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], ) # Wrap the value into a proper Response obj @@ -4073,14 +4500,14 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gsma_user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_user(request) # Establish that the response is the type that we expect. assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == gsma_user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -4089,15 +4516,23 @@ def get_message_fields(field): def test_create_user_rest_interceptors(null_interceptor): transport = transports.UserServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.UserServiceRestInterceptor(), + ) client = UserServiceClient(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.UserServiceRestInterceptor, "post_create_user") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_create_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_create_user") 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.UserServiceRestInterceptor, "post_create_user" + ) as post, mock.patch.object( + transports.UserServiceRestInterceptor, "post_create_user_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.UserServiceRestInterceptor, "pre_create_user" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4116,7 +4551,7 @@ def test_create_user_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gsma_user.CreateUserRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4124,7 +4559,13 @@ def test_create_user_rest_interceptors(null_interceptor): post.return_value = gsma_user.User() post_with_metadata.return_value = gsma_user.User(), metadata - client.create_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_user( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -4133,18 +4574,19 @@ def test_create_user_rest_interceptors(null_interceptor): def test_delete_user_rest_bad_request(request_type=user.DeleteUserRequest): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2'} + request_init = {"name": "accounts/sample1/users/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() @@ -4153,30 +4595,32 @@ def test_delete_user_rest_bad_request(request_type=user.DeleteUserRequest): client.delete_user(request) -@pytest.mark.parametrize("request_type", [ - user.DeleteUserRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + user.DeleteUserRequest, + dict, + ], +) def test_delete_user_rest_call_success(request_type): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'name': 'accounts/sample1/users/sample2'} + request_init = {"name": "accounts/sample1/users/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 = 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_user(request) @@ -4189,13 +4633,19 @@ def test_delete_user_rest_call_success(request_type): def test_delete_user_rest_interceptors(null_interceptor): transport = transports.UserServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.UserServiceRestInterceptor(), + ) client = UserServiceClient(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.UserServiceRestInterceptor, "pre_delete_user") 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.UserServiceRestInterceptor, "pre_delete_user" + ) as pre: pre.assert_not_called() pb_message = user.DeleteUserRequest.pb(user.DeleteUserRequest()) transcode.return_value = { @@ -4210,31 +4660,38 @@ def test_delete_user_rest_interceptors(null_interceptor): req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} request = user.DeleteUserRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - client.delete_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_user( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() def test_update_user_rest_bad_request(request_type=gsma_user.UpdateUserRequest): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'user': {'name': 'accounts/sample1/users/sample2'}} + request_init = {"user": {"name": "accounts/sample1/users/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() @@ -4243,19 +4700,25 @@ def test_update_user_rest_bad_request(request_type=gsma_user.UpdateUserRequest): client.update_user(request) -@pytest.mark.parametrize("request_type", [ - gsma_user.UpdateUserRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + gsma_user.UpdateUserRequest, + dict, + ], +) def test_update_user_rest_call_success(request_type): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'user': {'name': 'accounts/sample1/users/sample2'}} - request_init["user"] = {'name': 'accounts/sample1/users/sample2', 'state': 1, 'access_rights': [1]} + request_init = {"user": {"name": "accounts/sample1/users/sample2"}} + request_init["user"] = { + "name": "accounts/sample1/users/sample2", + "state": 1, + "access_rights": [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 @@ -4275,7 +4738,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 @@ -4289,7 +4752,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["user"].items(): # pragma: NO COVER + for field, value in request_init["user"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -4304,12 +4767,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") @@ -4322,12 +4789,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 = gsma_user.User( - name='name_value', - state=gsma_user.User.State.PENDING, - access_rights=[accessright.AccessRight.STANDARD], + name="name_value", + state=gsma_user.User.State.PENDING, + access_rights=[accessright.AccessRight.STANDARD], ) # Wrap the value into a proper Response obj @@ -4337,14 +4804,14 @@ def get_message_fields(field): # Convert return value to protobuf type return_value = gsma_user.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.update_user(request) # Establish that the response is the type that we expect. assert isinstance(response, gsma_user.User) - assert response.name == 'name_value' + assert response.name == "name_value" assert response.state == gsma_user.User.State.PENDING assert response.access_rights == [accessright.AccessRight.STANDARD] @@ -4353,15 +4820,23 @@ def get_message_fields(field): def test_update_user_rest_interceptors(null_interceptor): transport = transports.UserServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.UserServiceRestInterceptor(), + ) client = UserServiceClient(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.UserServiceRestInterceptor, "post_update_user") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_update_user_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_update_user") 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.UserServiceRestInterceptor, "post_update_user" + ) as post, mock.patch.object( + transports.UserServiceRestInterceptor, "post_update_user_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.UserServiceRestInterceptor, "pre_update_user" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4380,7 +4855,7 @@ def test_update_user_rest_interceptors(null_interceptor): req.return_value.content = return_value request = gsma_user.UpdateUserRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4388,7 +4863,13 @@ def test_update_user_rest_interceptors(null_interceptor): post.return_value = gsma_user.User() post_with_metadata.return_value = gsma_user.User(), metadata - client.update_user(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_user( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() @@ -4397,18 +4878,19 @@ def test_update_user_rest_interceptors(null_interceptor): def test_list_users_rest_bad_request(request_type=user.ListUsersRequest): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} 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() @@ -4417,25 +4899,27 @@ def test_list_users_rest_bad_request(request_type=user.ListUsersRequest): client.list_users(request) -@pytest.mark.parametrize("request_type", [ - user.ListUsersRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + user.ListUsersRequest, + dict, + ], +) def test_list_users_rest_call_success(request_type): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {'parent': 'accounts/sample1'} + request_init = {"parent": "accounts/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = user.ListUsersResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -4445,29 +4929,37 @@ def test_list_users_rest_call_success(request_type): # Convert return value to protobuf type return_value = user.ListUsersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') + response_value.content = json_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_users(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListUsersPager) - 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_users_rest_interceptors(null_interceptor): transport = transports.UserServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.UserServiceRestInterceptor(), + ) client = UserServiceClient(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.UserServiceRestInterceptor, "post_list_users") as post, \ - mock.patch.object(transports.UserServiceRestInterceptor, "post_list_users_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.UserServiceRestInterceptor, "pre_list_users") 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.UserServiceRestInterceptor, "post_list_users" + ) as post, mock.patch.object( + transports.UserServiceRestInterceptor, "post_list_users_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.UserServiceRestInterceptor, "pre_list_users" + ) as pre: pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() @@ -4486,7 +4978,7 @@ def test_list_users_rest_interceptors(null_interceptor): req.return_value.content = return_value request = user.ListUsersRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] @@ -4494,16 +4986,22 @@ def test_list_users_rest_interceptors(null_interceptor): post.return_value = user.ListUsersResponse() post_with_metadata.return_value = user.ListUsersResponse(), metadata - client.list_users(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_users( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() post_with_metadata.assert_called_once() + def test_initialize_client_w_rest(): client = UserServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) assert client is not None @@ -4517,9 +5015,7 @@ def test_get_user_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_user), - '__call__') as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: client.get_user(request=None) # Establish that the underlying stub method was called. @@ -4539,9 +5035,7 @@ def test_create_user_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_user), - '__call__') as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: client.create_user(request=None) # Establish that the underlying stub method was called. @@ -4561,9 +5055,7 @@ def test_delete_user_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_user), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: client.delete_user(request=None) # Establish that the underlying stub method was called. @@ -4583,9 +5075,7 @@ def test_update_user_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_user), - '__call__') as call: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: client.update_user(request=None) # Establish that the underlying stub method was called. @@ -4605,9 +5095,7 @@ def test_list_users_empty_call_rest(): ) # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_users), - '__call__') as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: client.list_users(request=None) # Establish that the underlying stub method was called. @@ -4628,18 +5116,21 @@ def test_transport_grpc_default(): transports.UserServiceGrpcTransport, ) + def test_user_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.UserServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_user_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceTransport.__init__') as Transport: + with mock.patch( + "google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.UserServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4648,11 +5139,11 @@ def test_user_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'get_user', - 'create_user', - 'delete_user', - 'update_user', - 'list_users', + "get_user", + "create_user", + "delete_user", + "update_user", + "list_users", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4663,7 +5154,7 @@ def test_user_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4672,25 +5163,30 @@ def test_user_service_base_transport(): def test_user_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_accounts_v1.services.user_service.transports.UserServiceTransport._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_accounts_v1.services.user_service.transports.UserServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UserServiceTransport( 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_user_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_accounts_v1.services.user_service.transports.UserServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.shopping.merchant_accounts_v1.services.user_service.transports.UserServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.UserServiceTransport() @@ -4699,14 +5195,12 @@ def test_user_service_base_transport_with_adc(): def test_user_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) UserServiceClient() 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, ) @@ -4721,12 +5215,12 @@ def test_user_service_auth_adc(): def test_user_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", ) @@ -4740,48 +5234,45 @@ def test_user_service_transport_auth_adc(transport_class): ], ) def test_user_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.UserServiceGrpcTransport, grpc_helpers), - (transports.UserServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.UserServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_user_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, @@ -4792,10 +5283,11 @@ def test_user_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize("transport_class", [transports.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) -def test_user_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [transports.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport], +) +def test_user_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -4804,7 +5296,7 @@ def test_user_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", @@ -4825,61 +5317,77 @@ def test_user_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_user_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.UserServiceRestTransport ( - 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.UserServiceRestTransport( + 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_user_service_host_no_port(transport_name): client = UserServiceClient( 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_user_service_host_with_port(transport_name): client = UserServiceClient( 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_user_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -4906,8 +5414,10 @@ def test_user_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_users._session session2 = client2.transport.list_users._session assert session1 != session2 + + def test_user_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.UserServiceGrpcTransport( @@ -4920,7 +5430,7 @@ def test_user_service_grpc_transport_channel(): def test_user_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.UserServiceGrpcAsyncIOTransport( @@ -4934,12 +5444,17 @@ def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) -def test_user_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: +@pytest.mark.parametrize( + "transport_class", + [transports.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport], +) +def test_user_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 @@ -4948,7 +5463,7 @@ def test_user_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", @@ -4978,17 +5493,20 @@ def test_user_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.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport]) -def test_user_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [transports.UserServiceGrpcTransport, transports.UserServiceGrpcAsyncIOTransport], +) +def test_user_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() @@ -5018,7 +5536,9 @@ def test_user_service_transport_channel_mtls_with_adc( def test_account_path(): account = "squid" - expected = "accounts/{account}".format(account=account, ) + expected = "accounts/{account}".format( + account=account, + ) actual = UserServiceClient.account_path(account) assert expected == actual @@ -5033,10 +5553,14 @@ def test_parse_account_path(): actual = UserServiceClient.parse_account_path(path) assert expected == actual + def test_user_path(): account = "whelk" email = "octopus" - expected = "accounts/{account}/users/{email}".format(account=account, email=email, ) + expected = "accounts/{account}/users/{email}".format( + account=account, + email=email, + ) actual = UserServiceClient.user_path(account, email) assert expected == actual @@ -5052,9 +5576,12 @@ def test_parse_user_path(): actual = UserServiceClient.parse_user_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 = UserServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -5069,9 +5596,12 @@ def test_parse_common_billing_account_path(): actual = UserServiceClient.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 = UserServiceClient.common_folder_path(folder) assert expected == actual @@ -5086,9 +5616,12 @@ def test_parse_common_folder_path(): actual = UserServiceClient.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 = UserServiceClient.common_organization_path(organization) assert expected == actual @@ -5103,9 +5636,12 @@ def test_parse_common_organization_path(): actual = UserServiceClient.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 = UserServiceClient.common_project_path(project) assert expected == actual @@ -5120,10 +5656,14 @@ def test_parse_common_project_path(): actual = UserServiceClient.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 = UserServiceClient.common_location_path(project, location) assert expected == actual @@ -5143,14 +5683,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.UserServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.UserServiceTransport, "_prep_wrapped_messages" + ) as prep: client = UserServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.UserServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.UserServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = UserServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5161,10 +5705,11 @@ def test_client_with_default_client_info(): def test_transport_close_grpc(): client = UserServiceClient( - 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() @@ -5173,10 +5718,11 @@ def test_transport_close_grpc(): @pytest.mark.asyncio async def test_transport_close_grpc_asyncio(): client = UserServiceAsyncClient( - 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() @@ -5184,10 +5730,11 @@ async def test_transport_close_grpc_asyncio(): def test_transport_close_rest(): client = UserServiceClient( - 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() @@ -5195,13 +5742,12 @@ def test_transport_close_rest(): def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = UserServiceClient( - 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: @@ -5210,10 +5756,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (UserServiceClient, transports.UserServiceGrpcTransport), - (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (UserServiceClient, transports.UserServiceGrpcTransport), + (UserServiceAsyncClient, transports.UserServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True @@ -5228,7 +5778,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,